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.
const User = require("../models/User"); const OTP = require("../models/OTP"); const otpGenerator = require("otp-generator");
Fetch data from the request's body.
const {firstName,lastName, email,password,confirmPassword, accountType,contactNumber,otp} = req.body;
Validate the Fetched Data (Check if any field is not filled)
if(!firstName || !lastName || !email || !password || !confirmPassword || !otp){ return res.status(403).json({ success:false, message:"All fields are required", }) }
if all fields are not filled properly then return a response stating all fields are required
Match the password and confirm password
if(password !== confirmPassword) { return res.status(400).json({ success:false, message:'passward and confirm password doesnot matched' }); }
if the password does not match then return the response "Password and Confirm Password does not match ".
Check if the user with same credential already exists or not.
const existingUser = await User.findOne({email})
if the user already exists then return the response "This user already exists".
if(existingUser){ return res.status(400).json({ success:false, message:'user already exist', }); }
Validate OTP
find the most recent otp related to the user
const recentOtp = await OTP.find({email}).sort({createdAt:-1}).limit(1);
validate otp
if(recentOtp .length == 0){ return res.status(400).json({ success:false, message:'OTP not Found', }); } else if(otp !== recentOtp){ return res.status(400).json({ success:false, message:'otp not matched' }); }
check that the length of OTP is zero if yes then return "otp not found"
also, check that the OTP entered is the recentOtp if not then return "otp not matched".
HASH PASSWORD
To store the password in the database we need to hash it in in order to maintain confidentiality, And from unauthorized access(if by chance anyone gets to know about your hashed password stored in Database then also your password is safe because it is hashed)
const hashedPassword = await bcrypt.hash(password, 10);
Create an entry for the particular user in the Database
const user = await User.create({ firstName, lastName, email, contactNumber, password:hashedPassword, accountType, additionalDetails:profileDetails._id, image: `https://api.dicebear.com/5.x/initials/svg?seed=${firstName} ${lastName}`, })
Create a Success Response
return res.status(200).json({ success:true, message:'User is registered Successfully', });