Hello guys i have a MERN project, in this project user will be able to register, login, and do some CRUD operations. After user login they will redirect to homepage.
All the user that register will have a User
role, the issue is i want to create role based on their email, if user login with [email protected]
that user will have role Admin
, if not the role stay the same.
The code below, i tried to find the email with regex, its working if bsi
is in the email. But if there is no bsi
in the email, its not working. I tried to find if else for this problem but icant find any. Is there a way to solve this ?
Code :
app.post("/register", async (req, res) => {
bcrypt
.hash(req.body.password, 10)
.then((hashedPassword) => {
// create a new user instance and collect the data
const user = new UserModel({
email: req.body.email,
password: hashedPassword,
role : "User"
});
// save the new user
user
.save()
// return success if the new user is added to the database successfully
.then((result) => {
res.status(201).send({
message: "User Created Successfully",
result,
});
})
// catch error if the new user wasn't added successfully to the database
.catch((error) => {
res.status(500).send({
message: "Error creating user",
error,
});
});
})
// catch error if the password hash isn't successful
.catch((e) => {
res.status(500).send({
message: "Password was not hashed successfully",
e,
});
});
});
app.post("/login", (req, res) => {
// UserModel.findOneAndUpdate({ email: req.body.email }).then((user)
UserModel.findOneAndUpdate({ email: { $regex : "bsi"} }, {$set : {"role" : "Admin"}}).then((user) => {
bcrypt.compare(req.body.password, user.password).then((passwordCheck) => {
if(!passwordCheck) {
return res.status(400).send({
message: "Passwords does not match",
error,
result,
});
}
const token = jwt.sign(
{
userId: user._id,
userEmail: user.email,
},
"RANDOM-TOKEN",
{ expiresIn: "24h" }
);
const result = {email : user.email}
req.session.email = result
const role = user.role
req.session.role = role
res.status(200).send({
message: "Login Successful",
email: user.email,
result,
role,
token
});
}).catch((error) => {
res.status(400).send({
message: "Passwords does not match",
error
});
});
}).catch((e) => {
res.status(404).send({
message: "Email not found",
e,
});
});
});