Skip to content

harshhere905/SecureAuth-API

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

14 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿ” SecureAuth API

A Production-Ready Authentication System

Node.js Express MongoDB JWT License: MIT

SecureAuth API is a robust, scalable, and production-ready authentication system built with Node.js, Express, MongoDB, and JWT. It implements industry-standard security practices including dual-token authentication, token rotation, session management, and OTP-based email verification.

Features โ€ข Architecture โ€ข Auth Flow โ€ข API Endpoints โ€ข Setup


โœจ Features

Feature Description
๐Ÿ”‘ JWT Dual-Token Auth Short-lived Access Tokens + long-lived Refresh Tokens
๐Ÿ”„ Token Rotation Refresh token rotated on every new access token request
๐Ÿ“ฑ Session Management Track & revoke sessions across all devices
๐Ÿ“ง OTP Email Verification Email verification via Nodemailer before account activation
๐Ÿ”’ Password Hashing Cryptographic hashing using bcrypt
๐Ÿช Secure Cookies HttpOnly, Secure cookies for refresh token storage
๐Ÿšช Logout Everywhere Invalidate all sessions with a single API call

๐Ÿ— Project Architecture

SecureAuth-API/
โ”‚
โ”œโ”€โ”€ config/
โ”‚   โ”œโ”€โ”€ db.js              # MongoDB connection via Mongoose
โ”‚   โ””โ”€โ”€ env.js             # Environment variable management
โ”‚
โ”œโ”€โ”€ controllers/
โ”‚   โ”œโ”€โ”€ authController.js  # Registration, Login, Logout logic
โ”‚   โ””โ”€โ”€ otpController.js   # OTP generation & verification
โ”‚
โ”œโ”€โ”€ models/
โ”‚   โ”œโ”€โ”€ User.js            # User schema & model
โ”‚   โ””โ”€โ”€ OTP.js             # OTP schema & model
โ”‚
โ”œโ”€โ”€ routes/
โ”‚   โ””โ”€โ”€ authRoutes.js      # API endpoint definitions
โ”‚
โ”œโ”€โ”€ utils/
โ”‚   โ”œโ”€โ”€ mailer.js          # Nodemailer email service
โ”‚   โ””โ”€โ”€ generateOTP.js     # OTP utility function
โ”‚
โ”œโ”€โ”€ middleware/
โ”‚   โ””โ”€โ”€ authMiddleware.js  # JWT verification middleware
โ”‚
โ”œโ”€โ”€ .env.example
โ”œโ”€โ”€ server.js
โ””โ”€โ”€ package.json

๐Ÿ”„ Authentication Flow

Auth Flow Diagram


๐Ÿ“ก API Endpoints

Auth Routes โ€” /api/auth

Method Endpoint Description Auth Required
POST /register Register a new user โŒ
POST /login Login and receive tokens โŒ
POST /verify-otp Verify email via OTP โŒ
POST /refresh Rotate tokens (get new access token) ๐Ÿช Cookie
POST /logout Logout from current device โœ…
POST /logout-all Logout from all devices โœ…

Request & Response Examples


๐Ÿ“ฎ POST /api/auth/register

Request Body:

{
  "username": "harshhere905",
  "email": "harsh@gmail.com",
  "password": "MySecurePass@123"
}

Response 201:

{
  "success": true,
  "message": "User registered. Please verify email via OTP."
}

Result:

Register API result


๐Ÿ”“ POST /api/auth/login

Request Body:

{
  "email": "harsh@example.com",
  "password": "MySecurePass@123"
}

Response 200:

{
  "success": true,
  "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "64f1a2b3c4d5e6f7a8b9c0d1",
    "username": "harshhere905",
    "email": "harsh@example.com"
  }
}

๐Ÿช Refresh token is set as HttpOnly Secure Cookie automatically.

Result:

Login API result


โœ… POST /api/auth/verify-otp

Request Body:

{
  "email": "harsh@example.com",
  "otp": "482910"
}

Response 200:

{
  "success": true,
  "message": "Email verified. Account is now active."
}

OTP Email Received:

OTP Email

API Result:

OTP Verify result


๐Ÿš€ Getting Started

Prerequisites

  • Node.js v18+
  • MongoDB Atlas account (or local MongoDB)
  • Gmail or SMTP credentials for Nodemailer

1. Clone the Repository

git clone https://github.com/harshhere905/SecureAuth-API.git
cd SecureAuth-API

2. Install Dependencies

npm install

3. Configure Environment Variables

cp .env.example .env

Edit .env with your values:

# MongoDB
MONGO_URI=mongodb+srv://<user>:<password>@cluster.mongodb.net/secureauth

# JWT
JWT_SECRET=your_jwt_secret_key
JWT_REFRESH_TOKEN=your_refresh_token_secret

# Google OAuth
CLIENT_ID=your_google_client_id
CLIENT_SECRET=your_google_client_secret

# Email (Nodemailer)
EMAIL_USER=your_email@gmail.com

4. Start the Server

# Development (with nodemon)
npm run dev

# Production
npm start

Server runs at http://localhost:3000 ๐Ÿš€


๐Ÿ”’ Security Highlights

  • Passwords are hashed with bcrypt before storage โ€” never stored in plaintext
  • Refresh tokens are stored in HttpOnly + Secure cookies, inaccessible to JavaScript
  • Token Rotation โ€” refresh token is invalidated and replaced on every use to prevent replay attacks
  • Session tracking on the server side enables instant revocation for all devices
  • OTP expiry โ€” OTPs are time-limited and single-use

๐Ÿ›  Tech Stack

Technology Purpose
Node.js Runtime environment
Express.js Web framework & routing
MongoDB + Mongoose Database & ODM
JSON Web Tokens (JWT) Stateless authentication
bcrypt Password hashing
Nodemailer OTP email delivery
cookie-parser Secure cookie handling
dotenv Environment variable management

๐Ÿ“ Environment Variables Reference

Variable Description Example
MONGO_URI MongoDB connection string mongodb+srv://...
JWT_SECRET JWT access token secret random_secret_key
JWT_REFRESH_TOKEN JWT refresh token secret another_secret_key
CLIENT_ID Google OAuth client ID xxxx.apps.googleusercontent.com
CLIENT_SECRET Google OAuth client secret GOCSPX-xxxx
EMAIL_USER SMTP email address you@gmail.com

๐Ÿค Contributing

Contributions are welcome! Please open an issue first to discuss what you'd like to change.

git checkout -b feature/your-feature-name
git commit -m "feat: add your feature"
git push origin feature/your-feature-name

๐Ÿ“„ License

This project is licensed under the MIT License โ€” see the LICENSE file for details.


Made with โค๏ธ by harshhere905

โญ Star this repo if you found it helpful! โญ

About

A production-ready authentication backend built with Node.js, Express, MongoDB, JWT, Refresh Tokens, Session Management, Email OTP Verification, and Secure Cookie-based Authentication.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors