How to create first accounts user in production?

What is the best practice to create your first meteor accounts user in production right after your first deployment?

I would like to create an admin account and use that to create other users. I know how to setup the code for user creation once my admin user is logged in. But how do I get that initial user in the database?

On server startup:

If (!Meteor.users.find().count()) {
    Accounts.createUser({username:'admin', password:'admin'});
}
2 Likes

Is that recommended? I have seen examples that have your code snippet wrapped in a condition that validates the code only runs in development.

Maybe choose a better password, just in case, but I think it should be safe. Maybe someone else can give another suggestion?

1 Like

Pretty much this. Delete this code in the next deploy though.

Any updates on best practices here? It seems like a hack to add this on server startup. I’d love to use meteor shell, but that only works in development.

Nope. Still the best practice. Place it in a start-up script that only runs on the server.

Yep. I see no issue. If you have password reset setup, and use a real email, you can always reset the password right after the app boots up. Then you don’t have to hard code the real password you want.

A bit safer than checking the default password into code is to fetch the password from an environment variable which is set as part of the deploy script.

Alternatively, build on @a.com’s suggestion and hard-code the password reset email into the startup as well:

If (!Meteor.users.find().count()) {
    const userId = Accounts.createUser({
        username: 'admin', 
        email: 'some-email@example.com', 
        password: Random.secret()
    });
    Accounts.sendResetPasswordEmail(userId);
}
3 Likes

I like this idea of just sending the reset/enrollment email right away.

In our case, we set an admin email or mobile number in the private settings. When our system detects those during registration, the system automatically makes the account admin/superadmin

I know it’s been a while but if anyone is still looking for a more secure solution I use a post signup hook and alanning:roles package. Using solution below admin password is submitted via normal signup flow so should be more secure.

import { Template } from ‘meteor/templating’;
import { Roles } from ‘meteor/alanning:roles’;

var postSignUp = function(userId) {
if (!Meteor.users.find().count()) {
Roles.addUsersToRoles(userId, ‘admin’);
} else {
Roles.addUsersToRoles(userId, ‘user’);
}
};

Note, that it’s also possible to leave the Password field so the account ist invalid until the Password has been set using the link.

1 Like