View as Json

Stateful Auth Blueprint

Session-based authentication blueprint with secure login, logout, and server-managed session flow.

Installation Guide

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

npx servercn-cli@latest add blueprint stateful-auth

Features

  • Session-Based Authentication - Server-managed sessions with refresh token support
  • User Registration & Login - Secure signup/signin with validation
  • Profile Management - Update profile, change password, avatar upload
  • Session Management - View active sessions, revoke specific or all sessions
  • Password Recovery - Forgot/reset password via OTP
  • OAuth Integration - GitHub and Google OAuth support
  • Security Features - Rate limiting, account restrictions, soft delete
  • Account Reactivation - Restore deleted accounts within grace period

Architecture Options

This blueprint is available in two architectures:

Traditional Model-View-Controller pattern with separated concerns:

  • Controllers handle business logic
  • Models define data schemas
  • Services encapsulate complex operations
  • Routes define API endpoints
  • Middlewares handle cross-cutting concerns

Domain-driven modular structure organized by feature:

  • Each module contains controller, service, routes, models
  • Shared utilities in common directories
  • Better scalability for large applications

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

Project Structure

src/
├── controllers/
│   ├── auth.controller.ts      # Authentication logic
│   ├── health.controller.ts    # Health check endpoints
│   └── oauth.controller.ts     # OAuth callbacks
├── models/
│   ├── user.model.ts           # User schema
│   ├── session.model.ts        # Session schema
│   └── otp.model.ts            # OTP schema
├── services/
│   ├── auth.service.ts         # Auth business logic
│   ├── email.service.ts        # Email sending
│   ├── otp.service.ts          # OTP generation/verification
│   └── upload.service.ts       # File upload handling
├── routes/
│   ├── auth.routes.ts          # Auth endpoints
│   ├── oauth.routes.ts         # OAuth endpoints
│   ├── health.routes.ts        # Health endpoints
│   └── index.ts                # Route aggregator
├── middlewares/
│   ├── verify-auth.ts          # JWT validation
│   ├── validate-request.ts     # Zod validation
│   ├── rate-limiter.ts         # Rate limiting rules
│   ├── upload-file.ts          # Multer setup
│   └── ...                     # Other middlewares
├── validators/
│   └── auth/index.ts           # Zod schemas for auth
├── constants/
│   └── auth.constants.ts       # Auth constants
├── helpers/
│   └── ...                     # Utility functions
├── utils/
│   └── ...                     # Common utilities
├── types/
│   └── express.d.ts            # Type definitions
└── configs/
    └── ...                     # Configuration files
src/
├── modules/
│   ├── auth/
│   │   ├── auth.controller.ts   # Auth endpoints
│   │   ├── auth.service.ts      # Auth business logic
│   │   ├── auth.routes.ts       # Auth endpoints
│   │   ├── auth.types.ts        # TypeScript types
│   │   ├── auth.constants.ts    # Constants
│   │   ├── auth.validation.ts   # Zod schemas
│   │   ├── user.model.ts        # User model
│   │   └── session.model.ts     # Session model
│   ├── otp/
│   │   ├── otp.service.ts       # OTP logic
│   │   └── otp.model.ts         # OTP model
│   ├── oauth/
│   │   ├── oauth.controller.ts  # OAuth callbacks
│   │   ├── oauth.service.ts     # OAuth logic
│   │   └── oauth.routes.ts      # OAuth routes
│   ├── upload/
│   │   └── upload.service.ts    # Upload logic
│   └── health/
│       ├── health.controller.ts # Health endpoints
│       └── health.routes.ts     # Health routes
├── routes/
│   ├── index.ts                 # Main router
│   └── health.routes.ts         # Health routes
├── shared/
│   ├── middlewares/             # Shared middlewares
│   ├── validators/              # Shared validators
│   ├── helpers/                 # Helper functions
│   ├── utils/                   # Utilities
│   └── constants/               # Shared constants
└── types/
    └── express.d.ts             # Type definitions

Environment Variables

Create a .env file with the following:

PORT='9000'
NODE_ENV='development'
LOG_LEVEL='info'
CORS_ORIGIN=''
 
# CRYPTO
CRYPTO_SECRET=
 
# DB
DATABASE_URL=
 
# RESEND
RESEND_API_KEY=
EMAIL_FROM=
 
# CLOUDINARY
CLOUDINARY_CLOUD_NAME=
CLOUDINARY_API_KEY=
CLOUDINARY_API_SECRET=
 
# GITHUB
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
GITHUB_REDIRECT_URI=
 
#  GOOGLE
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
GOOGLE_REDIRECT_URI=

Key Differences from Stateless Auth

  1. Server-Side Sessions - Sessions stored in database
  2. Session Revocation - Can invalidate specific/all sessions
  3. No Refresh Tokens - Uses session-based authentication
  4. Better Security - Full control over active sessions
  5. Resource Intensive - Requires database lookups for session validation

When to Use

Choose Stateful Auth when:

  • You need to track and manage user sessions
  • You want ability to revoke access instantly
  • You're building internal/admin applications
  • Security is higher priority than scalability

Avoid Stateful Auth when:

  • Building microservices (stateless is better)
  • You need horizontal scalability
  • High-performance APIs with millions of users
  • Mobile apps with offline capabilities

File & Folder Structure

Loading files...

Installation

npx servercn-cli@latest add bp stateful-auth