检查用户是否具有角色 - 解析云代码

时间:2015-03-21 00:14:52

标签: javascript parse-platform user-roles cloud-code

编写Parse Cloud Function(使用Parse Javascript SDK),我无法检查当前用户是否具有“管理员”角色。我正在查看Role类的Web视图,并且存在名为“Admin”的角色,如果我单击“查看关系”用户,则会显示当前用户。我怀疑它应该重要,但“Admin”是唯一的角色,当前用户是唯一具有角色的用户。最后,“Admin”角色具有公共读取的ACL,因此不应导致任何问题。

代码如下:

...
var queryRole = new Parse.Query(Parse.Role);
queryRole.equalTo('name', 'Admin'); 
queryRole.equalTo("users", Parse.User.current());
queryRole.first({
    success: function(result) { // Role Object
        var role = result;
        role ? authorized = true : console.log('Shiet, user not Admin');
    },
    error: function(error) {
        console.log("Bruh, queryRole error");
    }
})
console.log('After test: Auth = ' + authorized);
if (!authorized) {
    response.error("You ain't no admin, measly user");
    return;    
}
...

这会在日志中产生以下结果:

  

测试前:Auth = false

     

测试后:Auth = false

2 个答案:

答案 0 :(得分:9)

试一试:

var authorized = false;
console.log('Before test: Auth = ' + authorized);

var queryRole = new Parse.Query(Parse.Role);
queryRole.equalTo('name', 'Admin');
queryRole.first({
    success: function(result) { // Role Object
        console.log("Okay, that's a start... in success 1 with results: " + result);

        var role = result;
        var adminRelation = new Parse.Relation(role, 'users');
        var queryAdmins = adminRelation.query();

        queryAdmins.equalTo('objectId', Parse.User.current().id);
        queryAdmins.first({
            success: function(result) {    // User Object
                var user = result;
                user ? authorized = true : console.log('Shiet, user not Admin');
            }
        });
    },
    error: function(error) {
        console.log("Bruh, can't find the Admin role");
    }
}).then(function() {
    console.log('After test: Auth = ' + authorized);
});

答案 1 :(得分:8)

我有一个更简单的解决方案,试一试:

var adminRoleQuery = new Parse.Query(Parse.Role);
adminRoleQuery.equalTo('name', 'admin');
adminRoleQuery.equalTo('users', req.user);

return adminRoleQuery.first().then(function(adminRole) {
  if (!adminRole) {
    throw new Error('Not an admin');
  }
});