Skip to content

Marlinsk/nodejs-authentication-backend

Repository files navigation

Node.js Authentication Backend Application

A production-ready authentication backend built with Clean Architecture, Domain-Driven Design (DDD), and Test-Driven Development (TDD) principles, featuring JWT authentication, two-factor authentication, password recovery, and comprehensive logging.

Description

This project demonstrates modern software architecture patterns and security best practices for authentication systems. It implements a complete authentication backend with advanced features like two-factor authentication, password recovery, health monitoring, and structured logging.

Note: This project serves as a comprehensive reference implementation. While production-ready in architecture, evaluate and adapt the patterns to your specific use case rather than copying directly.

✨ Features

Authentication & Security

  • βœ… JWT-based authentication with access and refresh tokens
  • βœ… Two-Factor Authentication (2FA) with TOTP (Google Authenticator compatible)
  • βœ… Password recovery with time-limited, single-use tokens
  • βœ… Email and SMS verification (adapter pattern for multiple providers)
  • βœ… Backup codes for 2FA recovery
  • βœ… Password hashing with bcrypt

System Features

  • βœ… Health check endpoint with database connectivity monitoring
  • βœ… Comprehensive logging system with Winston (HTTP requests, errors, debug)
  • βœ… Clean Architecture with dependency injection
  • βœ… Database abstraction layer (supports SQL, NoSQL, In-Memory)
  • βœ… ULID-based IDs (sortable, timestamp-based)
  • βœ… Automated testing with 95+ unit and integration tests
  • βœ… Daily log rotation with 30-day retention

Developer Experience

  • βœ… TypeScript with strict typing
  • βœ… Path aliases for clean imports
  • βœ… Hot reload in development
  • βœ… Comprehensive API documentation
  • βœ… Test coverage reporting

πŸ—οΈ Architecture

This project follows Clean Architecture principles with clear separation of concerns:

src/
β”œβ”€β”€ domain/                # Business logic (entities, value objects, repository interfaces)
β”œβ”€β”€ application/           # Use cases, DTOs, provider interfaces
β”œβ”€β”€ infrastructure/        # External concerns (database, HTTP, providers)
β”‚   β”œβ”€β”€ database/          # Database adapters and repositories
β”‚   β”œβ”€β”€ http/              # Controllers, routes, middlewares
β”‚   └── providers/         # Token, hash, email, SMS, TOTP, logging
└── shared/                # Shared constants and utilities

Key Principles:

  • Dependencies flow inward (Infrastructure β†’ Application β†’ Domain)
  • Domain layer has zero dependencies on outer layers
  • Interfaces defined by inner layers, implemented by outer layers
  • Easy to swap implementations (e.g., in-memory DB for testing)

πŸš€ Getting Started

Prerequisites

  • Node.js 16+
  • pnpm (recommended) or npm
  • Git

Install pnpm (if not already installed)

npm install -g pnpm

Or using corepack (Node.js 16.13+):

corepack enable
corepack prepare pnpm@latest --activate

Clone the Repository

git clone https://github.com/Marlinsk/node-authentication-backend.git
cd node-authentication-backend

Install Dependencies

pnpm install

βš™οΈ Environment Setup

Create a .env file in the project root by copying the example:

cp .env.example .env

Required Variables

Core Configuration

DATABASE_URL="file:./dev.db"
JWT_SECRET_KEY="your-secret-key-change-in-production"

Password Reset

PASSWORD_RESET_URL="http://localhost:3000/reset-password"
PASSWORD_RESET_TOKEN_EXPIRATION_HOURS=1

Two-Factor Authentication

TOTP_ISSUER="NodeJS Authentication Backend"
TOTP_BACKUP_CODES_COUNT=10

Email and SMS Providers

EMAIL_PROVIDER="console"
SMS_PROVIDER="console"
EMAIL_SERVICE_API_KEY=""
EMAIL_FROM="noreply@example.com"
SMS_SERVICE_API_KEY=""
SMS_FROM=""

Provider Options:

  • console - Development mode (logs to console)
  • sendgrid - Production email service
  • twilio - Production SMS service

Logging Configuration

NODE_ENV="development"
LOG_LEVEL="info"
LOG_DIR="logs"
LOG_TO_FILE="false"

Log Levels: error, warn, info, http, debug

πŸƒ Running the Application

Development Mode

pnpm dev

Server starts at http://localhost:5500

Production Build

pnpm build
pnpm start

Testing

pnpm test                # Run all tests
pnpm test:watch          # Watch mode
pnpm test:coverage       # Coverage report

πŸ›£οΈ API Endpoints

Health Check

  • GET /health - Application health status (public)

User Management

  • POST / - Create user account
  • POST /login - User authentication
  • GET / - List all users (protected)
  • GET /:id - Get user by ID (protected)
  • PUT /:id - Update user (protected)
  • DELETE /:id - Delete user (protected)

Password Reset

  • POST /password/request - Request password reset
  • POST /password/reset - Reset password with token

Two-Factor Authentication

  • POST /2fa/enable - Enable 2FA (protected)
  • POST /2fa/verify - Verify 2FA token (protected)
  • POST /2fa/verify-backup - Verify backup code (protected)
  • DELETE /2fa/disable - Disable 2FA (protected)

Request Examples

Create User

POST http://localhost:5500/
Content-Type: application/json

{
  "name": "Andre Haskell",
  "username": "haskell",
  "email": "andhaskell@gmail.com",
  "password": "SecurePass123"
}

Login

POST http://localhost:5500/login
Content-Type: application/json

{
  "username": "haskell",
  "password": "SecurePass123"
}

Enable 2FA

POST http://localhost:5500/2fa/enable
Authorization: Bearer <your-token>
Content-Type: application/json

{
  "method": "totp"
}

Request Password Reset

POST http://localhost:5500/password/request
Content-Type: application/json

{
  "email": "andhaskell@gmail.com"
}

For complete API documentation, see API_DOCUMENTATION.md

πŸ§ͺ Testing

The project includes comprehensive test coverage:

pnpm test                # Run all tests (95+ tests)
pnpm test:watch          # Watch mode for TDD
pnpm test:coverage       # Generate coverage report

Test Structure:

  • Unit tests: Domain entities, value objects, use cases
  • Integration tests: Repository implementations, database operations
  • E2E tests: HTTP endpoints (planned)

🏦 Database Management

Access Database Editor

pnpm prisma:studio

Database Commands

pnpm prisma:migrate      # Create and apply migrations
pnpm prisma:generate     # Regenerate Prisma Client
pnpm prisma:push         # Push schema changes
pnpm prisma:seed         # Run database seeds

Supported Databases

The application uses an adapter pattern supporting:

  • In-Memory (default for development/testing)
  • SQL databases (PostgreSQL, MySQL, SQLite)
  • NoSQL databases (MongoDB)

Configure via DATABASE_TYPE in database config.

πŸ“Š Logging System

The application includes a comprehensive logging system powered by Winston:

Features

  • Automatic HTTP request logging (method, URL, status, duration, IP)
  • Error tracking with stack traces
  • Daily log rotation (30-day retention, 20MB per file)
  • Separate error and combined logs
  • Colorized console output in development
  • JSON format for log aggregation tools

Log Files (when enabled)

logs/
β”œβ”€β”€ error/
β”‚   └── error-2025-12-05.log
└── combined/
    └── combined-2025-12-05.log

Configuration

Set LOG_TO_FILE="true" in .env to enable file logging in development.

In production (NODE_ENV="production"), logs are automatically saved to files.

πŸ“ Project Structure

node-authentication-backend/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ domain/                         # Core business logic
β”‚   β”‚   β”œβ”€β”€ user/
β”‚   β”‚   β”‚   β”œβ”€β”€ entities/               # User, RefreshToken, PasswordResetToken, TwoFactorAuth
β”‚   β”‚   β”‚   └── repositories/           # Repository interfaces
β”‚   β”‚   └── shared/
β”‚   β”‚       β”œβ”€β”€ errors/                 # Domain errors
β”‚   β”‚       └── value-objects/          # Email, Password, EntityId
β”‚   β”‚
β”‚   β”œβ”€β”€ application/                    # Application services
β”‚   β”‚   β”œβ”€β”€ use-cases/                  # Business workflows
β”‚   β”‚   β”‚   β”œβ”€β”€ user/                   # CRUD, authentication
β”‚   β”‚   β”‚   β”œβ”€β”€ password-reset/         # Password recovery
β”‚   β”‚   β”‚   β”œβ”€β”€ two-factor/             # 2FA operations
β”‚   β”‚   β”‚   └── health/                 # Health check
β”‚   β”‚   β”œβ”€β”€ dtos/                       # Data transfer objects
β”‚   β”‚   └── providers/                  # Provider interfaces
β”‚   β”‚
β”‚   β”œβ”€β”€ infrastructure/                 # Technical implementation
β”‚   β”‚   β”œβ”€β”€ database/
β”‚   β”‚   β”‚   β”œβ”€β”€ adapters/               # SQL, NoSQL, In-Memory
β”‚   β”‚   β”‚   β”œβ”€β”€ repositories/           # Concrete implementations
β”‚   β”‚   β”‚   └── connection/             # Database factory
β”‚   β”‚   β”œβ”€β”€ http/
β”‚   β”‚   β”‚   β”œβ”€β”€ controllers/            # HTTP handlers
β”‚   β”‚   β”‚   β”œβ”€β”€ middlewares/            # Auth, error, logger
β”‚   β”‚   β”‚   β”œβ”€β”€ routes/                 # Route definitions
β”‚   β”‚   β”‚   └── factories/              # Dependency injection
β”‚   β”‚   └── providers/
β”‚   β”‚       β”œβ”€β”€ token/                  # JWT, bcrypt
β”‚   β”‚       β”œβ”€β”€ email/                  # Console, SendGrid
β”‚   β”‚       β”œβ”€β”€ sms/                    # Console, Twilio
β”‚   β”‚       β”œβ”€β”€ totp/                   # Speakeasy TOTP
β”‚   β”‚       └── logger/                 # Winston
β”‚   β”‚
β”‚   β”œβ”€β”€ shared/                         # Shared resources
β”‚   β”‚   └── constants/                  # HTTP status codes
β”‚   β”‚
β”‚   └── tests/                          # Test suites
β”‚       β”œβ”€β”€ unit/                       # Isolated tests
β”‚       └── integration/                # Database tests
β”‚
β”œβ”€β”€ .env.example                        # Environment template
β”œβ”€β”€ API_DOCUMENTATION.md                # Complete API docs
β”œβ”€β”€ CLAUDE.md                           # Project guide
└── README.md                           # This file

πŸ› οΈ Technologies

Core

  • Node.js - Runtime environment
  • TypeScript - Type safety and developer experience
  • Express - HTTP server framework

Architecture & Patterns

  • Clean Architecture - Separation of concerns
  • DDD - Domain-driven design principles
  • TDD - Test-driven development
  • Dependency Injection - Loose coupling

Authentication & Security

  • JWT - JSON Web Tokens (jsonwebtoken)
  • bcrypt - Password hashing
  • Speakeasy - TOTP for 2FA
  • ULID - Unique ID generation

Database & Storage

  • Prisma - ORM (optional)
  • Adapter pattern - Database abstraction

Logging & Monitoring

  • Winston - Structured logging
  • winston-daily-rotate-file - Log rotation

Testing

  • Jest - Test framework
  • 95+ tests - Unit and integration coverage

Development

  • Babel - TypeScript compilation
  • Nodemon - Hot reload
  • ESLint - Code linting (optional)

πŸ“š Additional Documentation

🀝 Contributing

Contributions are welcome! This project serves as a learning resource, and improvements are encouraged.

Areas for Contribution

  • Rate limiting implementation
  • Real email/SMS provider implementations
  • Additional test coverage
  • Performance optimizations
  • Documentation improvements

πŸ“ License

This project is open source and available for educational purposes.

🎯 Learning Objectives

This project demonstrates:

  • Clean Architecture implementation in Node.js
  • Domain-Driven Design patterns
  • Test-Driven Development workflow
  • Security best practices (JWT, 2FA, password reset)
  • Logging and monitoring strategies
  • Database abstraction and dependency injection
  • TypeScript advanced features

πŸ”’ Security Notes

  • Always change default JWT secret in production
  • Use strong password policies
  • Enable 2FA for sensitive operations
  • Keep dependencies updated
  • Review logs regularly for suspicious activity
  • Use HTTPS in production
  • Implement rate limiting for authentication endpoints

πŸš€ Production Checklist

Before deploying to production:

  • Change JWT_SECRET_KEY to a strong secret
  • Set NODE_ENV="production"
  • Configure real email provider (SendGrid)
  • Configure real SMS provider (Twilio)
  • Set up database migrations
  • Enable LOG_TO_FILE="true"
  • Configure log aggregation (ELK, CloudWatch, etc.)
  • Implement rate limiting
  • Set up SSL/TLS certificates
  • Configure CORS properly
  • Review and test health check integration
  • Set up monitoring and alerts

Built with ❀️ using Clean Architecture principles

About

Node.js authentication backend with Clean Architecture, DDD, TDD - JWT, 2FA, password reset

Topics

Resources

License

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published