Chet
Chet

Reputation: 19889

How to restrict Meteor account creation to an Administrator?

This can be broken down into two parts:

1) How to specify an account as an administrator?

This is what I have going on right now and it doesn't work.

Meteor.startup(function () {
    if (Meteor.users.find().count() === 0) {
        console.log("Adding fake data");
        Accounts.createUser({username:"admin", email:"[email protected]", password:"1234", admin: true, profile:{name:"Administrator"}});
     }

The "admin" property of the user doesn't work. I'm not sure putting it in the profile is the right thing to do... Any suggestions here?

2) How can I restrict user creation to only administrators?

This is what I have going and it also doesn't work

Meteor.users.allow({
    insert: function(userId, doc) {
        // only admin and create
        return (userId && Meteor.users(userId).admin);
    },

Upvotes: 3

Views: 2091

Answers (2)

Tarang
Tarang

Reputation: 75955

You could do something like this:

Server side code:

Meteor.methods({
    createUser:function(username, email, password, name) {
        if(Meteor.user() && Meteor.user().admin === true) { //You'll have to customize this to how you want it

            return Accounts.createUser({
                       username: username,
                       email: email,
                       password: password,
                       profile: {
                           name: name
                       }
                   });
        }else{
            console.log("not logged in or not an admin");
        }
    },
    makeMeAdmin: function() {
        //You can customize this to have a password or something this is just an example
        Meteor.users.update({_id: this.userId}, {$set:{admin:true}});
    }
});

Client side code:

Make yourself admin:

Meteor.call("makeMeAdmin");

Create a user:

Meteor.call("createUser", "username", "[email protected]", "password123", "Bob Bob");

Upvotes: 3

sbking
sbking

Reputation: 7680

Check out the authorization Atmosphere plugin. It handles role-based authorization and has an example of restricting new user creation to authorized users.

Upvotes: 2

Related Questions