在Auth.login之后立即检索jhipster中的角色

时间:2015-03-27 20:11:59

标签: jhipster

我希望在登录后根据此人拥有的角色将用户发送到特定视图。例如,我想将具有ROLE_STUDENT的用户发送到学生页面,将具有ROLE_TEACHER的用户发送到教师页面。不幸的是,如果我在Auth.login之后立即在控制器中调用isInRole,那就失败了。具体来说,在登录功能(我移动到main.controller.js以便登录对话框出现在主页面上)中,我有这样的代码:

$scope.login = function () {
        Auth.login({
            username: $scope.username,
            password: $scope.password
        }).then(function (account, $state) {
            Principal.identity(true);
            $scope.authenticationError = false;
            $scope.account = account;
            $scope.isAuthenticated = Principal.isAuthenticated;
            $scope.isInRole = Principal.isInRole;
            if ($scope.isInRole('ROLE_STUDENT')) {
                $scope.state.go('student_dashboard');
            }
        }).catch(function () {
            $scope.authenticationError = true;
        });
    };

但是,isInRole方法始终返回false。如果我调试它,我可以在principal.service.js中看到,此时,_authenticated为false且_identity未定义。

现在,如果我在控制器中注释掉isInRole条件,那么用户总是转到student_dashboard页面,我可以在student_dashboard页面上放置isInRole代码,并且效果很好。因此,似乎在重定向时间和目标页面加载的时间之间发生了某些事情,我想知道这是什么,以便我可以使它发生,从而确定用户是否具有特定角色,然后适当地重定向。

1 个答案:

答案 0 :(得分:0)

我相信你的问题在于

Principal.identity(true);

这实际上返回一个承诺,它执行ajax调用来更新主体用户,因此要使用主要功能,你需要做这样的事情

Principal.identity(true).then(function(profile) {
    $scope.authenticationError = false;
    $scope.account = account;
    $scope.isAuthenticated = Principal.isAuthenticated;
    $scope.isInRole = Principal.isInRole;
    if ($scope.isInRole('ROLE_STUDENT')) {
        $scope.state.go('student_dashboard');
    }
});

否则当前身份未定义。

相关问题