Title: Admin registration node
Tags: node.js;mongodb;express;mongoose
Question: I'm building a blog API using node. Authentication will be using JWT with two roles: admin and user.
My question is what approach should I use to ensure that only a single admin will ever be registered in the database?
I was thinking of using the following approach:
The first user to register 'admin' as username will be the admin and all the admin privileges will be bestowed unto that user. This user will be issued a token with role set to admin in payload on registration and subsequent logins.
If another user tries to register with admin, it will not work because the database will look up admin and reject re-registering a user with that username again.
Is this approach suitable or am I overlooking any flaw that would allow a user to gain admin privilege maliciously? Is there also a better approach?

Here is the accepted answer: I would argue agains such an approach because what if the admin user is deleted from the database and server is restarted (which might happen) then the next new registered user will automatically become admin.
Next thing is that admin status should be provided by role, not username.
So what I would recommend is that, each registration can create a user with only user role, no admin can be created this way.
I would preset admin entry in the database with some default logging credentials and then allow him/her to (or force them to) change those credentials once they log into the application.
But never give registration form/code ability to (kind of randomly) create new admin user.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2018:00:07/14/18', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<node.js><mongodb><express><mongoose>', 'Title': 'Admin registration node', 'ViewCount': 557, 'id': 51342023, 'user_AboutMe': '', 'user_AccountId': 8967760.0, 'user_DisplayName': 'kasho', 'user_Reputation': 478.0, 'user_Views': 43.0, 'user_id': 6687615.0}}