AngularJs - 最好的方式来限制访问“登录”用户 [英] AngularJs - best way to limit access to 'logged in' users
问题描述
我挣扎与一个应用程序我创建建立一个登录系统。
I'm struggling with setting up a login system for an app i'm creating.
我能够设置Cookie当用户或退出登录的。我不认为检测每一个观点,如果用户登录是一个非常优雅的解决方案,我怕一个页面在这里,有可能漏掉(这是一个相当大的应用程序)。
I'm able to set cookies for when the user is logged in or out. I don't think that testing every view if the user is logged in is a very elegant solution, and i'm afraid a page here and there may fall through the cracks (it's a rather large app).
我想最好的办法是截获莫名其妙路由变化,并检查用户登录,否则将它们发送到登录/创建用户页面。我已经发现了几个方法,但似乎没有任何正式文件。有没有人使用这种类型的方法在现实世界的情况下,并且是才有效呢?
I'm thinking the best way would be to intercept route changes somehow and check if the user is logged in, otherwise send them to a login/create user page. I've found a few methods, but nothing seems to be officially documented. Has anyone used this type of method in a real world case, and was it effective?
我的路由文件看起来是这样的:
My route file looks like this:
'use strict';
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
// LOGIN
.when('/User/LoginUser', {templateUrl: 'views/user/login.html',controller: 'loginCtrl'})
....... more routes here.......
// DEFAULT
.otherwise({redirectTo: '/'});
}]);
任何帮助或建议,或者指向的我怎么会做这样的事情,这将是极大的AP preciated记录真实世界的例子!
Any help or suggestions, or points to documented real world examples of how I would do something like this would be greatly appreciated!
推荐答案
您可以拦截路由变化如你所说,并采取相应的行动,使用下面的示例作为基础:
You can intercept route changes as you suggested and act accordingly, using the following example as a basis:
$rootScope.$on('$routeChangeStart', function (event, next) {
var userAuthenticated = ...; /* Check if the user is logged in */
if (!userAuthenticated && !next.isLogin) {
/* You can save the user's location to take him back to the same page after he has logged-in */
$rootScope.savedLocation = $location.url();
$location.path('/User/LoginUser');
}
});
此外,添加 isLogin:真正的
来登录页面的路由定义,像这样的:
Also, add isLogin: true
to the route definition of your login page, like this:
$routeProvider
// LOGIN
.when('/User/LoginUser', {templateUrl: 'views/user/login.html',controller: 'loginCtrl', isLogin: true})
祝你的项目!
这篇关于AngularJs - 最好的方式来限制访问“登录”用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!