12 KiB
Yaltopia Tickets Backend API
Enterprise-grade backend service for ticket and receipt verification system with advanced authentication, role-based access control, and universal database adapter architecture.
Overview
This API provides a robust foundation for ticket verification systems with enterprise-level security, scalability, and maintainability. Built with modern TypeScript and NestJS framework, it features a unique universal adapter pattern that allows seamless switching between different database providers without code changes.
Core Features
Authentication & Security
- JWT-based Authentication with configurable expiration
- Multi-factor Authentication via OTP integration
- Role-based Access Control (RBAC) with hierarchical permissions
- Password Security with bcrypt hashing
- API Documentation with Swagger/OpenAPI 3.0
User Management
- Hierarchical Role System: System Admin → Business Owner → Staff → Auditor
- Granular Permissions with role-based endpoint access
- User Lifecycle Management with soft deletion
- Team Management capabilities for business owners
Architecture Highlights
- Universal Database Adapter - Switch between PostgreSQL, MongoDB, or other providers
- Provider-Agnostic Design - No vendor lock-in
- Microservice-Ready architecture with modular design
- Production-Grade error handling and logging
- Type-Safe implementation with comprehensive TypeScript coverage
Technology Stack
| Component | Technology | Version |
|---|---|---|
| Runtime | Node.js | 18+ |
| Framework | NestJS | 10.x |
| Language | TypeScript | 5.1+ |
| Database | PostgreSQL | 13+ |
| ORM | Prisma | 5.7+ |
| Cache | Redis | 6+ |
| Queue | BullMQ | 4.x |
| Authentication | JWT + Supabase | Latest |
| Documentation | Swagger/OpenAPI | 3.0 |
| Testing | Jest | 29+ |
Getting Started
Prerequisites
Ensure your development environment meets these requirements:
- Node.js 18.0 or higher
- PostgreSQL 13.0 or higher
- Redis 6.0 or higher
- npm or yarn package manager
Installation
-
Clone the repository
git clone https://gitea.yaltopia.com/DebelaH/Yaltopia-Tickets-Backend.git cd Yaltopia-Tickets-Backend -
Install dependencies
npm install -
Environment configuration
cp .env.example .envConfigure the following required environment variables:
DATABASE_URL="postgresql://username:password@localhost:5432/database_name" JWT_SECRET="your-secure-jwt-secret-key" SUPABASE_URL="https://your-project.supabase.co" SUPABASE_ANON_KEY="your-supabase-anon-key" REDIS_URL="redis://localhost:6379" -
Database setup
npx prisma generate npx prisma db push -
Start the application
# Development npm run start:dev # Production npm run build npm run start:prod
The API will be available at http://localhost:3000 with documentation at http://localhost:3000/api
API Documentation
Authentication Endpoints
| Method | Endpoint | Description | Access |
|---|---|---|---|
POST |
/api/v1/auth/login |
User authentication | Public |
POST |
/api/v1/auth/register |
User registration | Admin Only |
POST |
/api/v1/auth/request-otp |
Request OTP verification | Public |
POST |
/api/v1/auth/verify-otp |
Verify OTP and authenticate | Public |
GET |
/api/v1/auth/profile |
Get current user profile | Authenticated |
GET |
/api/v1/auth/validate |
Validate JWT token | Authenticated |
User Management Endpoints
| Method | Endpoint | Description | Access |
|---|---|---|---|
GET |
/api/v1/users |
List users (role-filtered) | Authenticated |
GET |
/api/v1/users/:id |
Get user by ID | Authenticated |
POST |
/api/v1/users/staff |
Create staff/auditor | Owner+ |
PATCH |
/api/v1/users/:id |
Update user | Owner+ |
DELETE |
/api/v1/users/:id |
Deactivate user | Owner+ |
GET |
/api/v1/users/my-staff |
Get owner's staff | Owner+ |
Role-Based Access Control
Role Hierarchy
System Admin (Level 4)
├── Full system access
├── Manage all users and data
└── System configuration
Business Owner (Level 3)
├── Create and manage staff
├── View business reports
├── Manage business data
└── Verify transactions
Staff (Level 2)
├── Upload and process tickets
├── View assigned data
└── Basic verification tasks
Auditor (Level 1)
├── Read-only access to reports
├── View tickets for auditing
└── No modification permissions
Permission Matrix
| Action | System Admin | Business Owner | Staff | Auditor |
|---|---|---|---|---|
| Create Users | ✅ | ✅ (Staff only) | ❌ | ❌ |
| View All Users | ✅ | ✅ (Own staff) | ❌ | ❌ |
| Modify Users | ✅ | ✅ (Own staff) | ❌ | ❌ |
| View Reports | ✅ | ✅ (Own business) | ❌ | ✅ (Read-only) |
| System Config | ✅ | ❌ | ❌ | ❌ |
Architecture
Universal Database Adapter
The system implements a unique universal adapter pattern that provides database-agnostic operations:
// Switch providers with environment variables only
DATABASE_PROVIDER=prisma # PostgreSQL with Prisma
DATABASE_PROVIDER=supabase # Supabase (PostgreSQL + Auth)
DATABASE_PROVIDER=mongodb # MongoDB (Future)
Benefits:
- Zero Code Changes when switching providers
- No Vendor Lock-in - migrate between services seamlessly
- Future-Proof architecture for evolving requirements
- Cost Optimization - switch to most cost-effective provider
Project Structure
src/
├── features/ # Feature-based modules
│ ├── auth/ # Authentication & authorization
│ │ ├── guards/ # JWT and role guards
│ │ ├── strategies/ # Passport strategies
│ │ └── dto/ # Data transfer objects
│ └── users/ # User management
│ ├── dto/ # User DTOs
│ └── services/ # Business logic
├── shared/ # Shared utilities and services
│ ├── adapters/ # Universal database adapter
│ ├── repositories/ # Data access layer
│ ├── factories/ # Provider factories
│ ├── interfaces/ # Type definitions
│ ├── services/ # Shared services (Redis, Prisma)
│ ├── guards/ # Authentication guards
│ ├── decorators/ # Custom decorators
│ └── config/ # Configuration modules
└── prisma/ # Database schema and migrations
Database Schema
Core Entities
-- Users table with role-based access
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email VARCHAR UNIQUE NOT NULL,
password_hash VARCHAR NOT NULL,
role user_role NOT NULL,
full_name VARCHAR NOT NULL,
is_active BOOLEAN DEFAULT true,
created_by UUID REFERENCES users(id),
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
-- Enum for user roles
CREATE TYPE user_role AS ENUM (
'SYSTEM_ADMIN',
'BUSINESS_OWNER',
'STAFF',
'AUDITOR'
);
Development
Available Scripts
# Development
npm run start:dev # Start with hot reload
npm run start:debug # Start with debugging
# Production
npm run build # Build for production
npm run start:prod # Start production server
# Database
npm run prisma:generate # Generate Prisma client
npm run prisma:push # Push schema to database
npm run prisma:migrate # Run database migrations
npm run prisma:studio # Open Prisma Studio
# Code Quality
npm run lint # Run ESLint
npm run format # Format code with Prettier
npm run test # Run unit tests
npm run test:e2e # Run end-to-end tests
npm run test:cov # Run tests with coverage
# Provider Management
npm run migrate:provider # Migrate between database providers
npm run health:check # Check system health
Environment Configuration
Development Environment
NODE_ENV=development
PORT=3000
DATABASE_PROVIDER=prisma
DATABASE_URL="postgresql://user:pass@localhost:5432/yaltopia_dev"
JWT_SECRET="dev-secret-key"
REDIS_URL="redis://localhost:6379"
Production Environment
NODE_ENV=production
PORT=3000
DATABASE_PROVIDER=prisma
DATABASE_URL="postgresql://user:pass@prod-db:5432/yaltopia_prod"
JWT_SECRET="secure-production-secret"
REDIS_URL="redis://prod-redis:6379"
Security Features
Authentication Security
- JWT Tokens with configurable expiration
- Password Hashing using bcrypt with salt rounds
- OTP Verification for enhanced security
- Role-based Route Protection with guards
API Security
- CORS Protection with configurable origins
- Request Validation using class-validator
- Rate Limiting (recommended for production)
- Helmet.js for security headers
- Input Sanitization to prevent injection attacks
Data Security
- Environment Variable Protection - no secrets in code
- Database Connection Encryption with SSL
- Audit Logging for sensitive operations
- Soft Deletion to maintain data integrity
Deployment
Docker Deployment
# Production Dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY dist ./dist
EXPOSE 3000
CMD ["node", "dist/main"]
Environment Setup
-
Database Setup
# PostgreSQL with Docker docker run -d \ --name yaltopia-postgres \ -e POSTGRES_DB=yaltopia \ -e POSTGRES_USER=admin \ -e POSTGRES_PASSWORD=secure_password \ -p 5432:5432 \ postgres:13 -
Redis Setup
# Redis with Docker docker run -d \ --name yaltopia-redis \ -p 6379:6379 \ redis:6-alpine -
Application Deployment
# Build and deploy npm run build npm run start:prod
Monitoring & Observability
Health Checks
- Database Connectivity monitoring
- Redis Connection status
- Service Dependencies health verification
- API Response Time tracking
Logging
- Structured Logging with Winston
- Request/Response Logging for debugging
- Error Tracking with stack traces
- Performance Metrics collection
Contributing
Development Workflow
- Fork the repository
- Create a feature branch
git checkout -b feature/your-feature-name - Make your changes
- Run tests and linting
npm run test npm run lint - Commit your changes
git commit -m "feat: add your feature description" - Push to your fork
- Create a Pull Request
Code Standards
- TypeScript strict mode enabled
- ESLint configuration enforced
- Prettier for code formatting
- Conventional Commits for commit messages
- Unit Tests required for new features
Support & Maintenance
Version Support
- Current Version: 1.0.0
- Node.js: 18.x LTS (recommended)
- Database: PostgreSQL 13+ (primary), MongoDB (future)
- Security Updates: Applied within 48 hours
Contact Information
- Development Team: Yaltopia Backend Team
- Repository: https://gitea.yaltopia.com/DebelaH/Yaltopia-Tickets-Backend
- Issues: Use GitHub Issues for bug reports and feature requests
© 2025 Yaltopia. All rights reserved.