Skip to content

About

Production-ready Authentication & Authorization REST API built with Node.js, Express, TypeScript, and MongoDB — featuring JWT auth, role-based access control, and bcrypt password hashing.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

3 Commits

Folders and files

Repository files navigation

Auth System (Node.js + Express + TypeScript + MongoDB)

A production-ready Authentication and Authorization API built from scratch with Node.js, Express, TypeScript, and MongoDB (Mongoose). Implements JWT-based authentication and role-based access control (RBAC).

Features

  • User registration with hashed passwords (bcrypt)
  • JWT-based login (stateless authentication)
  • Protected routes via protect middleware (verifies JWT)
  • Role-based authorization via authorize middleware (user / admin)
  • Strongly typed end-to-end with TypeScript (Mongoose models, Express Request, JWT payloads)
  • Centralized, validated environment configuration (fails fast on missing secrets)
  • Secure-by-default password handling (select: false on the password field)

Tech Stack

Layer Technology
Runtime Node.js
Framework Express
Language TypeScript
Database MongoDB (via Mongoose)
Auth JSON Web Tokens (jsonwebtoken)
Password hashing bcryptjs
Dev tooling tsx (dev server), tsc (build)

Project Structure

src/
├── config/
│   ├── env.ts              # Validated, typed environment variables
│   └── db.ts                # MongoDB connection
├── controllers/
│   └── auth.controller.ts   # register, login, getProfile, getAdminDashboard
├── middlewares/
│   └── auth.middleware.ts   # protect (JWT verify), authorize (role check)
├── models/
│   └── User.ts               # Mongoose schema + bcrypt pre-save hook
├── routes/
│   └── auth.routes.ts        # Route definitions
├── types/
│   └── express/
│       └── index.d.ts        # Extends Express Request with `user`
├── utils/
│   └── jwt.util.ts           # JWT signing helper
└── server.ts                  # App entry point

Getting Started

Prerequisites

  • Node.js (v18+ recommended)
  • MongoDB running locally, or a MongoDB Atlas connection string

Installation

git clone https://github.com/SaqibShah-dev/auth-system-ts.git
cd auth-system-ts
npm install

Environment Variables

Create a .env file in the project root:

PORT=5000
NODE_ENV=development

MONGO_URI=mongodb://127.0.0.1:27017/auth-system
# Or, for MongoDB Atlas:
# MONGO_URI=mongodb+srv://<username>:<password>@cluster0.xxxxx.mongodb.net/auth-system

JWT_SECRET=your_super_secret_key_change_me
JWT_EXPIRES_IN=1d

The app will refuse to start if NODE_ENV, MONGO_URI, or JWT_SECRET are missing — this is intentional (fail fast at startup rather than failing later mid-request).

Running the App

# Development (auto-restart on file changes)
npm run dev

# Production build
npm run build
npm start

On success, you should see:

✅ MongoDB connected successfully
🚀 Server running on http://localhost:5000

API Reference

Base URL: http://localhost:5000/api/auth

POST /register

Public. Creates a new user with role user by default.

Body:

{
  "name": "John Doe",
  "email": "[email protected]",
  "password": "password123"
}

Responses:

  • 201 Created — user created, returns token + user
  • 400 Bad Request — missing fields
  • 409 Conflict — email already registered

POST /login

Public. Authenticates a user and returns a JWT.

Body:

{
  "email": "[email protected]",
  "password": "password123"
}

Responses:

  • 200 OK — returns token + user
  • 400 Bad Request — missing fields
  • 401 Unauthorized — invalid email or password (same message for both, to prevent user enumeration)

GET /profile

Protected. Requires a valid JWT.

Headers:

Authorization: Bearer <token>

Responses:

  • 200 OK — returns the current user's profile
  • 401 Unauthorized — missing/invalid/expired token
  • 404 Not Found — token is valid but the user no longer exists in the DB

GET /admin/dashboard

Protected + role-restricted (admin only).

Headers:

Authorization: Bearer <token>

Responses:

  • 200 OK — returns basic user stats
  • 401 Unauthorized — missing/invalid token
  • 403 Forbidden — valid token, but role is not admin

New users cannot self-assign the admin role. To test this route, manually update a user's role field to "admin" directly in the database, then log in again to get a fresh token (existing tokens retain the role they were issued with).

Security Notes

  • Passwords are hashed with bcrypt (cost factor 10) before being saved — never stored in plain text.
  • The password field is excluded from all queries by default (select: false) and must be explicitly requested (.select('+password')) — used only internally during login.
  • Login failures return identical messages/status codes regardless of whether the email or password was wrong, to prevent account enumeration.
  • JWTs are stateless: role changes made in the database do not affect already-issued tokens until they expire or the user logs in again.

Possible Next Steps

  • Centralized error-handling middleware (remove repeated try/catch in controllers)
  • Request validation with a schema library (e.g. Zod)
  • Refresh tokens / token revocation
  • Rate limiting on /login to mitigate brute-force attempts
  • Password reset flow (email-based)

License

MIT

About

Production-ready Authentication & Authorization REST API built with Node.js, Express, TypeScript, and MongoDB — featuring JWT auth, role-based access control, and bcrypt password hashing.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages