0
votes

Am using meteor-useraccounts and alanning:roles in my Meteor webapp. The idea is that a user can register and automatically gets assigned a role. So I was thinking of using the Accounts.onCreateUser hook, however can't get that to work.

Accounts.onCreateUser(function(options, user) {
    var user = user.user;
    var defaultRole = ['admin'];
            if (!user.roles){
                Roles.addUsersToRoles(user, defaultRole);
            }
});

I'm getting the following error message:

Exception while invoking method 'ATCreateUserServer' TypeError: Cannot read property 'roles' of undefined

Seems that the user is not known, hence undefined. Can you user Meteor-useraccounts and assign a role upon user creation.

NEW EDIT: tried a bit further and the below code is working but I'm not really in favor of using this as it is strange to add the role each time upon login of the user:

Accounts.onLogin(function(user) {
    check(user, Object);
        var user = user.user;
        var defaultRole = ['admin'];
        if (!user.roles){
            Roles.addUsersToRoles(user, defaultRole);
        }
    return user;
});
1

1 Answers

0
votes

There are always many ways to do that. On of which is to add the roles after the user is created and officially obtained a userId, like so:

var id = Accounts.createUser(
            createOptions
         );
Roles.addUsersToRoles(id, ["user","guest"]);

If you want to add roles using the hook onCreateUser you could extend the user object, like so:

Accounts.onCreateUser(function(options, user)
{
    if(!options || !user) {
        throw new Meteor.Error('Problem to create new user');
        return;
    }    
    var user_extend =
    {
       username: options.username,
       email: options.email,
       profile: options.profile,
       roles: ["user","guest"]
    };
    _.extend(user,user_extend);

    return user
}

I prefer method number one because you can decide when and where you want to at the roles to that user because you will set those roles to every user that registers on your site. I hope it helps.