javascript - AngularJS 和 Django 仅允许在用户登录时访问 Angular View

标签 javascript django angularjs routes

我正在使用 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/

相关文章:

javascript - Express 中间件在使用 postman 时不触发,但在与浏览器连接时有效

mysql - 使用 Django 将现有的 MyISAM 数据库转换为 InnoDB

Django:用于 MongoDB 的长字段 (BigIntegerField)

javascript - Angular ui网格在列中显示数组

javascript - AngularJS : Use factory inside a controller

javascript - angular.js自动完成选择选项不会触发其他模型

javascript - 更高效的 Javascript

javascript - 删除附加的内容并在单击时添加其他内容

javascript - 如何从 d3 中的数组中获取索引号?

python - 构建我的 Django 第三方应用程序的最佳方式是什么