Separate login auth for admin
I am successfully able to generate login for normal users. Now, I want to have same endpoint /login for my login screen for both normal user and admin. I want to create user-admin with fixed email and flexible password with the token generated will be fixed .
I am new in Node.JS backend routing.
This is my login route:-
router.post('/login' , (req, res, next) => {
User.find({email: req.body.email})
.exec()
.then(user => {
if(user.length < 1) {
return res.status(401).json({
message: "Auth failed. User not found."
})
}
bcrypt.compare(req.body.password, user[0].password, (err, result) =>{
if (err) {
return res.status(401).json({
message: "Auth failed. Check email and password"
});
}
if (result){
const token = jwt.sign(
{
email: user[0].email,
userId: user[0]._id
},
process.env.JWT_KEY,
{
expiresIn : "1h"
});
return res.status(200).json({
message: "Auth Successful",
token : token
});
}
});
})
.catch(err =>{
if (err.code == 500)
res.status(500).send(["Something went wrong in login"]);
else
return next(err);
});
});
What are the things I need to add for my admin portion ?
EDIT:-
user.model
var userSchema = new mongoose.Schema({
fullName : {
type: String,
required: "Full name can't be empty"
},
email : {
type: String,
required: "Email can't be empty",
unique: true
},
password : {
type: String,
required: "Password can't be empty",
minlength: [6 ,"Password must be atleast 6 character long"]
},
phoneNumber : {
type: String,
required: "Reqired for further contact.Can't be empty"
},
saltSecret: String
});
mongoose.model('User', userSchema);
user.controller
const mongoose = require ('mongoose');
const User = mongoose.model('User');
module.exports.register = (req, res, next) =>{
var user = new User();
user.fullName = req.body.fullName;
user.email = req.body.email;
user.password = req.body.password;
user.phoneNumber = req.body.phoneNumber;
user.save((err, doc) =>{
if(!err)
res.send(doc);
else{
if (err.code == 11000)
res.status(422).send(["Entered duplicate email address. Please check"]);
else
return next(err);
}
});
}
node.js express authentication routing
add a comment |
I am successfully able to generate login for normal users. Now, I want to have same endpoint /login for my login screen for both normal user and admin. I want to create user-admin with fixed email and flexible password with the token generated will be fixed .
I am new in Node.JS backend routing.
This is my login route:-
router.post('/login' , (req, res, next) => {
User.find({email: req.body.email})
.exec()
.then(user => {
if(user.length < 1) {
return res.status(401).json({
message: "Auth failed. User not found."
})
}
bcrypt.compare(req.body.password, user[0].password, (err, result) =>{
if (err) {
return res.status(401).json({
message: "Auth failed. Check email and password"
});
}
if (result){
const token = jwt.sign(
{
email: user[0].email,
userId: user[0]._id
},
process.env.JWT_KEY,
{
expiresIn : "1h"
});
return res.status(200).json({
message: "Auth Successful",
token : token
});
}
});
})
.catch(err =>{
if (err.code == 500)
res.status(500).send(["Something went wrong in login"]);
else
return next(err);
});
});
What are the things I need to add for my admin portion ?
EDIT:-
user.model
var userSchema = new mongoose.Schema({
fullName : {
type: String,
required: "Full name can't be empty"
},
email : {
type: String,
required: "Email can't be empty",
unique: true
},
password : {
type: String,
required: "Password can't be empty",
minlength: [6 ,"Password must be atleast 6 character long"]
},
phoneNumber : {
type: String,
required: "Reqired for further contact.Can't be empty"
},
saltSecret: String
});
mongoose.model('User', userSchema);
user.controller
const mongoose = require ('mongoose');
const User = mongoose.model('User');
module.exports.register = (req, res, next) =>{
var user = new User();
user.fullName = req.body.fullName;
user.email = req.body.email;
user.password = req.body.password;
user.phoneNumber = req.body.phoneNumber;
user.save((err, doc) =>{
if(!err)
res.send(doc);
else{
if (err.code == 11000)
res.status(422).send(["Entered duplicate email address. Please check"]);
else
return next(err);
}
});
}
node.js express authentication routing
add a comment |
I am successfully able to generate login for normal users. Now, I want to have same endpoint /login for my login screen for both normal user and admin. I want to create user-admin with fixed email and flexible password with the token generated will be fixed .
I am new in Node.JS backend routing.
This is my login route:-
router.post('/login' , (req, res, next) => {
User.find({email: req.body.email})
.exec()
.then(user => {
if(user.length < 1) {
return res.status(401).json({
message: "Auth failed. User not found."
})
}
bcrypt.compare(req.body.password, user[0].password, (err, result) =>{
if (err) {
return res.status(401).json({
message: "Auth failed. Check email and password"
});
}
if (result){
const token = jwt.sign(
{
email: user[0].email,
userId: user[0]._id
},
process.env.JWT_KEY,
{
expiresIn : "1h"
});
return res.status(200).json({
message: "Auth Successful",
token : token
});
}
});
})
.catch(err =>{
if (err.code == 500)
res.status(500).send(["Something went wrong in login"]);
else
return next(err);
});
});
What are the things I need to add for my admin portion ?
EDIT:-
user.model
var userSchema = new mongoose.Schema({
fullName : {
type: String,
required: "Full name can't be empty"
},
email : {
type: String,
required: "Email can't be empty",
unique: true
},
password : {
type: String,
required: "Password can't be empty",
minlength: [6 ,"Password must be atleast 6 character long"]
},
phoneNumber : {
type: String,
required: "Reqired for further contact.Can't be empty"
},
saltSecret: String
});
mongoose.model('User', userSchema);
user.controller
const mongoose = require ('mongoose');
const User = mongoose.model('User');
module.exports.register = (req, res, next) =>{
var user = new User();
user.fullName = req.body.fullName;
user.email = req.body.email;
user.password = req.body.password;
user.phoneNumber = req.body.phoneNumber;
user.save((err, doc) =>{
if(!err)
res.send(doc);
else{
if (err.code == 11000)
res.status(422).send(["Entered duplicate email address. Please check"]);
else
return next(err);
}
});
}
node.js express authentication routing
I am successfully able to generate login for normal users. Now, I want to have same endpoint /login for my login screen for both normal user and admin. I want to create user-admin with fixed email and flexible password with the token generated will be fixed .
I am new in Node.JS backend routing.
This is my login route:-
router.post('/login' , (req, res, next) => {
User.find({email: req.body.email})
.exec()
.then(user => {
if(user.length < 1) {
return res.status(401).json({
message: "Auth failed. User not found."
})
}
bcrypt.compare(req.body.password, user[0].password, (err, result) =>{
if (err) {
return res.status(401).json({
message: "Auth failed. Check email and password"
});
}
if (result){
const token = jwt.sign(
{
email: user[0].email,
userId: user[0]._id
},
process.env.JWT_KEY,
{
expiresIn : "1h"
});
return res.status(200).json({
message: "Auth Successful",
token : token
});
}
});
})
.catch(err =>{
if (err.code == 500)
res.status(500).send(["Something went wrong in login"]);
else
return next(err);
});
});
What are the things I need to add for my admin portion ?
EDIT:-
user.model
var userSchema = new mongoose.Schema({
fullName : {
type: String,
required: "Full name can't be empty"
},
email : {
type: String,
required: "Email can't be empty",
unique: true
},
password : {
type: String,
required: "Password can't be empty",
minlength: [6 ,"Password must be atleast 6 character long"]
},
phoneNumber : {
type: String,
required: "Reqired for further contact.Can't be empty"
},
saltSecret: String
});
mongoose.model('User', userSchema);
user.controller
const mongoose = require ('mongoose');
const User = mongoose.model('User');
module.exports.register = (req, res, next) =>{
var user = new User();
user.fullName = req.body.fullName;
user.email = req.body.email;
user.password = req.body.password;
user.phoneNumber = req.body.phoneNumber;
user.save((err, doc) =>{
if(!err)
res.send(doc);
else{
if (err.code == 11000)
res.status(422).send(["Entered duplicate email address. Please check"]);
else
return next(err);
}
});
}
node.js express authentication routing
node.js express authentication routing
edited Jan 3 at 11:00
WhoAmI
asked Jan 3 at 10:26
WhoAmIWhoAmI
13211
13211
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
You can add an additional field role to the Users collection which can contain values user or admin (Or array of values if there are more roles).
Then, when you create the JWT token, you can add the role field to it.
const token = jwt.sign(
{
email: user[0].email,
userId: user[0]._id,
role: user[0].role
},
process.env.JWT_KEY,
{
expiresIn : "1h"
});
Now, you can use this value to identify if the logged in user is admin or not.
You may need to create a new API for converting a user to admin (change the role field) or do it directly in the database depending on your requirement.
If you want to handle the admin logic entirely through code (without any modification to db) and you already know the email id of the user whom you want to assign as admin, then you can use the following logic.
const adminEmail = "admin@example.com";
const role = user[0].email===adminEmail? "admin" : "user";
const token = jwt.sign(
{
email: user[0].email,
userId: user[0]._id,
role
},
process.env.JWT_KEY,
{
expiresIn : "1h"
});
Ok got it. But I have no idea how to assign a user to admin. I don't want to use database handle directly. I need to do it from my code. I am using mongodb . I don't have any field as role inUsers.
– WhoAmI
Jan 3 at 10:43
You have to modify the code that creates a user to includerolealong with other details.
– Vivek
Jan 3 at 10:48
So in database do I need to create separate admin table ? Or I can do it in same users table ?
– WhoAmI
Jan 3 at 10:52
You don't need to create a new table. All you need to do is add a new field in existing users collection. For ordinary user, the role should be "user". For admin user, the role should be "admin".
– Vivek
Jan 3 at 10:54
But I am not hard coding any user details. I am confused in this part only as it is not hard coded. I am addinguser.modelandcontrollerin EDITS. Please check and suggest
– WhoAmI
Jan 3 at 10:57
|
show 4 more comments
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54020412%2fseparate-login-auth-for-admin%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can add an additional field role to the Users collection which can contain values user or admin (Or array of values if there are more roles).
Then, when you create the JWT token, you can add the role field to it.
const token = jwt.sign(
{
email: user[0].email,
userId: user[0]._id,
role: user[0].role
},
process.env.JWT_KEY,
{
expiresIn : "1h"
});
Now, you can use this value to identify if the logged in user is admin or not.
You may need to create a new API for converting a user to admin (change the role field) or do it directly in the database depending on your requirement.
If you want to handle the admin logic entirely through code (without any modification to db) and you already know the email id of the user whom you want to assign as admin, then you can use the following logic.
const adminEmail = "admin@example.com";
const role = user[0].email===adminEmail? "admin" : "user";
const token = jwt.sign(
{
email: user[0].email,
userId: user[0]._id,
role
},
process.env.JWT_KEY,
{
expiresIn : "1h"
});
Ok got it. But I have no idea how to assign a user to admin. I don't want to use database handle directly. I need to do it from my code. I am using mongodb . I don't have any field as role inUsers.
– WhoAmI
Jan 3 at 10:43
You have to modify the code that creates a user to includerolealong with other details.
– Vivek
Jan 3 at 10:48
So in database do I need to create separate admin table ? Or I can do it in same users table ?
– WhoAmI
Jan 3 at 10:52
You don't need to create a new table. All you need to do is add a new field in existing users collection. For ordinary user, the role should be "user". For admin user, the role should be "admin".
– Vivek
Jan 3 at 10:54
But I am not hard coding any user details. I am confused in this part only as it is not hard coded. I am addinguser.modelandcontrollerin EDITS. Please check and suggest
– WhoAmI
Jan 3 at 10:57
|
show 4 more comments
You can add an additional field role to the Users collection which can contain values user or admin (Or array of values if there are more roles).
Then, when you create the JWT token, you can add the role field to it.
const token = jwt.sign(
{
email: user[0].email,
userId: user[0]._id,
role: user[0].role
},
process.env.JWT_KEY,
{
expiresIn : "1h"
});
Now, you can use this value to identify if the logged in user is admin or not.
You may need to create a new API for converting a user to admin (change the role field) or do it directly in the database depending on your requirement.
If you want to handle the admin logic entirely through code (without any modification to db) and you already know the email id of the user whom you want to assign as admin, then you can use the following logic.
const adminEmail = "admin@example.com";
const role = user[0].email===adminEmail? "admin" : "user";
const token = jwt.sign(
{
email: user[0].email,
userId: user[0]._id,
role
},
process.env.JWT_KEY,
{
expiresIn : "1h"
});
Ok got it. But I have no idea how to assign a user to admin. I don't want to use database handle directly. I need to do it from my code. I am using mongodb . I don't have any field as role inUsers.
– WhoAmI
Jan 3 at 10:43
You have to modify the code that creates a user to includerolealong with other details.
– Vivek
Jan 3 at 10:48
So in database do I need to create separate admin table ? Or I can do it in same users table ?
– WhoAmI
Jan 3 at 10:52
You don't need to create a new table. All you need to do is add a new field in existing users collection. For ordinary user, the role should be "user". For admin user, the role should be "admin".
– Vivek
Jan 3 at 10:54
But I am not hard coding any user details. I am confused in this part only as it is not hard coded. I am addinguser.modelandcontrollerin EDITS. Please check and suggest
– WhoAmI
Jan 3 at 10:57
|
show 4 more comments
You can add an additional field role to the Users collection which can contain values user or admin (Or array of values if there are more roles).
Then, when you create the JWT token, you can add the role field to it.
const token = jwt.sign(
{
email: user[0].email,
userId: user[0]._id,
role: user[0].role
},
process.env.JWT_KEY,
{
expiresIn : "1h"
});
Now, you can use this value to identify if the logged in user is admin or not.
You may need to create a new API for converting a user to admin (change the role field) or do it directly in the database depending on your requirement.
If you want to handle the admin logic entirely through code (without any modification to db) and you already know the email id of the user whom you want to assign as admin, then you can use the following logic.
const adminEmail = "admin@example.com";
const role = user[0].email===adminEmail? "admin" : "user";
const token = jwt.sign(
{
email: user[0].email,
userId: user[0]._id,
role
},
process.env.JWT_KEY,
{
expiresIn : "1h"
});
You can add an additional field role to the Users collection which can contain values user or admin (Or array of values if there are more roles).
Then, when you create the JWT token, you can add the role field to it.
const token = jwt.sign(
{
email: user[0].email,
userId: user[0]._id,
role: user[0].role
},
process.env.JWT_KEY,
{
expiresIn : "1h"
});
Now, you can use this value to identify if the logged in user is admin or not.
You may need to create a new API for converting a user to admin (change the role field) or do it directly in the database depending on your requirement.
If you want to handle the admin logic entirely through code (without any modification to db) and you already know the email id of the user whom you want to assign as admin, then you can use the following logic.
const adminEmail = "admin@example.com";
const role = user[0].email===adminEmail? "admin" : "user";
const token = jwt.sign(
{
email: user[0].email,
userId: user[0]._id,
role
},
process.env.JWT_KEY,
{
expiresIn : "1h"
});
edited Jan 3 at 11:13
answered Jan 3 at 10:38
VivekVivek
1,33811213
1,33811213
Ok got it. But I have no idea how to assign a user to admin. I don't want to use database handle directly. I need to do it from my code. I am using mongodb . I don't have any field as role inUsers.
– WhoAmI
Jan 3 at 10:43
You have to modify the code that creates a user to includerolealong with other details.
– Vivek
Jan 3 at 10:48
So in database do I need to create separate admin table ? Or I can do it in same users table ?
– WhoAmI
Jan 3 at 10:52
You don't need to create a new table. All you need to do is add a new field in existing users collection. For ordinary user, the role should be "user". For admin user, the role should be "admin".
– Vivek
Jan 3 at 10:54
But I am not hard coding any user details. I am confused in this part only as it is not hard coded. I am addinguser.modelandcontrollerin EDITS. Please check and suggest
– WhoAmI
Jan 3 at 10:57
|
show 4 more comments
Ok got it. But I have no idea how to assign a user to admin. I don't want to use database handle directly. I need to do it from my code. I am using mongodb . I don't have any field as role inUsers.
– WhoAmI
Jan 3 at 10:43
You have to modify the code that creates a user to includerolealong with other details.
– Vivek
Jan 3 at 10:48
So in database do I need to create separate admin table ? Or I can do it in same users table ?
– WhoAmI
Jan 3 at 10:52
You don't need to create a new table. All you need to do is add a new field in existing users collection. For ordinary user, the role should be "user". For admin user, the role should be "admin".
– Vivek
Jan 3 at 10:54
But I am not hard coding any user details. I am confused in this part only as it is not hard coded. I am addinguser.modelandcontrollerin EDITS. Please check and suggest
– WhoAmI
Jan 3 at 10:57
Ok got it. But I have no idea how to assign a user to admin. I don't want to use database handle directly. I need to do it from my code. I am using mongodb . I don't have any field as role in
Users.– WhoAmI
Jan 3 at 10:43
Ok got it. But I have no idea how to assign a user to admin. I don't want to use database handle directly. I need to do it from my code. I am using mongodb . I don't have any field as role in
Users.– WhoAmI
Jan 3 at 10:43
You have to modify the code that creates a user to include
role along with other details.– Vivek
Jan 3 at 10:48
You have to modify the code that creates a user to include
role along with other details.– Vivek
Jan 3 at 10:48
So in database do I need to create separate admin table ? Or I can do it in same users table ?
– WhoAmI
Jan 3 at 10:52
So in database do I need to create separate admin table ? Or I can do it in same users table ?
– WhoAmI
Jan 3 at 10:52
You don't need to create a new table. All you need to do is add a new field in existing users collection. For ordinary user, the role should be "user". For admin user, the role should be "admin".
– Vivek
Jan 3 at 10:54
You don't need to create a new table. All you need to do is add a new field in existing users collection. For ordinary user, the role should be "user". For admin user, the role should be "admin".
– Vivek
Jan 3 at 10:54
But I am not hard coding any user details. I am confused in this part only as it is not hard coded. I am adding
user.model and controller in EDITS. Please check and suggest– WhoAmI
Jan 3 at 10:57
But I am not hard coding any user details. I am confused in this part only as it is not hard coded. I am adding
user.model and controller in EDITS. Please check and suggest– WhoAmI
Jan 3 at 10:57
|
show 4 more comments
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54020412%2fseparate-login-auth-for-admin%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown