角色 - Parse.com Javascript

Roles - Parse.com Javascript

目前我有 javascript 允许来自 (_User) table 的所有用户登录。我在角色 [=18= 中设置了一个名为 (Admins) 的角色] 并将一个用户分配给此角色。这是一个 if 语句吗?

目前用户是这样登录成功的

$scope.logIn = function(form) {
Parse.User.logIn(form.username, form.password, {
  success: function(user) {
    $scope.currentUser = user;
    $scope.$apply();
    window.location.href = "TEST.html";
  },

很容易检查任何用户是否属于某个角色。唯一棘手的部分是要意识到检查包括一个查询,因此是一个异步操作。所以首先,一个通用的角色检查函数:

function userHasRole(user, roleName) {
    var query = new Parse.Query(Parse.Role);
    query.equalTo("name", roleName);
    query.equalTo("users", user);
    return query.find().then(function(roles) {
        return roles.length > 0;
    });
}

这个 returns 一个将用布尔值实现的承诺,所以你可以这样称呼它:

var currentUser = Parse.User.current();
// is the user an "admin"?
userHasRole(currentUser, "admin").then(function(isAdmin) {
    console.log((isAdmin)? "user is admin" : "user is not admin");
});

在您的代码中像这样应用它。在视图中:

<form role="form" name="loginForm">
    <div class="form-group">
        <label>Email</label>
        <input type="email" class="form-control" name="email" ng-model="user.username" />
    </div>
    <div class="form-group">
        <label>Password</label>
        <input type="password" class="form-control" name="password" ng-model="user.password" />
    </div>
    <div class="form-group">
        <button class="btn btn-ar btn-primary" ng-click="pressedLogIn()">Log in</button>
    </div>
</form>

在控制器中:

(function() {
    'use strict';
    angular.module('myApp.controllers').controller('LogInController', LogInController);

    LogInController.$inject = ['$scope'];

    function LogInController($scope) {
        $scope.user = { username:"", password:""};

        function userHasRole(user, roleName) {
            // defined exactly as above
            // my real app has a user service, and this would be better placed there
        }

        $scope.pressedLogIn = function() {
            if ($scope.loginForm.$valid) {
                Parse.User.logIn($scope.user.username, $scope.user.password).then(function(user) {
                    $scope.user = user;
                    return userHasRole(user, "administrator");
                }).then(function(isAdmin) {
                    alert("user is admin = " + isAdmin);
                }, function(e) {
                    alert(error.message);
                });
            }
        };
    }
})();