Skip to content

MarkosBK/fullstack-auth-backend

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

7 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Fullstack Authentication Backend

A robust authentication backend API built with NestJS, featuring comprehensive user management, role-based access control, and modern authentication flows.

πŸš€ Features

  • Multi-provider Authentication: Local email/password and Google OAuth2
  • Role-Based Access Control (RBAC): Admin, Customer, and Signup roles with permissions
  • JWT Authentication: Secure token-based authentication with refresh tokens
  • OTP Verification: Email-based OTP for registration and password reset
  • Redis Caching: High-performance caching with Redis for improved scalability
  • Database Management: PostgreSQL with Prisma ORM
  • API Documentation: Swagger/OpenAPI documentation
  • Rate Limiting: Built-in rate limiting for security
  • Email Service: Configurable email service integration
  • Docker Support: Containerized development environment

πŸ› οΈ Tech Stack

πŸ“‹ Prerequisites

  • Node.js: 24.7.0 (specified in package.json engines)
  • npm: Latest version
  • Docker: For running PostgreSQL and Redis
  • Git: For version control

πŸš€ Quick Start

1. Clone the Repository

git clone <repository-url>
cd backend

2. Install Dependencies

npm install

3. Environment Setup

Create a .env file in the root directory:

cp .env.example .env

4. Start Services with Docker

docker-compose up -d

This will start:

  • PostgreSQL database on port 5433
  • Redis cache on port 6380
  • MailHog for email testing on ports 1025 (SMTP) and 8025 (Web UI)

5. Database Setup

# Generate Prisma client
npm run prisma:generate

# Run database migrations
npm run prisma:migrate

6. Start Development Server

npm run start:dev

The API will be available at http://localhost:3000

7. View API Documentation

Visit http://localhost:3000/api to access the Swagger documentation.

πŸ“ Project Structure

src/
β”œβ”€β”€ cache/                   # Redis caching system
β”œβ”€β”€ common/                  # Shared utilities
β”‚   β”œβ”€β”€ decorators/         # Common decorators
β”‚   β”œβ”€β”€ dto/                # Base DTOs
β”‚   β”œβ”€β”€ filters/            # Exception filters
β”‚   β”œβ”€β”€ interceptors/       # Response interceptors
β”‚   β”œβ”€β”€ schemas/            # Base response schemas
β”‚   └── utils/              # Utility functions
β”œβ”€β”€ config/                  # Configuration management
β”œβ”€β”€ database/               # Database module (Prisma)
β”œβ”€β”€ modules/               # Business logic modules
β”‚   β”œβ”€β”€ auth/              # Authentication module
β”‚   β”‚   β”œβ”€β”€ decorators/    # Custom decorators (@Auth, @Roles, @CurrentUser)
β”‚   β”‚   β”œβ”€β”€ dtos/          # Data Transfer Objects
β”‚   β”‚   β”œβ”€β”€ guards/        # Authentication guards
β”‚   β”‚   β”œβ”€β”€ schemas/       # Response schemas
β”‚   β”‚   β”œβ”€β”€ services/      # Password and token services
β”‚   β”‚   └── strategies/    # Passport strategies (JWT, Local)
β”‚   β”œβ”€β”€ account/           # Account management
β”‚   β”œβ”€β”€ role/              # Role management
β”‚   └── user/              # User management
└── services/              # External services
    β”œβ”€β”€ email/             # Email service
    └── otp/               # OTP service

πŸ”§ Environment Variables

Required Environment Variables

Create a .env file with the following variables:

# Application Configuration
APPLICATION_PORT=3000
ALLOWED_ORIGINS=https://localhost2:3005,http://localhost:3001,https://yourdomain.com

# Database Configuration
POSTGRES_URI=postgresql://postgres:password@localhost:5433/fullstack_auth
POSTGRES_HOST=localhost
POSTGRES_PORT=5433
POSTGRES_USER=postgres
POSTGRES_PASSWORD=password
POSTGRES_DB=fullstack_auth

# Redis Configuration
REDIS_HOST=localhost
REDIS_PORT=6380
REDIS_USER=
REDIS_PASSWORD=redis_password

# JWT Configuration
SESSION_SECRET=your-super-secret-jwt-key-here
SESSION_EXPIRES_IN=15m
SESSION_REFRESH_EXPIRES_IN=7d
RESET_PASSWORD_EXPIRES_IN=1h

# Google OAuth Configuration
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
GOOGLE_CALLBACK_URL=http://localhost:3000/auth/google/callback

Environment Variables Description

Variable Description Example
APPLICATION_PORT Port for the NestJS application 3000
ALLOWED_ORIGINS CORS allowed origins (comma-separated) https://localhost2:3005,http://localhost:3001
POSTGRES_URI Complete PostgreSQL connection string postgresql://user:pass@host:port/db
POSTGRES_HOST PostgreSQL host localhost
POSTGRES_PORT PostgreSQL port 5433
POSTGRES_USER PostgreSQL username postgres
POSTGRES_PASSWORD PostgreSQL password password
POSTGRES_DB PostgreSQL database name fullstack_auth
REDIS_HOST Redis host localhost
REDIS_PORT Redis port 6380
REDIS_USER Redis username (optional) ``
REDIS_PASSWORD Redis password redis_password
SESSION_SECRET JWT secret key (use a strong secret) your-super-secret-jwt-key
SESSION_EXPIRES_IN JWT access token expiration 15m
SESSION_REFRESH_EXPIRES_IN JWT refresh token expiration 7d
RESET_PASSWORD_EXPIRES_IN Password reset token expiration 1h
GOOGLE_CLIENT_ID Google OAuth client ID your-google-client-id
GOOGLE_CLIENT_SECRET Google OAuth client secret your-google-client-secret
GOOGLE_CALLBACK_URL Google OAuth callback URL http://localhost:3000/auth/google/callback

Note about CORS: The ALLOWED_ORIGINS setting only affects web browsers. Mobile applications (React Native, Flutter, etc.) bypass CORS restrictions as they use native HTTP clients. For mobile app security, rely on JWT authentication, API keys, and rate limiting instead.

🎯 Available Scripts

# Development
npm run start:dev          # Start development server with hot reload
npm run start:debug        # Start development server with debugging

# Production
npm run build              # Build the application
npm run start:prod         # Start production server

# Database
npm run prisma:generate    # Generate Prisma client
npm run prisma:migrate     # Run database migrations
npm run prisma:deploy      # Deploy migrations to production

# Code Quality
npm run lint               # Run ESLint
npm run format             # Format code with Prettier

# Testing
npm run test               # Run unit tests
npm run test:watch         # Run tests in watch mode
npm run test:cov           # Run tests with coverage
npm run test:e2e           # Run end-to-end tests

πŸ” Authentication Flow

1. Registration Flow

  1. User provides email and password
  2. System sends OTP to email for verification
  3. User verifies OTP
  4. Account is created with SIGNUP role
  5. User can complete profile setup

2. Login Flow

  1. User provides email and password
  2. System validates credentials
  3. JWT access and refresh tokens are issued
  4. User is authenticated

3. Google OAuth Flow

  1. User clicks "Login with Google"
  2. Redirected to Google OAuth
  3. Google returns authorization code
  4. System exchanges code for user info
  5. User account is created/updated
  6. JWT tokens are issued

4. Password Reset Flow

  1. User requests password reset
  2. System sends OTP to email
  3. User verifies OTP
  4. User sets new password
  5. Password is updated

πŸ—οΈ Database Schema

The application uses the following main entities:

  • User: Core user information
  • Account: Authentication provider accounts (Local, Google)
  • Role: User roles (Admin, Customer, Signup)
  • Permission: Granular permissions for resources
  • Token: JWT refresh tokens
  • UserRole: Many-to-many relationship between users and roles
  • RolePermission: Many-to-many relationship between roles and permissions

πŸš€ Deployment

Docker Deployment

  1. Build the Docker image:
docker build -t fullstack-auth-backend .
  1. Run with docker-compose:
docker-compose up -d

Production Considerations

  • Use environment-specific .env files
  • Set up proper SSL certificates
  • Configure production database
  • Set up monitoring and logging
  • Use process managers like PM2
  • Configure reverse proxy (nginx)

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Commit your changes: git commit -m 'Add amazing feature'
  4. Push to the branch: git push origin feature/amazing-feature
  5. Open a Pull Request

πŸ“ License

This project is licensed under the UNLICENSED License.

πŸ†˜ Support

If you encounter any issues or have questions:

  1. Check the Issues page
  2. Create a new issue with detailed information
  3. Contact the development team

Happy Coding! πŸŽ‰

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors