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: '/'});
}]);
任何帮助或建议,或指向我将如何做这样的事情的记录在案的真实世界示例,将不胜感激!
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: true
添加到登录页面的路由定义中,如下所示:
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屋!