An open API service indexing awesome lists of open source software.

https://github.com/marlinsk/nodejs-authentication-backend

User authentication backend application with JWT and refresh token.
https://github.com/marlinsk/nodejs-authentication-backend

autentication express jwt-token login-system middleware nodejs prisma refresh-token rest-api sqlite typescript

Last synced: about 2 months ago
JSON representation

User authentication backend application with JWT and refresh token.

Awesome Lists containing this project

README

          

# 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)
```bash
npm install -g pnpm
```

Or using corepack (Node.js 16.13+):
```bash
corepack enable
corepack prepare pnpm@latest --activate
```

### Clone the Repository
```bash
git clone https://github.com/Marlinsk/node-authentication-backend.git
cd node-authentication-backend
```

### Install Dependencies
```bash
pnpm install
```

## ⚙️ Environment Setup

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

```bash
cp .env.example .env
```

### Required Variables

#### Core Configuration
```env
DATABASE_URL="file:./dev.db"
JWT_SECRET_KEY="your-secret-key-change-in-production"
```

#### Password Reset
```env
PASSWORD_RESET_URL="http://localhost:3000/reset-password"
PASSWORD_RESET_TOKEN_EXPIRATION_HOURS=1
```

#### Two-Factor Authentication
```env
TOTP_ISSUER="NodeJS Authentication Backend"
TOTP_BACKUP_CODES_COUNT=10
```

#### Email and SMS Providers
```env
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
```env
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
```bash
pnpm dev
```
Server starts at `http://localhost:5500`

### Production Build
```bash
pnpm build
pnpm start
```

### Testing
```bash
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
```bash
POST http://localhost:5500/
Content-Type: application/json

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

#### Login
```bash
POST http://localhost:5500/login
Content-Type: application/json

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

#### Enable 2FA
```bash
POST http://localhost:5500/2fa/enable
Authorization: Bearer
Content-Type: application/json

{
"method": "totp"
}
```

#### Request Password Reset
```bash
POST http://localhost:5500/password/request
Content-Type: application/json

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

For complete API documentation, see [API_DOCUMENTATION.md](API_DOCUMENTATION.md)

## 🧪 Testing

The project includes comprehensive test coverage:

```bash
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
```bash
pnpm prisma:studio
```

### Database Commands
```bash
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

- [API_DOCUMENTATION.md](API_DOCUMENTATION.md) - Complete API reference with examples
- [CLAUDE.md](CLAUDE.md) - Detailed architecture guide and development instructions

## 🤝 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**