Skip to content

rohan26ir/Backend-Auth-System

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Backend Authentication System

A comprehensive Node.js authentication system built with Express.js and MongoDB, featuring user registration, email verification, JWT-based authentication, session management, and secure logout functionality.

Features

  • User Registration: Secure user signup with email and username validation
  • Email Verification: OTP-based email verification system
  • JWT Authentication: Access and refresh token implementation
  • Session Management: Multi-device session tracking and management
  • Secure Logout: Single device and all-devices logout options
  • Password Hashing: SHA-256 password encryption
  • Email Notifications: Gmail OAuth2 integration for sending verification emails
  • Middleware Integration: Morgan logging, cookie parsing, and CORS support

Tech Stack

  • Backend Framework: Express.js
  • Database: MongoDB with Mongoose ODM
  • Authentication: JSON Web Tokens (JWT)
  • Email Service: Nodemailer with Gmail OAuth2
  • Password Hashing: Crypto (SHA-256)
  • Logging: Morgan
  • Environment Management: dotenv

Prerequisites

Before running this application, make sure you have the following installed:

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

Installation

  1. Clone the repository

    git clone <repository-url>
    cd Backend-Authentication-System
  2. Install dependencies

    npm install
  3. Set up environment variables

    • Copy the env-Demo file to .env
    • Fill in the required environment variables (see Environment Setup section)
  4. Configure MongoDB

    • Create a MongoDB Atlas cluster or use a local MongoDB instance
    • Get your connection string
  5. Set up Gmail OAuth2

    • Enable 2-factor authentication on your Gmail account
    • Generate an app password or set up OAuth2 credentials
    • Configure the Google OAuth2 settings

Environment Setup

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

MONGO_URI=mongodb+srv://<username>:<password>@cluster-url.mongodb.net/database-name
JWT_SECRET=your-super-secret-jwt-key-here
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
GOOGLE_REFRESH_TOKEN=your-google-refresh-token
GOOGLE_USER=your-gmail-address@gmail.com

MongoDB Setup

  1. Go to MongoDB Atlas
  2. Create a new project and cluster
  3. Configure database access (add username & password)
  4. Set network access (add IP: 0.0.0.0 for development)
  5. Copy the connection string and replace <username>, <password>, and <database-name>

Gmail OAuth2 Setup

  1. Go to Google Cloud Console
  2. Create a new project or select existing one
  3. Enable Gmail API
  4. Create OAuth2 credentials (Client ID and Client Secret)
  5. Generate a refresh token for your application
  6. Add your Gmail address to the GOOGLE_USER variable

Running the Application

  1. Development mode

    npm run dev
  2. Production mode

    npm start

The server will start on port 3000 by default.

API Endpoints

Authentication Routes

All routes are prefixed with /api/auth

Method Endpoint Description Auth Required
POST /register Register a new user No
POST /login User login No
GET /get-me Get current user info Yes (Access Token)
GET /refresh-token Refresh access token Yes (Refresh Token Cookie)
GET /logout Logout from current device Yes (Refresh Token Cookie)
GET /logout-all Logout from all devices Yes (Refresh Token Cookie)
GET /verify-email Verify email with OTP No

Request/Response Examples

Register User

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

{
  "username": "johndoe",
  "email": "john@example.com",
  "password": "securepassword123"
}

Response:

{
  "message": "User registered successfully",
  "user": {
    "username": "johndoe",
    "email": "john@example.com",
    "verified": false
  }
}

Login User

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

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

Response:

{
  "message": "Logged in successfully",
  "user": {
    "username": "johndoe",
    "email": "john@example.com"
  },
  "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

Verify Email

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

{
  "email": "john@example.com",
  "otp": "123456"
}

Response:

{
  "message": "Email verified successfully"
}

Database Models

User Model

{
  username: String (required, unique),
  email: String (required, unique),
  password: String (required, hashed),
  verified: Boolean (default: false)
}

Session Model

{
  user: ObjectId (ref: users),
  refreshTokenHash: String,
  ip: String,
  userAgent: String,
  revoked: Boolean (default: false),
  createdAt: Date,
  updatedAt: Date
}

OTP Model

{
  email: String,
  user: ObjectId (ref: users),
  otpHash: String,
  createdAt: Date,
  updatedAt: Date
}

Security Features

  • Password Hashing: SHA-256 encryption for passwords
  • JWT Tokens: Secure access and refresh token implementation
  • Session Tracking: IP and User-Agent logging for security
  • Token Revocation: Ability to invalidate sessions
  • OTP Verification: Time-sensitive email verification
  • HTTP-Only Cookies: Secure refresh token storage
  • CORS Protection: Configured for secure cross-origin requests

Project Structure

Backend-Authentication-System/
├── src/
│   ├── config/
│   │   ├── config.js          # Environment configuration
│   │   └── db.js              # Database connection
│   ├── controllers/
│   │   └── auth.controller.js # Authentication logic
│   ├── models/
│   │   ├── user.model.js      # User schema
│   │   ├── session.model.js   # Session schema
│   │   └── otp.model.js       # OTP schema
│   ├── routes/
│   │   └── auth.routes.js     # Authentication routes
│   ├── services/
│   │   └── email.service.js   # Email sending service
│   ├── utils/
│   │   └── utils.js           # Utility functions
│   └── app.js                 # Express app setup
├── server.js                  # Server entry point
├── package.json               # Dependencies and scripts
├── .env                       # Environment variables
├── env-Demo                   # Environment template
└── README.md                  # Project documentation

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some 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.

Support

For questions or issues, please open an issue in the GitHub repository.

About

A comprehensive Node.js authentication system built with Express.js and MongoDB, featuring user registration, email verification, JWT-based authentication, session management, and secure logout functionality.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors