Login Authentication Using Express Js involves the following steps:
Import the required models(which you have created as a schema for storing data in the database) which will be used to save data in the database along with it import the required modules instance like jwt and bcrypt.
const User = require("../models/User"); const OTP = require("../models/OTP"); const otpGenerator = require("otp-generator"); const bcrypt = require("bcrypt"); const jwt = require("jsonwebtoken");
fetch the required data from the request's body.
const {email,password} = req.body;
Validate your data
check whether the fetched data is filled or not, if the fields are filled move to the next step, else return a response mentioning "All fields are required, please try again"
if(!email || !password){ return res.status(400).json({ success:false, message:"All fields are required, please try again", }) }
Check whether user exists (i.e is the user signed up before login)
const user = await User.findOne({email}).populate("additionalDetails"); if(!user){ return res.status(400).json({ success:false, message:'Not registered user', }); }
the above block code retrieves the user's data based on the email entered while login. and check if the user is registered or not if yes it will verify the user's password(next step), else it will return an error response mentioning "you are not a registered user".
Password matching (Using bcrypt)
if(await bcrypt.compare(password, user.password)){
const payload = {
email:user.email,
id :user._id,
accountType:user.accountType,
}
const token = jwt.sign(payload, process.env.JWT_SECRET,{
expiresIn:"2h",
});
user.token = token;
user.password = undefined;
//crate cookie and send response
const option = {
expires: new Date(Date.now() + 3*24*60*60*1000),
httpOnly:true,
}
res.cookie("token",token,option).status(200).json({
success:true,
token,
user,
message:"user loggedIn successfully",
})
here we compare the password entered by the user with the password stored in the database using bcrypt.compare()
function and if the password match generate a token for that user along with a cookie and send a response.
- If the password match fails then return a response to the message
else{ return res.status(401).json({ success:false, message: "Password is incorrect", }); }