javascript AngularJs - 限制“登录”用户访问的最佳方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18918579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJs - best way to limit access to 'logged in' users
提问by flashpunk
I'm struggling with setting up a login system for an app i'm creating.
我正在努力为我正在创建的应用程序设置登录系统。
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).
我可以在用户登录或退出时设置 cookie。我不认为在用户登录的情况下测试每个视图是一个非常优雅的解决方案,而且我担心这里和那里的页面可能会出现裂缝(这是一个相当大的应用程序)。
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!
任何帮助或建议,或指向我将如何做这样的事情的真实世界示例的记录将不胜感激!
回答by urish
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');
}
});
Also, add isLogin: true
to the route definition of your login page, like this:
另外,添加isLogin: true
到登录页面的路由定义中,如下所示:
$routeProvider
// LOGIN
.when('/User/LoginUser', {templateUrl: 'views/user/login.html',controller: 'loginCtrl', isLogin: true})
Good luck with your project!
祝你的项目好运!
回答by Chris Russo
My opinion:
我的看法:
<?php if (!$_SESSION['user_id'] { forward(/user/access); }) ?>
and here comes your angular app...
你的角度应用来了......