LoginSignup
7
7

More than 5 years have passed since last update.

ユーザにRoleを付与するBackground Jobs

Last updated at Posted at 2014-04-09

Parseで安全にユーザにRoleを付与する方法を考えた結果、
Background Jobを使えばいいんじゃないかと思ったので、メモしとく。
やってることは以下↓

  1. Role取得。存在しなければ、Role作成
  2. ユーザ取得。存在しなければ処理終了
  3. ユーザが取得できたらRoleを付与して処理終了
role_job.js
Parse.Cloud.job("addUserToRole", function(request, status) {
  Parse.Cloud.useMasterKey();
  var role;
  var query = new Parse.Query(Parse.Role);
  query.equalTo("name", "Moderator");
  query.first().then(function(adminRole) {
    if (adminRole == undefined) {
      var roleACL = new Parse.ACL();
      roleACL.setRoleReadAccess('Moderator', false);
      roleACL.setRoleWriteAccess('Moderator', false);
      return new Parse.Role("Moderator", roleACL).save();
    } else {
      return adminRole;
    }
  }).then(function(adminRole) {
    role = adminRole;
    var query = new Parse.Query(Parse.User);
    query.equalTo("username", request.params.username);
    return query.first();
  }).then(function(user) {
    if (user == undefined) {
      status.success(request.params.username + " not found");
    }
    role.getUsers().add(user);
    role.save();
  }).then(function() {
    status.success('success');
  }, function(error) {
    console.log("Failed with error: " + error.code + ":"+ error.message);
    status.error(error.message);
  });
});

そして、usernameパラメータにユーザ名を設定してBackground Jobsを実行
CloudFunctionと違ってマスターキーが必要。Parseに直接アクセスしてScheduled Jobsから実行しても良い。

curl -X POST \
  -H "X-Parse-Application-Id:アプリケーションID" \
  -H "X-Parse-Master-Key: マスターキー" \
  -H "Content-Type: application/json" \
  -d '{"username":"ユーザ名"}' \
  https://api.parse.com/1/jobs/addUserToRole
7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7