简体   繁体   中英

Allow actions based on Meteor.user() porperties?

I want to allow adding and deleting from my Meteor collections based on a user property.

This is how I set up my admin user:

if (Meteor.isServer) {

    if (Meteor.users.find().count() === 0) {

        Accounts.createUser({
        username:'Greg',
        password:'default',
        isAdmin: 1
        });

    }

}

I now want to allow every user with isAdmin = true to create another user via Accounts.createUser:

Meteor.methods({
    makeUser: function(attributes) {
        var user = Meteor.user();
        if (user.isAdmin)
            Accounts.createUser(attributes)
        else
            console.log('User ' + user.username + ' created a player.')
    }  
})

The user is never created as if user.isAdmin never equals true. What am I doing wrong? Is this related to publishing and subscribing? At the moment I still have autopublish switched on.

Add flag isAdmin to profile object:

Accounts.createUser({
        username:'Greg',
        password:'default',
        profile:{
          isAdmin: 1
        }  
});

See docs

Accounts.createUser methods allows to add ONLY fields username , password , email and profile to user object.

Meteor.methods({
    makeUser: function(attributes) {
        var user = Meteor.user();
        if (user.profile && user.profile.isAdmin)
            Accounts.createUser(attributes)
        else
            console.log('User ' + user.username + ' created a player.')
    }  
})

Update

Consider using package roles .

In that case normal user can still call Accounts.createUser and completely bypass your makeUser to create a user, which I don't think it's what the behaviour you want to see. I would suggest wrapping Accounts.onCreateUser with the isAdmin logic from @Kuba Wyrobek:

// server side
Accounts.onCreateUser(function(options, user) {
    user.profile = options.profile ? options.profile : {};
    if (user.profile && user.profile.isAdmin) {
        return user;
    } else {
        throw new Meteor.Error(403, "Forbbiden");
    }
});

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