Last active
September 2, 2019 22:14
-
-
Save sean-nicholas/d48e4b2fd4016e8a9fc0bad5e348582a to your computer and use it in GitHub Desktop.
auto logout zone
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { Router } from '@angular/router'; | |
| import { AuthService } from './auth.service'; | |
| import { Injectable, NgZone } from '@angular/core'; | |
| import * as store from 'store'; | |
| const MINUTES_UNITL_AUTO_LOGOUT = 5 // in Minutes | |
| const CHECK_INTERVALL = 1000 // in ms | |
| const STORE_KEY = 'lastAction'; | |
| @Injectable() | |
| export class AutoLogoutService { | |
| constructor( | |
| private auth: AuthService, | |
| private router: Router, | |
| private ngZone: NgZone | |
| ) { | |
| this.check(); | |
| this.initListener(); | |
| this.initInterval(); | |
| } | |
| get lastAction() { | |
| return parseInt(store.get(STORE_KEY)); | |
| } | |
| set lastAction(value) { | |
| store.set(STORE_KEY, value); | |
| } | |
| initListener() { | |
| this.ngZone.runOutsideAngular(() => { | |
| document.body.addEventListener('click', () => this.reset()); | |
| }); | |
| } | |
| initInterval() { | |
| this.ngZone.runOutsideAngular(() => { | |
| setInterval(() => { | |
| this.check(); | |
| }, CHECK_INTERVALL); | |
| }) | |
| } | |
| reset() { | |
| this.lastAction = Date.now(); | |
| } | |
| check() { | |
| const now = Date.now(); | |
| const timeleft = this.lastAction + MINUTES_UNITL_AUTO_LOGOUT * 60 * 1000; | |
| const diff = timeleft - now; | |
| const isTimeout = diff < 0; | |
| this.ngZone.run(() => { | |
| if (isTimeout && this.auth.loggedIn) { | |
| console.log(`Sie wurden automatisch nach ${MINUTES_UNITL_AUTO_LOGOUT} Minuten Inaktivität ausgeloggt.`); | |
| this.auth.logout(); | |
| this.router.navigate(['login']); | |
| } | |
| }); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // app.component.ts | |
| import { AutoLogoutService } from './services/auto-logout.service'; | |
| import { Component } from '@angular/core'; | |
| @Component({ | |
| selector: 'app-root', | |
| templateUrl: './app.component.html', | |
| styleUrls: [ | |
| './app.component.scss' | |
| ] | |
| }) | |
| export class AppComponent { | |
| constructor( | |
| // Inject service | |
| private autoLogout: AutoLogoutService | |
| ) { } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment