[英]Redirect users to login page if unauthenticated
I am using node.js restify as backend and angularjs as frontend. 我正在使用node.js restify作为后端,而angularjs作为前端。
I have a website which has 3 webpages. 我有一个包含3个网页的网站。 This is what I want. 这就是我要的。 Whenever any user visit any of these webpage, they will be redirected to a login page if they are not authenticated. 每当任何用户访问这些网页中的任何网页时,如果未通过身份验证,他们将被重定向到登录页面。
How I did was force authentication at every webpage. 我的做法是在每个网页上强制进行身份验证。 The angular controller looks like this; 角度控制器看起来像这样;
.controller('LoginAuthentication', ['$scope', '$http', 'configuration', 'dialogs',
function($scope, $http, $configuration, dialogs)
{
//alert("testing LoginAuthentication controller");
var url_check_user_logged_in = '127.0.0.1/users/check_loggedin';
$http.get(url_check_user_logged_in).success(function(data, status, headers, config)
{
if (data.LoggedInStatus === 'NotLoggedIn')
{
console.log('NotLogged');
window.location.href=$configuration.webroot + "/app/login.html";
}
else if (data.LoggedInStatus === 'LoggedIn')
{
console.log('Logged');
}
});
}])//.controller('MyCtrl1', [function()
Is there a more efficient/effective way in angularjs? angularjs中有没有更有效的方法? This approach violates the DRY (don't repeat yourself) principle because I have to repeat the same code in every webpage. 这种方法违反了DRY(不要重复自己)的原则,因为我必须在每个网页中重复相同的代码。
You could use Angular services. 您可以使用Angular服务。 Or like stated before cookies/sessions. 或像在cookie /会话之前所说的那样。
Here is a link to Angular servicesl: https://docs.angularjs.org/guide/services 这是Angular servicesl的链接: https : //docs.angularjs.org/guide/services
Add a factory first: 首先添加工厂:
angular.module("myApp").factory('LoginService',function($location){
var service={};
service.loggedIn=function(){....}
service.redirectIfNotLoggedIn=function(){
if(! service.loggedIn())$location.path("/login");
}
return service;
})
Then call LoginService.redirectIfNotLoggedIn()
to every page that you have. 然后,对您拥有的每个页面调用LoginService.redirectIfNotLoggedIn()
。 Also don't forget to complete the service.loggedIn()
method, and also to inject LoginService
to the respective Controllers
. 同样不要忘记完成service.loggedIn()
方法,并将LoginService
注入到各自的Controllers
。
The answer I gave above works for simple, plain systems. 我上面给出的答案适用于简单的简单系统。 However, I noticed that you are calling the server every time (Am I right?). 但是,我注意到您每次都在呼叫服务器(对吗?)。 If you want an asynchronous method, you can add the following to the LoginService
: 如果需要异步方法,可以将以下内容添加到LoginService
:
service.loggedIn=false;
service.asyncAuthorize=function(cb,error){
$http.get(url_check_user_logged_in).success(function(data){
if (data.LoggedInStatus === 'NotLoggedIn'){
service.loggedIn=false;
cb(false);
}else if (data.LoggedInStatus === 'LoggedIn'){
service.loggedIn=true;
cb(true);
}
}).error(function(data){
if(! error) return;
error(data);
});
}
Then you can simply call LoginService.asyncAuthorize(cb)
or LoginService.asyncAuthorize(cb,fun)
which receives a callback if the request fails. 然后,您可以简单地调用LoginService.asyncAuthorize(cb)
或LoginService.asyncAuthorize(cb,fun)
,如果请求失败LoginService.asyncAuthorize(cb,fun)
该方法将接收回调。
The cb
parameter is a function which is executed as the requests. cb
参数是作为请求执行的功能。 If the user is logged in, cb
returns true
, otherwise, false
. 如果用户已登录,则cb
返回true
,否则返回false
。 If the request fails to the server, error
is called. 如果对服务器的请求失败,则会调用error
。
Final code in the Controller: 控制器中的最终代码:
LoginService.asyncAuthorize(function(state){
console.log(state , "is the login state");
},function(e){
console.log("could not contact server");
});
put following code in loginCtrl.js 将以下代码放在loginCtrl.js中
$scope.login = function(){
if($scope.email === 'test@test.com' && $scope.password === "1234"){
$cookies.isLogin = true;
$cookies.put('isLogin', true);
$state.go('home');
}
else
$scope.error = "wrong credential";
};
Which will store the cookie 'isLogin' when the login is successful. 登录成功后,它将存储cookie'isLogin'。
And when the state is changed in app.js for $stateChangeStart function: 并且在app.js中为$ stateChangeStart函数更改状态时:
$rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
if (toState && toState.secure) {
if($cookies.get('isLogin')){
//do nothing
}else{
$state.go("login");
event.preventDefault();
}
}
if(toState.url == '/login' && $cookies.get('isLogin')) {
$state.go("home");
event.preventDefault();
}
});
So here the cookie is checked. 因此,此处检查了cookie。
I hope this works.! 我希望这可行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.