Skip to content

Instantly share code, notes, and snippets.

@sean-nicholas
Last active March 20, 2019 09:46
Show Gist options
  • Select an option

  • Save sean-nicholas/82f4dbfd52db0d88e1307c2e8d3bf445 to your computer and use it in GitHub Desktop.

Select an option

Save sean-nicholas/82f4dbfd52db0d88e1307c2e8d3bf445 to your computer and use it in GitHub Desktop.
Auto Logout
const store = require('store');
const MINUTES_UNITL_AUTO_LOGOUT = 5 // in mins
const CHECK_INTERVAL = 1000 // in ms
const STORE_KEY = 'lastAction';
class AutoLogoutService {
get lastAction() {
return parseInt(store.get(STORE_KEY));
}
set lastAction(value) {
store.set(STORE_KEY, value);
}
constructor(authService) {
this.auth = authService;
this.check();
this.initListener();
this.initInterval();
}
initListener() {
document.body.addEventListener('click', () => this.reset());
}
reset() {
this.lastAction = Date.now();
}
initInterval() {
setInterval(() => {
this.check();
}, CHECK_INTERVAL);
}
check() {
const now = Date.now();
const timeleft = this.lastAction + MINUTES_UNITL_AUTO_LOGOUT * 60 * 1000;
const diff = timeleft - now;
const isTimeout = diff < 0;
if (isTimeout && this.auth.loggedIn) {
this.auth.logout();
}
}
}
@yadav-angad
Copy link
Copy Markdown

How can I consume this logout service in my angular app?

@sean-nicholas
Copy link
Copy Markdown
Author

Sorry, I didn't get informed by github about the comments.

Consuming is easy: Just inject it into your AppComponent.

export class AppComponent {
  constructor(
    private autoLogout:AutoLogoutService
  ) { }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment