Reputation: 23
I'm a beginner in back-end development using express and mongoose.
I'm creating a blog that will only have one admin that can edit, create, delete posts. How would I handle the admin? Does it make sense to create a mongoose model just for the admin or can I have his password and username in a .env file and just make a comparison in the login route?
Is the .env file safe during production? Can a client access process.env through his browser?
Are jsonwebtokens enough for authentication or should I use passport.js?
Upvotes: 1
Views: 498
Reputation: 84
Implementing admin is pretty simple; if you already have a schema for regular users, just add a field that specifies whether they are admin or not:
const userSchema = new mongoose.Schema({
username:{
type: String,
...
},
password:{
type: String,
...
},
role: {
type: String,
default: 'user',
enum: ['admin', 'user']
}
})
Then, for all the protected routes that only admin can do (like editing, creating, etc) place a middleware function before it to check the role field on the user.
const restricted = (req, res, next) => {
if (user.role !== 'admin') { // assuming you pass user info
return res.status(403).json({
status: 'fail',
message: 'Unauthorized to access this route'
})
}
next()
}
Upvotes: 1
Reputation: 96
If your blog is only used by you, you can certainly use an env
file to store your account and password.
However, if you are going to make a "normal" application, you should create a user table in your database and use an authentication mechanism to keep your data safe.
In addition, jwt
is usually used to authenticate the RESTful interface, but there are also many other authentication methods, such as sessionid
and oauth
, you should choose the right authentication method according to your needs.
Upvotes: 0