【摘要】
很多时候我们登录一个网站却往往忘记注销。这种疏忽于个人而言有可能造成个人信息泄露,而对于公司单位而言却有可能被有心人趁机而入从而造成不可挽回的损失。所以就个人来说我们在上网时要注意个人信息的保护。检测上网环境的安全与否且上网结束时应及时清除能导致个人信息泄露的登录认证信息。而对于我们开发者而言,也应该设身处地为客户着想,预防可能出现的安全信息事故。本篇文章将介绍如何使用AngularJS的ng-Idle插件做一个定时自动注销功能,从而在检测到用户一段时间没操作之后自动注销网站。
【正文】
一、依赖项
使用ng-Idle需要引入如下两个文件:
二、使用方法
首先需要在你的module里注入ng-Idle,如下:
varapp = angular.module('myApp', ['ngIdle']);//将ngIdle注入myApp
app
.controller('EventsCtrl',function($scope, Idle) {
$scope.events = [];
$scope.$on('IdleStart',function() {
// the user appears to have gone idle
});
$scope.$on('IdleWarn',function(e,
countdown) {
// follows after the IdleStart event, but includes a
countdown until the user is considered timed out
// the countdown arg is the number of seconds remaining
until then.
// you can change the title or display a warning dialog
from here.
// you can let them resume their session by calling
Idle.watch()
});
$scope.$on('IdleTimeout',function() {
// the user has timed out (meaning idleDuration + timeout
has passed without any activity)
// this is where you'd log them
//用户不活跃倒计时结束时触发的方法,比如此处可注销登录。
});
$scope.$on('IdleEnd',function() {
// the user has come back from AFK and is doing stuff. if
you are warning them, you can use this to hide the dialog
//可定义用户在登出之前返回操作时触发的方法。
});
$scope.$on('Keepalive',function() {
//是用户保持活跃状态的方法。
});
})
.config(function(IdleProvider, KeepaliveProvider) {
// configure Idle settings
//单位:秒,计时多久无操作则进入timeOut倒计时。
IdleProvider.idle(5);
//单位:秒,倒计时结束之前无操作则执行设定的IdleTimeout。
IdleProvider.timeout(5);
//单位:秒,间隔多久进行一次使用户保持活跃的方法。
KeepaliveProvider.interval(2);
})
.run(function(Idle)
{
//开始侦听应用运行
Idle.watch();
});
三、效果展示
超时登出:
$rootScope.$on('IdleTimeout',function() {
/* Logout user */
alert("会话已超时");
window.location.href ='Account/SignOut';
});
倒计时状态: