我正在使用 AngularJS、django Rest 框架和 Django。我想这样做,以便匿名用户无法访问 angularjs 端的 View 。其余框架不允许匿名用户从 angularjs veiw 实际执行任何操作,但是,匿名用户仍然可以访问它,我想禁止这样做。所以基本上我想设置 django 在我的 angularjs 路由中具有的 login_required 功能。
var app = angular.module('mostAwesomeApp', ['restangular', 'ngRoute'])
app.config(function($routeProvider){
var base_dir = STATIC_URL + 'js/ng-coolest-app-ever/templates/';
$routeProvider.when('/',
{
templateUrl: base_dir + 'list.html',
controller: 'listViewCtrl'
})
.when('/edit/:pk',{
templateUrl: base_dir + 'update.html',
controller: 'editCtrl'
})
})
// any one can see this ctrl/view
app.controller('listViewCtrl', function($scope){
$scope.doSomethingAwesome = function(){//doing something awesome}
})
// only authed users should be able access this ctrl and view attached to it
app.controller('editCtrl', function($scope){
$scope.onlyAuthedUsersCanDoAndSee = function(){
// doing something awesome for authed peeps}
}
})
<div ng-app='mostAwesomeApp'>
// This is the issue. If i'm using ng-view that means I cant just do a
// Django if user.auth... statements to dictate what a anon user can or
// cannot see
<ng-view></ng-view>
</div>
所以我一直在争论的解决方案就是将用户状态传递到 JavaScript 变量中,并使其对我的所有应用程序全局化。然后只需检查 var 是否有任何需要特殊处理的应用程序。是的,它可以工作,但它看起来确实不是最优雅的。
最佳答案
您可以使用 $routeProvider 的解析方法在 View 加载之前检查登录用户。如果未经身份验证,您可以引发应用程序的另一部分监听的任意事件并将用户重定向到登录 View
$routeProvider.when('/edit/:pk',{
templateUrl: base_dir + 'update.html',
controller: `enter code here`'editCtrl',
resolve: {
currentUser: function(MyUserAuthService, $rootScope) {
var u = MyUserAuthService.getCurrentUser();
if (u === null) $rootScope.$broadcast('noauth');
return u;
}
}
})
app.run(function($rootScope, $location) {
$rootScope.$on('noauth', function() {
$location.path('/loginpage');
});
});
关于javascript - AngularJS 和 Django 仅允许在用户登录时访问 Angular View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22133507/