简体   繁体   中英

Parse.com: Signup user to role

How do you add a user to an existing role when they're signing up? My code below doesn't work, I don't get any errors or any prints in the logs (not sure what I'm doing wrong):

Parse.User.signUp(req.body.email, req.body.password, {
    "name": req.body.name,
    "email": req.body.email,
}, {
    success: function(user) {
        var query = new Parse.Query(Parse.Role);
        query.equalTo("name", 'Basic User');

        query.find({
            success: function(roles) {
                alert("HELLO" + roles);

                if (roles.length < 1) {
                    alert("HELLO");

                    console.log("Error Signing Up: No roles for " + signUpRoleGroup + " were found");
                } else {
                    alert("HERE");

                    roles[0].getUsers().add(user);
                    roles[0].save();
                }
            },
            error: function(error) {
                alert("Could not add users to the account " + accountName + " error: " + error.message);
            }
        });
    },
    error: function(user, error) {
        alert("Error signing up user");
    }
});

I think what's going on is the caller isn't giving this function a chance to finish saving the role. The cloud function should wait until the role is saved before invoking response.success() or error().

Here's a promise-returning rewrite of the same code. Easier on the eyes, I think, and clearer about asynch tasks done serially. This puts you in more firm control of the response.

Parse.Cloud.define("signupAsBasicUser", function(request, response) {
    signupAsBasicUser(request.params.name, request.params.password, request.params.email).then(function(user) {
        response.success(user);
    }, function(error) {
        response.error(error);
    });
});


// return a promise fulfilled with a signed-up user who is added to the 'Basic User" role
//
function signupAsBasicUser(name, password, email) {
    Parse.Cloud.useMasterKey();
    var user = new Parse.User();
    user.set("username", name);
    user.set("password", password);
    user.set("email", email);
    return user.signUp().then(function() {
        var query = new Parse.Query(Parse.Role);
        query.equalTo("name", 'Basic User');
        return query.find();
    }).then(function(roles) {
        if (roles.length < 1) return Parse.Promise.error("no such role");
        roles[0].getUsers().add(user);
        return roles[0].save();
    }).then(function() {
        return user;
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM