Day 81

Authentication Basics

13 min
JavaScript 100 Days

Authentication verify karta hai ke user kaun hai. Registration (account banana), Login (identity verify karna), aur protected routes — yeh sab sikhna web development ka core hai.

Registration & Login Flow

Basic auth system.

auth.js
javascript
const bcrypt = require("bcrypt");
const User = require("../models/User");

// REGISTER
async function register(req, res) {
  const { name, email, password } = req.body;
  
  // Pehle check karo email already exist to nahi karta
  const existing = await User.findOne({ email });
  if (existing) {
    return res.status(409).json({ error: "Email already registered" });
  }
  
  // Password hash karo — NEVER store plain text!
  const hashedPassword = await bcrypt.hash(password, 12);
  
  const user = await User.create({
    name,
    email,
    password: hashedPassword
  });
  
  // Password response mein mat bhejo
  const { password: _, ...userWithoutPassword } = user.toObject();
  
  res.status(201).json({
    message: "Registration successful!",
    user: userWithoutPassword
  });
}

// LOGIN
async function login(req, res) {
  const { email, password } = req.body;
  
  // User dhundo
  const user = await User.findOne({ email });
  if (!user) {
    return res.status(401).json({ error: "Invalid credentials" }); // intentionally vague
  }
  
  // Password check karo
  const isMatch = await bcrypt.compare(password, user.password);
  if (!isMatch) {
    return res.status(401).json({ error: "Invalid credentials" });
  }
  
  res.json({ message: "Login successful!", userId: user._id });
}

🎯 Practice Challenge

Complete auth system banao — register, login, logout. Email verification aur password reset bhi add karo.