Stateful Authentication with MongoDB (Mongoose)

MongoDB implementation of stateful authentication using Mongoose ODM for session management.

Installation Guide

You can add the stateful authentication blueprint to your project using the Servercn CLI:

npx servercn-cli add blueprint stateful-auth

API Endpoints

All endpoints are the same for both MVC and Feature architectures.

Base URL: http://localhost:3000/api/v1/auth

MethodEndpointDescription
POST/verify-otpVerify OTP for email verification
POST/signupRegister new user
POST/signinLogin user
GET/profileGet user profile
PATCH/profileUpdate profile (with avatar)
POST/logoutLogout current user
POST/forgot-passwordRequest password reset OTP
POST/reset-passwordReset password with OTP
POST/change-passwordChange current password
DELETE/delete-accountSoft delete account
PUT/reactivate-accountRestore deleted account

Base URL: http://localhost:3000/api/v1/auth/sessions

MethodEndpointDescription
GET/sessionsGet all active user sessions
DELETE/sessionsRevoke all sessions except current
DELETE/sessions/:sessionIdRevoke specific session

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

MethodEndpointDescription
GET/githubInitiate GitHub OAuth
GET/github/callbackGitHub OAuth callback
GET/googleInitiate Google OAuth
GET/google/callbackGoogle OAuth callback

Base URL: http://localhost:3000/api/v1/health

MethodEndpointDescription
GET/Basic health check
GET/detailedDetailed health status

Architecture Comparison

project/
├── src/
   ├── controllers/
   ├── auth.controller.ts      # All auth endpoints
   ├── health.controller.ts    # Health checks
   └── oauth.controller.ts     # OAuth callbacks
   ├── models/
   ├── user.model.ts           # User schema + methods
   ├── session.model.ts        # Session schema
   └── otp.model.ts            # OTP schema
   ├── services/
   ├── auth.service.ts         # Core auth logic
   ├── email.service.ts        # Email sending
   ├── otp.service.ts          # OTP generation/verify
   └── upload.service.ts       # Cloudinary upload
   ├── routes/
   ├── auth.routes.ts          # /api/auth routes
   ├── oauth.routes.ts         # /api/oauth routes
   ├── health.routes.ts        # /api/health routes
   └── index.ts                # Route aggregator
   ├── middlewares/
   ├── verify-auth.ts          # JWT/session validation
   ├── validate-request.ts     # Zod validation
   ├── rate-limiter.ts         # Rate limiting rules
   ├── upload-file.ts          # Multer setup
   ├── user-account-restriction.ts  # Account status check
   └── validate-id.ts          # ObjectId validation
   ├── validators/
   └── auth/
       └── index.ts            # Zod schemas
   ├── constants/
   └── auth.constants.ts       # Auth constants
   ├── helpers/
   ├── api-error.ts            # Error helper
   ├── async-handler.ts        # Async wrapper
   └── pick.ts                 # Object picker
   ├── utils/
   ├── logger.ts               # Winston logger
   ├── response-formatter.ts   # API response wrapper
   ├── error-handler.ts        # Global error handler
   ├── http-status-codes.ts    # HTTP codes
   ├── not-found-handler.ts    # 404 handler
   └── shutdown.ts             # Graceful shutdown
   ├── types/
   └── express.d.ts            # Express type extensions
   ├── configs/
   ├── cors.config.ts          # CORS settings
   ├── db.config.ts            # MongoDB connection
   ├── env.config.ts           # Env validation
   ├── passport.config.ts      # Passport strategies
   └── security.config.ts      # Security headers
   ├── app.ts                      # Express app setup
   └── server.ts                   # Server entry point
├── swagger.config.ts               # Swagger configuration
└── package.json
project/
├── src/
   ├── modules/
   ├── auth/
   ├── auth.controller.ts     # Auth endpoints
   ├── auth.service.ts        # Auth logic
   ├── auth.routes.ts         # Auth routes
   ├── auth.types.ts          # TypeScript types
   ├── auth.constants.ts      # Auth constants
   ├── auth.validation.ts     # Zod schemas
   ├── user.model.ts          # User schema
   └── session.model.ts       # Session schema
   ├── otp/
   ├── otp.service.ts         # OTP generation/verify
   └── otp.model.ts           # OTP schema
   ├── oauth/
   ├── oauth.controller.ts    # OAuth callbacks
   ├── oauth.service.ts       # OAuth logic
   └── oauth.routes.ts        # OAuth routes
   ├── upload/
   └── upload.service.ts      # Cloudinary upload
   └── health/
       ├── health.controller.ts   # Health endpoints
       └── health.routes.ts       # Health routes
   ├── routes/
   ├── index.ts                   # Main router
   └── health.routes.ts           # Health routes
   ├── shared/
   ├── middlewares/
   ├── verify-auth.ts         # JWT validation
   ├── validate-request.ts    # Zod validation
   ├── rate-limiter.ts        # Rate limiting
   ├── upload-file.ts         # Multer setup
   ├── user-account-restriction.ts  # Account check
   └── validate-id.ts         # ObjectId validation
   ├── helpers/
   ├── api-error.ts           # Error helper
   ├── async-handler.ts       # Async wrapper
   └── pick.ts                # Object picker
   ├── utils/
   ├── logger.ts              # Winston logger
   ├── response-formatter.ts  # Response wrapper
   ├── error-handler.ts       # Global error handler
   ├── http-status-codes.ts   # HTTP codes
   ├── not-found-handler.ts   # 404 handler
   └── shutdown.ts            # Graceful shutdown
   └── constants/
       └── api-response.constants.ts  # Response constants
   ├── types/
   └── express.d.ts               # Express type extensions
   ├── app.ts                         # Express app setup
   └── server.ts                      # Server entry point
├── swagger.config.ts                  # Swagger configuration
└── package.json

Key Files

  • auth.controller.ts - Handles signup, signin, profile management, password operations, session management
  • oauth.controller.ts - GitHub & Google OAuth callback handlers
  • health.controller.ts - Basic and detailed health checks
  • auth.service.ts - Core authentication business logic
  • email.service.ts - Email delivery using Nodemailer
  • otp.service.ts - OTP generation, hashing, and verification
  • upload.service.ts - Cloudinary file upload integration
  • user.model.ts - User schema with hooks and instance methods
  • session.model.ts - Session tracking schema
  • otp.model.ts - One-time password schema
  • auth.routes.ts - All authentication endpoints
  • oauth.routes.ts - OAuth flow routes
  • health.routes.ts - Health check endpoints

File & Folder Structure

Loading files...

Installation

npx servercn-cli add bp stateful-auth