Skip to content

A comprehensive, production-ready authentication system built with the MERN stack (MongoDB, Express.js, React, Node.js) featuring secure session management, email verification, password reset functionality, and modern UI/UX.

Notifications You must be signed in to change notification settings

adithpv/Mern-authentication-system

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

18 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ” MERN Authentication System

A comprehensive, production-ready authentication system built with the MERN stack (MongoDB, Express.js, React, Node.js) featuring secure session management, email verification, password reset functionality, and modern UI/UX.

πŸ“‹ Table of Contents

🎯 Overview

This authentication system implements a robust, secure authentication mechanism with the following key components:

  • Backend: Node.js/Express.js API with TypeScript
  • Frontend: React with Chakra UI and React Query
  • Database: MongoDB with Mongoose ODM
  • Authentication: JWT-based with refresh tokens
  • Email Service: Resend for email verification and password reset
  • Security: bcrypt password hashing, secure cookies, CORS protection

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Frontend      β”‚    β”‚    Backend      β”‚    β”‚    Database     β”‚
β”‚   (React)       │◄──►│   (Express)     │◄──►│   (MongoDB)     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚                       β”‚                       β”‚
         β”‚                       β”‚                       β”‚
         β–Ό                       β–Ό                       β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Chakra UI      β”‚    β”‚   JWT Tokens    β”‚    β”‚   Collections   β”‚
β”‚  React Query    β”‚    β”‚   Middleware    β”‚    β”‚   - Users       β”‚
β”‚  React Router   β”‚    β”‚   Controllers   β”‚    β”‚   - Sessions    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚   - Verificationβ”‚
                                              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

✨ Features

πŸ” Authentication Features

  • User Registration with email verification
  • Secure Login with password hashing
  • JWT-based Authentication with access and refresh tokens
  • Session Management with device tracking
  • Password Reset via email
  • Email Verification for new accounts
  • Automatic Token Refresh on frontend
  • Logout with session cleanup

πŸ›‘οΈ Security Features

  • bcrypt Password Hashing (salt rounds: 12)
  • HTTP-only Secure Cookies for token storage
  • CORS Protection with origin validation
  • Rate Limiting for password reset requests
  • Session Expiration (30 days default)
  • Token Expiration (Access: 15min, Refresh: 30 days)
  • Input Validation with Zod schemas
  • Error Handling with custom error codes

🎨 Frontend Features

  • Modern UI with Chakra UI components
  • Responsive Design for all devices
  • Real-time State Management with React Query
  • Protected Routes with authentication guards
  • Session Management UI showing active devices
  • Form Validation and error handling
  • Loading States and user feedback

πŸ› οΈ Technology Stack

Backend

  • Node.js - JavaScript runtime
  • Express.js - Web framework
  • TypeScript - Type safety
  • MongoDB - NoSQL database
  • Mongoose - ODM for MongoDB
  • JWT - JSON Web Tokens
  • bcrypt - Password hashing
  • Zod - Schema validation
  • Resend - Email service
  • Cookie-parser - Cookie handling
  • CORS - Cross-origin resource sharing

Frontend

  • React 18 - UI library
  • Vite - Build tool
  • Chakra UI - Component library
  • React Query - Data fetching
  • React Router - Client-side routing
  • Axios - HTTP client
  • Framer Motion - Animations

πŸ›οΈ System Design

Database Schema

erDiagram
    User {
        ObjectId _id PK
        String email UK
        String password
        Boolean verified
        Date createdAt
        Date updatedAt
    }

    Session {
        ObjectId _id PK
        ObjectId userId FK
        String userAgent
        Date createdAt
        Date expiresAt
    }

    VerificationCode {
        ObjectId _id PK
        ObjectId userId FK
        String type
        Date createdAt
        Date expiresAt
    }

    User ||--o{ Session : "has"
    User ||--o{ VerificationCode : "has"
Loading

Authentication Flow

sequenceDiagram
    participant U as User
    participant F as Frontend
    participant B as Backend
    participant D as Database
    participant E as Email Service

    Note over U,E: Registration Flow
    U->>F: Fill registration form
    F->>B: POST /auth/register
    B->>D: Create user & verification code
    B->>E: Send verification email
    B->>F: Return user data & tokens
    F->>U: Set cookies & redirect

    Note over U,E: Login Flow
    U->>F: Fill login form
    F->>B: POST /auth/login
    B->>D: Verify credentials
    B->>D: Create session
    B->>F: Return tokens
    F->>U: Set cookies & redirect

    Note over U,E: Protected Route Access
    U->>F: Access protected route
    F->>B: GET /user (with access token)
    B->>B: Verify JWT token
    B->>D: Get user data
    B->>F: Return user data
    F->>U: Display protected content

    Note over U,E: Token Refresh Flow
    F->>B: GET /auth/refresh (with refresh token)
    B->>B: Verify refresh token
    B->>D: Check session validity
    B->>F: Return new access token
    F->>U: Update cookies
Loading

Session Management

graph TD
    A[User Login] --> B[Create Session]
    B --> C[Generate Access Token]
    B --> D[Generate Refresh Token]
    C --> E[Set HTTP-only Cookies]
    D --> E
    E --> F[Session Active]

    F --> G{Token Expired?}
    G -->|Yes| H[Use Refresh Token]
    G -->|No| I[Continue Session]

    H --> J{Refresh Token Valid?}
    J -->|Yes| K[Generate New Access Token]
    J -->|No| L[Redirect to Login]

    K --> F
    I --> M[Session Expires in 30 Days]
    M --> N[Auto Logout]
Loading

πŸ”„ Authentication Flow

1. User Registration

  1. User fills registration form (email, password, confirm password)
  2. Frontend validates input and sends to /auth/register
  3. Backend validates data with Zod schemas
  4. Checks if email already exists
  5. Hashes password with bcrypt
  6. Creates user record in database
  7. Generates email verification code
  8. Sends verification email via Resend
  9. Creates session and generates JWT tokens
  10. Sets secure HTTP-only cookies
  11. Returns user data (without password)

2. Email Verification

  1. User clicks verification link in email
  2. Frontend extracts verification code from URL
  3. Makes request to /auth/email/verify/:code
  4. Backend validates verification code
  5. Updates user's verified status to true
  6. Deletes verification code from database
  7. Returns success message

3. User Login

  1. User enters email and password
  2. Frontend sends credentials to /auth/login
  3. Backend finds user by email
  4. Compares password hash using bcrypt
  5. Creates new session with user agent
  6. Generates access and refresh tokens
  7. Sets secure cookies
  8. Returns success message

4. Protected Route Access

  1. Frontend makes API request with access token
  2. Backend middleware validates JWT token
  3. Extracts user ID and session ID from token
  4. Checks if session exists and is valid
  5. Attaches user data to request object
  6. Allows access to protected resource

5. Token Refresh

  1. Frontend detects 401 error with InvalidAccessToken code
  2. Automatically calls /auth/refresh with refresh token
  3. Backend validates refresh token
  4. Checks session validity and expiration
  5. Generates new access token
  6. Optionally generates new refresh token if expiring soon
  7. Updates cookies and continues original request

6. Password Reset

  1. User requests password reset via email
  2. Backend validates email and creates reset code
  3. Sends password reset email with secure link
  4. User clicks link and enters new password
  5. Backend validates reset code and updates password
  6. Deletes all user sessions (force logout from all devices)
  7. Clears authentication cookies

πŸ›‘οΈ Security Features

Password Security

  • bcrypt Hashing: Passwords are hashed with bcrypt using 12 salt rounds
  • Pre-save Middleware: Automatic password hashing before saving to database
  • Password Validation: Minimum 6 characters required

Token Security

  • JWT Tokens: Access tokens (15min) and refresh tokens (30 days)
  • HTTP-only Cookies: Tokens stored in secure, HTTP-only cookies
  • SameSite Policy: Cookies set with strict same-site policy
  • Secure Flag: Cookies marked as secure in production

Session Security

  • Session Tracking: Each login creates a new session with user agent
  • Session Expiration: Sessions expire after 30 days
  • Session Management: Users can view and delete active sessions
  • Force Logout: Password reset invalidates all sessions

API Security

  • CORS Protection: Configured with specific origin and credentials
  • Input Validation: All inputs validated with Zod schemas
  • Error Handling: Custom error codes and messages
  • Rate Limiting: Password reset requests limited to prevent abuse

πŸ“š API Documentation

Authentication Endpoints

POST /auth/register

Register a new user account.

Request Body:

{
  "email": "user@example.com",
  "password": "password123",
  "confirmPassword": "password123"
}

Response:

{
  "_id": "user_id",
  "email": "user@example.com",
  "verified": false,
  "createdAt": "2024-01-01T00:00:00.000Z",
  "updatedAt": "2024-01-01T00:00:00.000Z"
}

POST /auth/login

Authenticate user and create session.

Request Body:

{
  "email": "user@example.com",
  "password": "password123"
}

Response:

{
  "message": "Login SuccessFull"
}

GET /auth/refresh

Refresh access token using refresh token.

Response:

{
  "message": "Access token refreshed"
}

GET /auth/logout

Logout user and invalidate session.

Response:

{
  "message": "Logout successfull"
}

GET /auth/email/verify/:code

Verify email address using verification code.

Response:

{
  "message": "Email was successfully verified"
}

POST /auth/password/forgot

Send password reset email.

Request Body:

{
  "email": "user@example.com"
}

Response:

{
  "message": "Password reset email send"
}

POST /auth/password/reset

Reset password using verification code.

Request Body:

{
  "password": "newpassword123",
  "verificationCode": "verification_code_id"
}

Response:

{
  "message": "Password reset successfull"
}

Protected Endpoints

GET /user

Get current user information.

Response:

{
  "_id": "user_id",
  "email": "user@example.com",
  "verified": true,
  "createdAt": "2024-01-01T00:00:00.000Z",
  "updatedAt": "2024-01-01T00:00:00.000Z"
}

GET /sessions

Get all active sessions for current user.

Response:

[
  {
    "_id": "session_id",
    "userAgent": "Mozilla/5.0...",
    "createdAt": "2024-01-01T00:00:00.000Z",
    "isCurrent": true
  }
]

DELETE /sessions/:id

Delete specific session.

Response:

{
  "message": "Session removed"
}

πŸš€ Installation & Setup

Prerequisites

  • Node.js (v18 or higher)
  • MongoDB (local or cloud)
  • Resend account for email service

Backend Setup

  1. Clone the repository
git clone <repository-url>
cd mern-authentication/backend
  1. Install dependencies
npm install
  1. Set up environment variables
cp .env.example .env
# Edit .env with your configuration
  1. Start development server
npm run dev

Frontend Setup

  1. Navigate to frontend directory
cd ../frontend
  1. Install dependencies
npm install
  1. Set up environment variables
cp .env.example .env
# Edit .env with your API URL
  1. Start development server
npm run dev

πŸ”§ Environment Variables

Backend (.env)

# Database
MONGO_URI=mongodb://localhost:27017/auth-app

# Server
NODE_ENV=development
PORT=4004
APP_ORIGIN=http://localhost:5173

# JWT Secrets
JWT_SECRET=your-super-secret-jwt-key
JWT_REFRESH_SECRET=your-super-secret-refresh-key

# Email Service (Resend)
EMAIL_SENDER=noreply@yourdomain.com
RESEND_API_KEY=your-resend-api-key

Frontend (.env)

VITE_API_URL=http://localhost:4004

πŸ’‘ Usage Examples

Frontend Authentication Hook

import useAuth from "./hooks/useAuth";

function Profile() {
  const { user, isLoading } = useAuth();

  if (isLoading) return <div>Loading...</div>;
  if (!user) return <div>Please login</div>;

  return <div>Welcome, {user.email}!</div>;
}

API Calls

import { login, register, getUser } from "./lib/api";

// Login
const handleLogin = async (email, password) => {
  try {
    await login({ email, password });
    // Redirect or update state
  } catch (error) {
    console.error("Login failed:", error);
  }
};

// Register
const handleRegister = async (email, password, confirmPassword) => {
  try {
    const user = await register({ email, password, confirmPassword });
    // Handle successful registration
  } catch (error) {
    console.error("Registration failed:", error);
  }
};

// Get user data
const { user } = useAuth();

Protected Routes

import { Navigate } from "react-router-dom";
import useAuth from "./hooks/useAuth";

function ProtectedRoute({ children }) {
  const { user, isLoading } = useAuth();

  if (isLoading) return <div>Loading...</div>;
  if (!user) return <Navigate to="/login" replace />;

  return children;
}

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the ISC License.

πŸ™ Acknowledgments


Note: This is a production-ready authentication system with comprehensive security features. Make sure to customize the environment variables and security settings according to your specific requirements before deploying to production.

About

A comprehensive, production-ready authentication system built with the MERN stack (MongoDB, Express.js, React, Node.js) featuring secure session management, email verification, password reset functionality, and modern UI/UX.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published