Ng-Idle: - The Angular “NgIdle” are used to detecting and responding to idle users and it automatically handles the Auto logout process.
Why
use Auto Logout in Angular 1 or Angular 2?
1.
A user must be logged out after 10 to
15 minutes (As per you).
2.
Every click interaction must reset
the timer.
3.
The timer must be synchronized
between tabs and so on.
4.
If users close the tab before your
timer expires, he gets logged out when he visits again.
Stayed Informed - Angular 2 auto logout!
The Example 1 - Auto logout based on idle user as,
Step 1: - First you go on Google CDN Server and download the angular.js file and angular-idle.js on your local and setup in your apps.
<script src="angular.js"></script> <script src="angular-idle.js"></script>
Step 2:-
var app = angular.module(‘myApp’, [‘ngIdle’]);
Step 3:-
app.config(["KeepaliveProvider", "IdleProvider", function (KeepaliveProvider, IdleProvider) { IdleProvider.idle(5); IdleProvider.timeout(5); KeepaliveProvider.interval(10); }]);
Step 4:-
app.run(['Idle', function (Idle) { Idle.watch(); }]);
The Example 2- Auto logout based on idle user as,
This is other way you can do it, the code sample for Auto logout based on idle user using Angular's run and watch i.e.
Step 1:-
var app = angular.module('myApp', []);
Step 2:-
app.run(function ($rootScope, $log) { var lastAccessApp = new Date(); $rootScope.$watch(function watchIdleInterval() { var date = new Date(); var nowDate = date - lastAccessApp; if (20 * 60 * 100 < nowDate) { $log.log('This is log!'); //TODO: Remove all cookies, cash form apps. //TODO: Redirect to login page. } lastAccessApp = date; }); });
I hope you are enjoying with this post! Please share with you friends. Thank you!!