如何隐藏与AngularJS ngView未经授权的用户模板? [英] How to hide templates with AngularJS ngView for unauthorized users?
问题描述
我有一个基本的PHP应用程序,用户登录被储存在HTTP会话。该应用程序有一个主模板,说的index.html,即切换使用ngView子认为,像这样的
I have a basic PHP app, where the user login is stored in the HTTP Session. The app has one main template, say index.html, that switch sub-view using ngView, like this
<body ng-controller='MainCtrl'>
<div ng-view></div>
</body>
现在,这个主模板可以通过基本的PHP控制保护,但我有子模板(即用户列表,添加用户,编辑用户等)是纯HTML文件,根据我的路由设置距离角度包括。
Now, this main template can be protected via basic PHP controls, but i have sub-templates (i.e. user list, add user, edit user, etc.) that are plain html files, included from angular according to my route settings.
虽然我能够检查AUTH什么关系的HTTP服务的要求,一个用户能够浏览到子模板URL和访问它。我怎么能prevent这从发生?
While i am able to check for auth what concern the request of http services, one user is able to navigate to the sub-template url and access it. How can i prevent this from happen?
推荐答案
我想创建一个服务是这样的:
I would create a service like this:
app.factory('routeAuths', [ function() {
// any path that starts with /template1 will be restricted
var routeAuths = [{
path : '/template1.*',
access : 'restricted'
}];
return {
get : function(path) {
//you can expand the matching algorithm for wildcards etc.
var routeAuth;
for ( var i = 0; i < routeAuths.length; i += 1) {
routeAuth = routeAuths[i];
var routeAuthRegex = new RegExp(routeAuth.path);
if (routeAuthRegex.test(path)) {
if (routeAuth.access === 'restricted') {
return {
access : 'restricted',
path : path
};
}
}
}
// you can also make the default 'restricted' and check only for 'allowed'
return {
access : 'allowed',
path : path
};
}
};
} ]);
和主/根控制器监听 $ locationChangeStart
事件:
And in the main/root controller listen for $locationChangeStart
events:
app.controller('AppController', ['$scope', '$route', '$routeParams', '$location', 'routeAuths',
function(scope, route, routeParams, location, routeAuths) {
scope.route = route;
scope.routeParams = routeParams;
scope.location = location;
scope.routeAuth = {
};
scope.$on('$locationChangeStart', function(event, newVal, oldVal) {
var routeAuth = routeAuths.get(location.path());
if (routeAuth.access === 'restricted') {
if (scope.routeAuth.allowed) {
event.preventDefault();
}
else {
//if the browser navigates with a direct url that is restricted
//redirect to a default
location.url('/main');
}
scope.routeAuth.restricted = routeAuth;
}
else {
scope.routeAuth.allowed = routeAuth;
scope.routeAuth.restricted = undefined;
}
});
}]);
演示
- plunker
参考
- angularjs services
- location
更新
为了充分prevent HTML模板访问那么最好在服务器上进行为好。因为如果从静态文件服务HTML服务器上的用户可以访问该文件直接例如:这样root_url /模板/ template1.html规避的角度检查器。
In order to fully prevent html template access then it's best done on the server as well. Since if you serve the html from a static folder on server a user can access the file directly ex: root_url/templates/template1.html thus circumventing the angular checker.
这篇关于如何隐藏与AngularJS ngView未经授权的用户模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!