Skip to content

habibcoder/mern-auth-project

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Full-Stack Authentication Project

A comprehensive full-stack authentication system built with Node.js, Express, React, and MongoDB. This project implements essential authentication features including user signup, login, email verification, and password reset functionality.

Table of Contents

Key Features

  • ✅ User Registration with Email Verification
  • ✅ User Login/Logout
  • ✅ Password Reset via Email
  • ✅ JWT-based Authentication
  • ✅ Form Validation
  • ✅ Rate Limiting
  • ✅ Protected Routes
  • ✅ Responsive UI
  • ✅ Password Strength Meter
  • ✅ Error Handling

Technology Stack

Backend

  • Node.js - JavaScript runtime environment
  • Express.js - Web application framework
  • MongoDB - NoSQL database

NPM Packages

  • Mongoose - Object Data Modeling (ODM) library
  • JWT - JSON Web Tokens for authentication
  • Bcrypt.js - Password hashing
  • Mailtrap - Email testing service
  • Dotenv - Environment variable management

Frontend

  • React - JavaScript library for building user interfaces
  • Tailwind CSS - Utility-first CSS framework

NPM Packages

  • Vite - Build tool and development server
  • Zustand - State management
  • Framer Motion - Animation library
  • React Router - Declarative routing
  • Axios - HTTP client

Folder Structure

.
├── backend/
│   ├── config/              # Configuration files
│   ├── controllers/         # Request handlers
│   ├── db/                  # Database connection
│   ├── mailtrap/            # Email templates and configuration
│   ├── middleware/          # Custom middleware
│   ├── models/              # Database models
│   ├── routes/              # API routes
│   ├── utils/               # Utility functions
│   └── index.js             # Entry point
├── frontend/
│   ├── src/
│   │   ├── components/      # Reusable UI components
│   │   ├── pages/           # Page components
│   │   ├── services/        # API service layer
│   │   ├── store/           # State management
│   │   ├── utils/           # Utility functions
│   │   ├── App.jsx          # Main app component
│   │   └── main.jsx         # Entry point
│   └── index.html           # HTML template
├── .env                     # Environment variables
└── README.md                # Project documentation

Setup Instructions

Prerequisites

  • Node.js (v14 or higher)
  • MongoDB account (MongoDB Atlas or local instance)
  • Mailtrap account for email testing

Backend Setup

  1. Clone the repository:

    git clone <repository-url>
    cd mern-auth-project
  2. Install backend dependencies:

    npm install
  3. Create a .env file in the root directory (see Environment Variables)

  4. Start the backend server:

    npm run dev

Frontend Setup

  1. Navigate to the frontend directory:

    cd frontend
  2. Install frontend dependencies:

    npm install
  3. Start the development server:

    npm run dev
  4. Open your browser and visit http://localhost:5173

Environment Variables

Create a .env file in the root directory with the following variables:

# MongoDB connection string
MONGO_URI=your_mongodb_connection_string

# Server port
PORT=5000

# JWT secret key (use a strong random string)
JWT_SECRET=your_jwt_secret_key

# Node environment
NODE_ENV=development

# Mailtrap token for email testing
MAILTRAP_TOKEN=your_mailtrap_token

# Client URL for CORS and email links
CLIENT_URI=http://localhost:5173

Environment Variable Descriptions

Variable Description Required
MONGO_URI MongoDB connection string
PORT Server port number
JWT_SECRET Secret key for JWT token signing
NODE_ENV Node environment (development/production)
MAILTRAP_TOKEN Mailtrap API token for email testing
CLIENT_URI Frontend application URL

API Endpoints Overview

The authentication system consists of 7 core endpoints that manage the complete user authentication lifecycle:

1. User Signup (POST /api/auth/signup)

Purpose: Registers a new user in the system
Authentication Required: No
Flow:

  • Accepts user details (name, email, password)
  • Validates that all fields are provided and meet requirements
  • Checks if user already exists
  • Hashes the password using bcrypt
  • Generates a verification token for email confirmation
  • Saves user to MongoDB database
  • Sends verification email to user
  • Creates JWT token and sets it in an HTTP-only cookie
  • Returns success response with user data (excluding password)

2. User Login (POST /api/auth/login)

Purpose: Authenticates existing users and establishes a session
Authentication Required: No
Flow:

  • Validates email and password are provided
  • Finds user by email in database
  • Compares provided password with hashed password using bcrypt
  • If valid, generates JWT token and sets it in HTTP-only cookie
  • Updates user's lastLogin timestamp
  • Returns success response with user data

3. User Logout (POST /api/auth/logout)

Purpose: Terminates user session
Authentication Required: No
Flow:

  • Clears the JWT token cookie
  • Returns success message

4. Check Authentication (GET /api/auth/check-auth)

Purpose: Verifies if a user is currently authenticated
Authentication Required: Yes (requires valid JWT token)
Flow:

  • Middleware verifies JWT token from cookie
  • Finds user by ID (from token) in database
  • Returns user data if found, otherwise returns error

5. Email Verification (POST /api/auth/verify-email)

Purpose: Confirms user's email address
Authentication Required: No
Flow:

  • Accepts verification code from user
  • Finds user by verification token that hasn't expired
  • If valid, marks user as verified and removes verification token
  • Sends welcome email to user
  • Returns success response

6. Forgot Password (POST /api/auth/forgot-password)

Purpose: Initiates password reset process
Authentication Required: No
Flow:

  • Accepts user's email address
  • Finds user by email in database
  • Generates secure reset token and expiration time
  • Saves token and expiration to user document
  • Sends password reset email with token link
  • Returns success message

7. Reset Password (POST /api/auth/reset-password/:token)

Purpose: Allows user to set a new password using reset token
Authentication Required: No
Flow:

  • Accepts reset token (in URL) and new password
  • Finds user by reset token that hasn't expired
  • If valid, hashes new password and updates user document
  • Removes reset token and expiration from user document
  • Sends password reset success email
  • Returns success message

Request/Response Examples

Signup

POST /api/auth/signup
Content-Type: application/json

{
  "name": "John Doe",
  "email": "john@example.com",
  "password": "SecurePassword123"
}

Login

POST /api/auth/login
Content-Type: application/json

{
  "email": "john@example.com",
  "password": "SecurePassword123"
}

Verify Email

POST /api/auth/verify-email
Content-Type: application/json

{
  "code": "123456"
}

Authentication Flow Overview

These endpoints work together to provide a complete authentication experience:

  • Registration Flow: User signs up → Receives verification email → Verifies email → Automatically logged in
  • Login Flow: User provides credentials → System validates → JWT cookie set → User authenticated
  • Password Reset Flow: User requests reset → Receives email → Clicks link → Sets new password
  • Session Management: Check-auth endpoint validates active sessions → Logout endpoint terminates sessions

📧 Mailtrap Free Plan Note

This project uses Mailtrap for testing email functionality (such as email verification and password reset).

⚠️ Important:

If you're using the Mailtrap Free Plan, emails can only be sent to the email address registered with your Mailtrap account. To send emails to other addresses, you’ll need to upgrade to a paid Mailtrap plan that supports external recipients. This configuration is perfectly fine for personal projects, testing, and local development.

🛡️ Security Best Practices

1. Password Security

  • Passwords are hashed using bcrypt.js with a salt rounds of 10
  • Minimum password length of 8 characters required
  • Password complexity validation (uppercase, lowercase, number)

2. JWT Token Security

  • Secure JWT secret management
  • HttpOnly cookies to prevent XSS attacks
  • SameSite attribute set to 'strict' to prevent CSRF attacks
  • Token expiration of 7 days

3. Input Validation

  • Server-side validation using express-validator
  • Email format validation
  • Name length validation (2-50 characters)
  • Password strength validation

4. Rate Limiting

  • Rate limiting implemented to prevent brute force attacks
  • Different limits for authentication endpoints:
    • 5 requests per 15 minutes for signup/login
    • 3 requests per 15 minutes for password reset

5. CORS Configuration

  • Restricted CORS to only allow requests from the client URI
  • Credentials enabled for secure cookie transmission

6. Environment Variables

  • Sensitive data stored in environment variables
  • Validation of required environment variables at startup

7. Error Handling

  • Centralized error handling middleware
  • Specific error messages for different error types
  • Stack trace logging for debugging (in development only)

8. Database Security

  • Mongoose schema validation
  • Indexes for improved query performance
  • Automatic removal of sensitive data from responses

🌟 Future Features

Planned improvements and upcoming features include:

  • 🔐 OAuth Login (Google, GitHub, etc.)
  • 📱 Two-Factor Authentication (2FA) via Email or Authenticator App
  • 📊 Admin Dashboard for managing users and roles
  • 📅 Session Management and device tracking
  • 🕵️ Account Activity Logs (login history, IP tracking)
  • 🌍 Multi-language Support (i18n)
  • 💬 Email Templates with Dynamic Content
  • 📦 Docker Support for easier deployment
  • 🧪 Unit and Integration Tests (Jest + Supertest)

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.


Built with ❤️ for educational purposes

About

A comprehensive full-stack authentication system built with Node.js, Express, React, and MongoDB. This project implements essential authentication features including user signup, login, email verification, and password reset functionality.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages