Skip to content

hamidukarimi/authforge-express

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

13 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

AuthForge Express

License: MIT TypeScript Node.js

An open-source authentication backend built with Node.js, Express.js, MongoDB, and TypeScript.
It includes JWT-based authentication, refresh tokens with database sessions, role-based access control, rate limiting, and password management. Designed for real-world projects and easily extendable.


πŸ”Ή Features

  • βœ… User registration & login with hashed passwords
  • βœ… JWT authentication (access + refresh tokens)
  • βœ… Database-backed refresh tokens (sessions stored in MongoDB)
  • βœ… Role-based authorization (user & admin)
  • βœ… Password change & session invalidation
  • βœ… Logout & logout-all devices
  • βœ… Rate limiting per IP (prevents brute force login)
  • βœ… Error handling with standardized ApiError
  • βœ… Environment configuration with Zod validation
  • βœ… Fully typed with TypeScript (strict mode)
  • βœ… RESTful API design

πŸ”Ή Tech Stack

  • Node.js (v18+)
  • Express.js
  • MongoDB (local or Atlas)
  • Mongoose
  • TypeScript (strict mode)
  • Zod for environment & request validation
  • JWT for authentication
  • Bcrypt for password hashing
  • dotenv for environment variables
  • ts-node / nodemon for development

πŸ”Ή Project Structure

src/
β”œβ”€ config/
β”‚  β”œβ”€ db.ts
β”‚  └─ env.ts
β”œβ”€ controllers/
β”‚  β”œβ”€ logout.controller.ts
β”‚  β”œβ”€ refresh.controller.ts
β”‚  β”œβ”€ session.controller.ts
β”‚  └─ user.controller.ts
β”œβ”€ middlewares/
β”‚  β”œβ”€ auth.middleware.ts
β”‚  β”œβ”€ error.middleware.ts
β”‚  β”œβ”€ rateLimit.middleware.ts
β”‚  β”œβ”€ role.middleware.ts
β”‚  └─ validate.middleware.ts
β”œβ”€ models/
β”‚  β”œβ”€ Session.model.ts
β”‚  └─ User.model.ts
β”œβ”€ routes/
β”‚  β”œβ”€ admin.routes.ts
β”‚  β”œβ”€ index.ts
β”‚  β”œβ”€ logout.routes.ts
β”‚  β”œβ”€ refresh.routes.ts
β”‚  β”œβ”€ session.routes.ts
β”‚  └─ user.routes.ts
β”œβ”€ services/
β”‚  β”œβ”€ refresh.service.ts
β”‚  β”œβ”€ session.service.ts
β”‚  └─ user.service.ts
β”œβ”€ types/
β”‚  └─ express.d.ts
β”œβ”€ utils/
β”‚  β”œβ”€ ApiError.ts
β”‚  └─ jwt.ts
β”œβ”€ validators/
β”‚  β”œβ”€ session.validator.ts
β”‚  └─ user.validator.ts
β”œβ”€ app.ts
└─ server.ts

πŸ”Ή Installation

1️⃣ Clone the repository

git clone https://github.com/hamidukarimi/authforge-express.git
cd authforge-express

2️⃣ Install dependencies

npm install

3️⃣ Create .env file

You must create a .env file in the root of the project.

You can copy from .env.example:

cp .env.example .env

Or manually create one with:

PORT=5000
NODE_ENV=development
MONGO_URI=your_mongodb_uri
JWT_ACCESS_SECRET=your_access_secret
JWT_REFRESH_SECRET=your_refresh_secret
JWT_ACCESS_EXPIRES_IN=10m
JWT_REFRESH_EXPIRES_IN=7d
CLIENT_URL=http://localhost:3000

All environment variables are validated at startup using Zod. The server will not start if any required variable is missing or invalid.


πŸ”Ή Running the Server

Development mode (with nodemon + ts-node)

npm run dev

Build

npm run build

Production mode

npm start

By default, the server runs on:

http://localhost:5000

πŸ”Ή API Overview

Authentication Routes

Route Method Auth Required Description
/api/users/ POST ❌ Register a new user
/api/sessions/ POST ❌ Login user (returns access & refresh tokens)
/api/logout/ POST ❌ Logout current session
/api/logout/all POST βœ… Logout all sessions
/api/token/ POST ❌ Get new access token using refresh token
/api/users/me/password PUT βœ… Change password

Headers

Authorization: Bearer <access_token>
Content-Type: application/json

πŸ”Ή Example: Register

Request

POST /api/users/
Content-Type: application/json
{
  "name": "John Doe",
  "email": "user@example.com",
  "password": "password123"
}

Response

{
  "success": true,
  "message": "User created successfully",
  "data": {
    "user": {
      "id": "64f1a2b3c4d5e6f7g8h9",
      "name": "John Doe",
      "email": "user@example.com",
      "role": "user"
    },
    "accessToken": "eyJhbGciOiJIUzI1NiIsIn..."
  }
}

πŸ”Ή Example: Login

Request

POST /api/sessions/
Content-Type: application/json
{
  "email": "user@example.com",
  "password": "password123"
}

Response

{
  "success": true,
  "message": "Logged in successfully",
  "data": {
    "user": {
      "id": "64f1a2b3c4d5e6f7g8h9",
      "name": "John Doe",
      "email": "user@example.com",
      "role": "user"
    },
    "accessToken": "eyJhbGciOiJIUzI1NiIsIn..."
  }
}

The refresh token is stored in an httpOnly cookie automatically.


πŸ”Ή TypeScript Notes

This project uses strict TypeScript with the following key patterns:

  • Mongoose models are fully typed using IDocument, IMethods, and Model generics
  • Express Request is extended via src/types/express.d.ts to include req.user
  • JWT payloads are typed with AccessTokenPayload and RefreshTokenPayload interfaces
  • Zod schemas export inferred types (LoginInput, RegisterInput, etc.) as the single source of truth for request shapes
  • All catch blocks narrow unknown errors safely with instanceof checks

πŸ”Ή Contributing

This project is open-source.

You are welcome to fork, submit pull requests, or open issues.

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

Then open a Pull Request.


πŸ”Ή License

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


πŸ”Ή Notes

  • Easily extensible with email verification, password reset, or OAuth providers
  • Ensure environment variables are properly configured before deployment
  • Never commit JWT secrets to public repositories

⭐ Support

If you find this project useful, consider giving it a star ⭐ on GitHub.

Made with ❀️ by Hamid Karimi