Skip to content

Repository files navigation

🏮 Fanous App

A multi-vendor marketplace backend for handmade crafts and artisanal products

NestJS TypeScript PostgreSQL Redis Node.js


📖 Overview

Fanous is a REST API backend for a multi-vendor e-commerce platform where artisans and craftspeople can create shops and sell their handmade products. The name "Fanous" (فانوس) means "lantern" in Arabic — reflecting the platform's purpose of shining a light on traditional craftsmanship.

Built with NestJS and following layered architecture patterns, the application handles user management, authentication, role-based access control, account lifecycle, moderation, vendor onboarding, and asynchronous job processing.


✨ Features

Authentication & Security

  • JWT-based auth — Access tokens + refresh tokens with Redis-backed revocation
  • Multi-tier rate limiting — Default (60/min), strict (10/min), and auth (5/15min) tiers
  • Role-based access control — 6 distinct roles: Admin, Super Admin, Support Admin, Support Agent, Shop Owner, User
  • Account protection — Account verification, deletion guard, disabled account detection
  • Correlation IDs — Every error response includes a UUID for traceability

User Management

  • Full CRUD — Create, read, update users with admin capabilities
  • Profile management — Update profile, password, and profile image (S3 uploads)
  • Email management — Change primary email with two-step verification on old and new addresses
  • Recovery email — Secondary email with OTP verification for account recovery
  • Phone verification — Twilio-powered SMS OTP verification
  • Account status — Activate/deactivate accounts with email notifications
  • Bulk role operations — Assign or remove roles across multiple users atomically

Account Lifecycle

  • Grace-period deletion — Account deletion requests with configurable grace period before permanent removal
  • Bulk operations — Request or cancel deletion for multiple accounts
  • Restoration — Restore accounts within the grace period
  • Scheduled cleanup — BullMQ-powered background jobs to process expired deletion requests

Moderation

  • Moderation actions — Warn, suspend, restrict accounts
  • Action history — Full audit trail of moderation actions per account
  • Appeals — Users can appeal moderation decisions
  • Revocable actions — Moderation actions can be revoked with tracking

Infrastructure

  • Job queues — BullMQ with Redis for async email sending and resource cleanup
  • Structured logging — Winston with daily rotation (JSON in production, colorized in dev)
  • API documentation — Auto-generated Swagger/OpenAPI docs at /api
  • API versioning — URI-based versioning (/api/v1/...)
  • Environment validation — Validates all config at startup; fails fast on misconfiguration
  • Global error handling — Consistent error response format with correlation IDs

🛠️ Tech Stack

Layer Technology
Runtime Node.js 22
Framework NestJS 11
Language TypeScript 5.7
Database PostgreSQL 16 + TypeORM
Cache / Sessions Redis 7 (ioredis)
Job Queue BullMQ
File Storage AWS S3
SMS Twilio
Email Nodemailer
Logging Winston + Daily Rotate File
API Docs Swagger / OpenAPI
Validation class-validator + class-transformer
Authentication JWT (jsonwebtoken + bcrypt)

🏗️ Architecture

src/
├── common/                   # Shared guards, decorators, filters, interceptors, services
│   ├── guards/               # AuthGuard, RolesGuard, AccountVerifiedGuard
│   ├── decorators/           # @Public(), @Protected(), @Roles()
│   ├── filters/              # Global exception filter
│   ├── interceptors/         # Response transformation
│   └── services/             # Email sender, SMS sender, OTP, password helper
│
├── config/                   # App configuration, env validation, multer, Redis
├── infrastructure/
│   └── redis/                # Redis module with connection pooling and health checks
├── logs/                     # Winston logger service with daily rotation
├── queues/                   # BullMQ setup, email processor, resource cleanup processor
│
├── modules/
│   ├── auth/                 # Authentication, account recovery, token management
│   ├── users/                # User CRUD, profile, roles, email, account status
│   ├── account-lifecycle/    # Account deletion requests, grace periods, restoration
│   ├── moderation/           # Moderation actions and appeals
│   └── vendors/              # Vendor/shop management (upcoming)
│
├── health/                   # Health check endpoint
└── main.ts                   # Application bootstrap

Design Patterns

Pattern Implementation
Layered Architecture Controller → Service → Repository → Entity
Interface-driven DI Every service and repository backed by an explicit interface
Repository Pattern TypeORM repositories abstracted behind custom repository classes
Guard-based Auth AuthGuard (JWT validation) + RolesGuard (authorization) global via APP_GUARD
Global Exception Filter Catches all unhandled exceptions, returns structured { success, statusCode, correlationId, message }
Decorator-based Metadata @Public(), @Protected(), @Roles() for declarative access control

🚀 Getting Started

Prerequisites

  • Node.js ≥ 22
  • PostgreSQL ≥ 14
  • Redis ≥ 6
  • npm ≥ 10

Installation

# Clone the repository
git clone git@github.com:Mohamed-Ramadan1/fanous-app.git
cd fanous-app

# Install dependencies
npm install

Environment Configuration

Create a .env file in the project root (see src/config/env.validation.ts for all required variables):

# Application
NODE_ENV=development
PORT=3000
LOG_DIR=logging

# Database
DATABASE_HOST=localhost
DATABASE_PORT=5432
DATABASE_USER=postgres
DATABASE_PASSWORD=your_password
DATABASE_NAME=fanous

# JWT
ACCESS_TOKEN_SECRET=your_access_secret
REFRESH_TOKEN_SECRET=your_refresh_secret
ACCESS_TOKEN_EXPIRATION=15m
REFRESH_TOKEN_EXPIRATION=7d
LOGOUT_TOKEN_SECRET=your_logout_secret
LOGOUT_TOKEN_EXPIRATION=7d
COOKIE_EXPIRATION=604800
JWT_ISSUER=fanous-app

# Redis
REDIS_HOST=localhost
REDIS_PORT=6379

# Email (Nodemailer)
EMAIL_FROM_NAME=Fanous App
EMAIL_FROM=noreply@fanous.app
EMAIL_USER=your_smtp_user
EMAIL_PASSWORD=your_smtp_password
EMAIL_PORT=587
EMAIL_HOST=smtp.example.com

# AWS S3
AWS_REGION=us-east-1
AWS_ACCESS_KEY_ID=your_aws_key
AWS_SECRET_ACCESS_KEY=your_aws_secret
S3_BUCKET_NAME=fanous-bucket

# Twilio
TWILIO_ACCOUNT_SID=your_twilio_sid
TWILIO_AUTH_TOKEN=your_twilio_token
TWILIO_PHONE_NUMBER=+1234567890

# OpenAI (optional)
OPENAI_API_KEY=your_openai_key

Running the Application

# Development (with hot reload)
npm run start:dev

# Production
npm run build
npm run start:prod

# Debug mode
npm run start:debug

Once running, the API documentation is available at:

http://localhost:3000/api

🔗 API Reference

The full API is documented via Swagger at /api. Below is a high-level overview:

Authentication — /api/v1/auth

Method Endpoint Description
POST /sign-up Register a new user
POST /login Authenticate and receive tokens
POST /logout Invalidate current session
POST /access-token Refresh an expired access token

Account Recovery — /api/v1/auth/recovery

Method Endpoint Description
POST /forgot-password Request a password reset link
POST /reset-password/:userId/:token Reset password with token
POST /verify-email/:userId/:token Verify email address

Users — /api/v1/users

Method Endpoint Description
GET / List all users
GET /:id Get user by ID
POST / Create a new user (admin)

Profile Management — /api/v1/users/profile-management

Method Endpoint Description
PATCH /update-password Change password
PATCH /update-profile Update name and profile fields
PATCH /profile-image Upload profile image (S3)
POST /email-verification/resend Resend email verification

Email Management — /api/v1/users/email

Method Endpoint Description
POST /change/initiate Start email change (sends OTPs)
POST /change/verify Verify and complete email change
POST /change/resend Resend verification codes
DELETE /change/cancel Cancel pending email change

Recovery Email — /api/v1/users/recovery-email

Method Endpoint Description
POST / Add a recovery email
POST /verify Verify recovery email with OTP
POST /remove Request recovery email removal
DELETE / Confirm recovery email removal
POST /verify/resend Resend verification OTP

Account Status — /api/v1/users/account-status

Method Endpoint Description
POST /activate Activate a deactivated account
POST /deactivate Deactivate an active account

Account Settings — /api/v1/users/account-settings

Method Endpoint Description
PATCH /accept-terms Accept terms and conditions
PATCH /notifications/enable Enable notifications
PATCH /notifications/disable Disable notifications
POST /phone/request-verification Request phone verification SMS
PATCH /phone/verify Verify phone number with OTP

Roles Management — /api/v1/users/roles-management

Method Endpoint Description
PATCH /assign-roles/:userId Assign roles to a single user
PATCH /remove-roles/:userId Remove roles from a single user
PATCH /reset-roles/:userId Reset user roles to default
PATCH /bulk-assign Bulk assign roles to multiple users
PATCH /bulk-remove Bulk remove roles from multiple users
GET /:userId/roles Get roles for a user

Account Deletion — /api/v1/account-lifecycle

Method Endpoint Description
POST /deletion-requests Request account deletion
PATCH /deletion-requests/cancel Cancel own deletion request

Deletion Requests Management — /api/v1/account-lifecycle/deletion-requests-management

Method Endpoint Description
GET / List all deletion requests
GET /:id Get a specific deletion request
POST / Create a deletion request (admin)
PATCH /:id/cancel Cancel a deletion request
PATCH /:id/extend-grace-period Extend the grace period
POST /bulk-deletion-requests Bulk create deletion requests
PATCH /bulk-cancel Bulk cancel deletion requests

Moderation — /api/v1/moderation

Method Endpoint Description
GET /actions List all moderation actions
GET /actions/:id Get a specific action
POST /actions Create a moderation action
PATCH /actions/:id Update a moderation action
PATCH /actions/:id/revoke Revoke a moderation action
GET /actions/:id/moderation-history Get moderation history for a user
GET /actions/:id/active-actions Get active actions for a user
DELETE /actions/:id Delete a moderation action

A Postman Collection is also included in the repository.


🔐 Roles & Permissions

Role Description
Super Admin Full system access, admin management, security settings, database operations
Admin User management, shop management, content moderation, advanced reporting
Support Admin Support team management, ticket access, knowledge base, customer service reports
Support Agent Customer inquiries, assigned tickets, customer data updates, notifications
Shop Owner Shop and product management, order processing, inventory, financial reports
User Browse products, place orders, manage profile, communicate with sellers

🧪 Testing

# Unit tests (jest)
npm test

# Watch mode
npm run test:watch

# Coverage report
npm run test:cov

# E2E tests
npm run test:e2e

Note: Test coverage is currently being built out. See the Codebase Insights Report for current coverage status.


📜 Available Scripts

Script Description
npm run build Compile TypeScript to JavaScript
npm run start Start the application
npm run start:dev Start with hot reload (watch mode)
npm run start:debug Start with debugger attached
npm run start:prod Start from compiled output
npm run lint Run ESLint with auto-fix
npm run format Format code with Prettier
npm test Run unit tests
npm run test:cov Run tests with coverage report
npm run test:e2e Run end-to-end tests

🐳 Docker

# Build the image
docker build -t fanous-app .

# Run with docker-compose (PostgreSQL + Redis + App)
docker-compose up

Note: Docker setup is minimal and being improved. Full containerization is on the roadmap.


📊 Codebase Metrics

Metric Value
Source Files 221 TypeScript files
Lines of Code ~23,300
Controllers 13
Services 29
DTOs 36
Entities 4
Modules 11
Commits 116
API Version v1

🗺️ Roadmap

See enhancements/todo.md for the full task list. Key upcoming items:

  • Test suite — Unit and integration test coverage
  • Database migrations — Replace synchronize with TypeORM migrations
  • Email template extraction — Move HTML-in-TypeScript to Handlebars/MJML
  • CI/CD pipeline — GitHub Actions for lint → test → build → deploy
  • Vendor management — Complete vendor/shop CRUD operations
  • Event-driven refactor@nestjs/event-emitter for cross-module communication
  • Docker production setup — Multi-stage builds, docker-compose for local dev
  • Audit logging — Immutable record of who did what and when
  • Real-time notifications — WebSocket/SSE for live updates

📂 Project Structure (Abbreviated)

fanous-app/
├── .github/                  # GitHub workflows (CI/CD)
├── enhancements/             # Audit reports, todo list, best practices guides
├── logging/                  # Log output (gitignored in production)
│   ├── app/                  # Application logs (14-day rotation)
│   ├── exceptions/           # Uncaught exceptions (30-day rotation)
│   └── rejections/           # Unhandled promise rejections (30-day rotation)
├── public/                   # Static assets
├── src/
│   ├── common/               # Shared infrastructure
│   ├── config/               # Configuration & validation
│   ├── health/               # Health check module
│   ├── infrastructure/       # Redis module
│   ├── logs/                 # Logger service
│   ├── modules/              # Feature modules
│   │   ├── account-lifecycle/
│   │   ├── auth/
│   │   ├── moderation/
│   │   ├── users/
│   │   └── vendors/
│   ├── queues/               # BullMQ setup & processors
│   ├── types/                # Global type declarations
│   ├── utils/                # Utility functions
│   └── main.ts               # Bootstrap
├── test/                     # E2E test setup
├── .env                      # Environment variables
├── docker-compose.yml        # Docker compose config
├── Dockerfile                # Docker image definition
├── package.json              # Dependencies & scripts
├── tsconfig.json             # TypeScript configuration
├── Fanous-app.postman_collection.json  # Postman API collection
└── README.md                 # You are here

🤝 Contributing

This is a personal project currently not accepting external contributions. For suggestions or feedback, please open an issue on GitHub.


📄 License

This project is unlicensed and private. All rights reserved.


Built with ❤️ using NestJS — Last updated July 2026

Releases

Packages

Contributors

Languages