How user registration and login works?

✅1.User Registration: How Data is Saved in DB

🔹 Frontend (e.g., React Form)

The user fills a registration form:

{
  name: "Avinash",
  email: "avi@example.com",
  password: "MySecurePassword123"
}

🔹 Backend (Node.js + Express example)

  1. Receive form data in an API endpoint:

app.post("/register", async (req, res) => {
  const { name, email, password } = req.body;
  ...
});
  1. Check if user already exists:

const existingUser = await User.findOne({ email });
if (existingUser) {
  return res.status(400).json({ message: "User already exists" });
}
  1. Hash the password using bcrypt:

const bcrypt = require("bcrypt");
const saltRounds = 10;
const hashedPassword = await bcrypt.hash(password, saltRounds);
  1. Save the user in the database (MongoDB):

const newUser = new User({ name, email, password: hashedPassword });
await newUser.save();
res.status(201).json({ message: "User registered successfully" });

✅ 🔐 Result:

Only the hashed version of the password is saved in the database:

{
  "_id": "12345",
  "name": "Avinash",
  "email": "avi@example.com",
  "password": "$2b$10$eJx12345fK...encryptedHash"
}

2. User Login: How Identity is Verified

🔹 Frontend:

User submits login form:

{
  email: "avi@example.com",
  password: "MySecurePassword123"
}

🔹 Backend:

  1. Find user by email:

const user = await User.findOne({ email });
if (!user) {
  return res.status(401).json({ message: "Invalid credentials" });
}
  1. Compare entered password with hashed one:

const isMatch = await bcrypt.compare(req.body.password, user.password);
if (!isMatch) {
  return res.status(401).json({ message: "Invalid credentials" });
}
  1. Create a session or JWT (JSON Web Token):

const jwt = require("jsonwebtoken");
const token = jwt.sign({ id: user._id }, "your_jwt_secret", { expiresIn: "1d" });
res.json({ message: "Login successful", token });

3. What Happens Behind the Scenes

Step Purpose
Hashing Irreversibly encrypts the password, making it unreadable. Even if database is hacked, attacker can't get real passwords.
Salting Adds random characters to the password before hashing, to prevent dictionary and rainbow table attacks.
JWT Token Used to authenticate the user in future requests, proving identity without saving sessions on the server.
Token Verification Every protected API checks token validity before responding to the user.

✅ Example MongoDB User Record:

{
  "_id": "64a123456789",
  "name": "Avinash",
  "email": "avi@example.com",
  "password": "$2b$10$aGjDqrGrV2ZhRjeqxkYMEuX/9QKv.aa5kIvga4X0fJtVSkRz.kPu6"
}

🔐 Summary:

Feature Description
Hashing Password is hashed using bcrypt, never stored in plain text.
Verification On login, bcrypt compares hash of input password with stored one.
JWT or Sessions Authenticated users receive a token to access protected resources.


User Registration and Login Flow

 User Registration : 
Through frontend like register page collect the data like the name/username, email, password

eg: 

{

  name: "Avinash",

  email: "avi@example.com",

  password: "MySecurePassword123"

}

user fill these all data and hit on the submit buttom.
Then through the regsiter api it reach to the backend part 
where controller already write what to do when user send these api request 
ex:
app.post("/register", async (req, res) => {
  const { name, email, password } = req.body;
  ...
});

and also check or validate the user register is already register or not 
for this we handle from this
const existingUser = await User.findOne({ email });
if (existingUser) {
  return res.status(400).json({ message: "User already exists" });
}

if new user then first bcrypt the password of user 1st
ex:
const bcrypt = require("bcrypt");
const saltRounds = 10;
const hashedPassword = await bcrypt.hash(password, saltRounds);

https://unhealthyirreparable.com/cit2c8ca?key=7566cfdb82de49ba4912160b26b7621f
after this user need to save in the database for the future login
ex:
const newUser = new User({ name, email, password: hashedPassword });
await newUser.save();
res.status(201).json({ message: "User registered successfully" });

now save data in database is like
{
  "_id": "12345",
  "name": "Avinash",
  "email": "avi@example.com",
  "password": "$2b$10$eJx12345fK...encryptedHash"
}

now user has to login 
Through the frontend part login with email id , password
ex:
{
  email: "avi@example.com",
  password: "MySecurePassword123"
}

and hit login button the through api this data reach to the backend part
where find is user present through the email id
ex:
const user = await User.findOne({ email });
if (!user) {
  return res.status(401).json({ message: "Invalid credentials" });
}

ones the find the user then create session which help the user to authetication in future requests
example;
{
  "_id": "64a123456789",
  "name": "Avinash",
  "email": "avi@example.com",
  "password": "$2b$10$aGjDqrGrV2ZhRjeqxkYMEuX/9QKv.aa5kIvga4X0fJtVSkRz.kPu6"
}




🌍 Explore Our Projects

Project Link
🎬 Telegram Bot https://tpi.li/nXPuWjXk
🍿 Movie Website https://cine-link-hub.vercel.app/
📝 Blogging Platform https://studio--blogger-showcase.us-central1.hosted.app/
💍 ShaadiCraft Page ShaadiCraft

Comments

Popular posts from this blog

How to Upload Your Local Project to GitHub Properly

YouTube Videos, Translation, AI Tools Aur Hindi Mein Dekhne Ka Experience

How to Build a Telegram Bot Using Node.js – Step-by-Step Guide