Skip to content

Commit fea4f58

Browse files
update apis and docs
1 parent 0d2d360 commit fea4f58

37 files changed

Lines changed: 14593 additions & 10587 deletions

‎.github/workflows/main.yml‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
# name: Docker Build & Deploy (Advanced)
2+
3+
# on:
4+
# push:
5+
# branches:
6+
# - main # Deploy only when code is pushed to main
7+
8+
# jobs:
9+
# deploy:
10+
# runs-on: ubuntu-latest
11+
12+
# steps:
13+
# - name: Checkout Repository
14+
# uses: actions/checkout@v3
15+
16+
# - name: Login to Docker Hub
17+
# uses: docker/login-action@v2
18+
# with:
19+
# username: ${{ secrets.DOCKER_USERNAME }}
20+
# password: ${{ secrets.DOCKER_PASSWORD }}
21+
22+
# - name: Connect & Deploy on Production Server
23+
# uses: appleboy/ssh-action@v0.1.7
24+
# with:
25+
# host: ${{ secrets.SERVER_HOST }}
26+
# username: ${{ secrets.SERVER_USER }}
27+
# key: ${{ secrets.SERVER_SSH_KEY }}
28+
# script_stop: true
29+
# script: |
30+
# set -e # Exit if any command fails
31+
32+
# echo "🚀 Starting KlikyAI API Deployment..."
33+
34+
# PROJECT_PATH="/home/kliky/workingdir/prod/klikyai-api-v3"
35+
# COMPOSE_FILE="$PROJECT_PATH/docker-compose.yaml"
36+
# IMAGE_NAME="klikyai-api-v3"
37+
# IMAGE_TAG="latest"
38+
39+
# echo "📂 Switching to project directory..."
40+
# cd $PROJECT_PATH
41+
42+
# echo "🔐 Checking Git remote access..."
43+
# git remote -v
44+
45+
# echo "🔄 Pulling latest code from branch..."
46+
# # Ensure the server uses SSH for GitHub, not HTTPS
47+
# git remote set-url origin git@github.com:KlikyAI/klikyai-api-v3.git
48+
# git fetch origin main
49+
# git reset --hard origin/main
50+
51+
# echo "🧹 Stopping running containers..."
52+
# docker compose -f $COMPOSE_FILE down
53+
54+
# echo "⚙️ Building fresh Docker image..."
55+
# docker compose -f $COMPOSE_FILE build --no-cache
56+
57+
# echo "🚀 Starting updated containers..."
58+
# docker compose -f $COMPOSE_FILE up -d
59+
60+
# echo "⏳ Waiting 10 seconds before starting health checks..."
61+
# sleep 10
62+
63+
# echo "⏳ Checking API health..."
64+
# HEALTH_URL="https://generator.klikyai.app/dev/v3/health"
65+
# MAX_RETRIES=15
66+
# RETRY_DELAY=10
67+
# HEALTH_OK=false
68+
69+
# for i in $(seq 1 $MAX_RETRIES); do
70+
# STATUS_CODE=$(curl -o /dev/null -s -w "%{http_code}" "$HEALTH_URL")
71+
# if [ "$STATUS_CODE" = "200" ]; then
72+
# echo "✅ API is healthy (HTTP $STATUS_CODE)"
73+
# HEALTH_OK=true
74+
# break
75+
# else
76+
# echo "Waiting for API to respond... ($i/$MAX_RETRIES)"
77+
# sleep $RETRY_DELAY
78+
# fi
79+
# done
80+
81+
# if [ "$HEALTH_OK" != true ]; then
82+
# echo "❌ Health check failed after $MAX_RETRIES attempts."
83+
# docker compose logs
84+
# exit 1
85+
# fi
86+
87+
# echo "🪣 Pushing image to Docker Hub..."
88+
# docker compose -f $COMPOSE_FILE push
89+
90+
# echo "✅ Deployment completed successfully!"

‎README.md‎

Lines changed: 199 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
> **Enterprise-Grade Node.js Backend API with Advanced Features**
1212
13-
Node.js Backend is a comprehensive, production-ready RESTful API built with Express.js, featuring JWT authentication, role-based access control, real-time activity logging, advanced security middleware, and comprehensive monitoring capabilities.
13+
Node.js Backend is a comprehensive, production-ready RESTful API built with Express.js, featuring JWT authentication with Instagram-style multi-token pattern, role-based access control, real-time activity logging, advanced security middleware, and comprehensive monitoring capabilities.
1414

1515
**Repository**: [https://github.com/fullstack-open-source/nodejs-backend-with-sql](https://github.com/fullstack-open-source/nodejs-backend-with-sql)
1616

@@ -19,10 +19,12 @@ Node.js Backend is a comprehensive, production-ready RESTful API built with Expr
1919
- [🚀 Features](#-features)
2020
- [🏗️ Architecture](#️-architecture)
2121
- [System Architecture](#system-architecture)
22+
- [Authentication Architecture](#authentication-architecture)
2223
- [Request Flow](#request-flow)
2324
- [Middleware Stack](#middleware-stack)
2425
- [Database Architecture](#database-architecture)
2526
- [Module Structure](#module-structure)
27+
- [📚 API Documentation](#-api-documentation)
2628
- [📦 Installation & Setup](#-installation--setup)
2729
- [Prerequisites](#prerequisites)
2830
- [Quick Start](#quick-start)
@@ -39,14 +41,15 @@ Node.js Backend is a comprehensive, production-ready RESTful API built with Expr
3941
### 🎯 Core Capabilities
4042

4143
- **RESTful API**: Comprehensive REST API with Express.js framework
42-
- **JWT Authentication**: Secure token-based authentication system
44+
- **JWT Authentication**: Instagram-style multi-token authentication system (Access, Session, Refresh tokens)
4345
- **Role-Based Access Control**: Flexible permission system with groups and permissions
4446
- **Activity Logging**: Comprehensive audit trail with detailed metadata
4547
- **File Upload**: Google Cloud Storage integration for media files
46-
- **Email & SMS**: Twilio and Nodemailer integration for notifications
48+
- **Email & SMS**: Twilio and Nodemailer integration for notifications and OTP
4749
- **Error Tracking**: Sentry integration for production monitoring and error tracking
4850
- **API Documentation**: Auto-generated Swagger/OpenAPI documentation
49-
- **Request Queue**: Rate limiting and request queuing for traffic management
51+
- **Multilingual Support**: Multi-language API responses with automatic translation
52+
- **Rate Limiting**: Request throttling and rate limiting for traffic management
5053
- **Worker Pool**: CPU-intensive task processing with worker threads
5154
- **Docker Ready**: Production-ready containerization with multi-stage builds
5255
- **PM2 Support**: Process management with cluster mode for high availability
@@ -65,6 +68,17 @@ Node.js Backend is a comprehensive, production-ready RESTful API built with Expr
6568
- **CORS**: Cross-origin resource sharing with whitelist validation
6669
- **Swagger**: Interactive API documentation with Swagger UI
6770
- **Nginx Reverse Proxy**: Production-ready reverse proxy configuration
71+
- **Multilingual**: Multi-language support for API responses (English, Arabic, and more)
72+
73+
### 🔐 Authentication Features
74+
75+
- **Multi-Token System**: Access token (1 hour), Session token (7 days), Refresh token (30 days)
76+
- **Token Blacklisting**: Redis-based token invalidation for secure logout
77+
- **OTP Verification**: Email, SMS, and WhatsApp OTP support
78+
- **Password Management**: Set, change, and reset password functionality
79+
- **Email/Phone Verification**: Two-step verification for contact changes
80+
- **Session Management**: Stateless session management with unique session IDs
81+
- **Token Rotation**: Automatic token rotation on refresh for enhanced security
6882

6983
### 🗄️ Database Support & Flexibility
7084

@@ -257,8 +271,8 @@ The system follows a layered architecture with clear separation of concerns:
257271
│ (Prisma ORM) │ │ (Sessions, Cache) │
258272
│ - User Data │ │ - Session Storage │
259273
│ - Permissions │ │ - OTP Cache │
260-
│ - Activity Logs │ │ - Rate Limiting │
261-
│ - Groups │ │ - Temporary Data │
274+
│ - Activity Logs │ │ - Token Blacklist │
275+
│ - Groups │ │ - Rate Limiting │
262276
└──────────────────────────┘ └──────────────────────────┘
263277
│
264278
▼
@@ -271,6 +285,19 @@ The system follows a layered architecture with clear separation of concerns:
271285
└──────────────────────────┘
272286
```
273287

288+
### Authentication Architecture
289+
290+
The authentication system implements a **stateless, multi-token architecture** similar to Instagram:
291+
292+
**Key Features:**
293+
- **Multi-Token System**: Access token (1 hour), Session token (7 days), Refresh token (30 days)
294+
- **Token Blacklisting**: Redis-based cache for token invalidation
295+
- **Session Management**: Unique session_id links all tokens together
296+
- **Token Rotation**: Refresh tokens rotate on each refresh for security
297+
- **Origin Validation**: Domain-specific token validation
298+
299+
**Complete Documentation**: See [Authentication Router](./api/router/authenticate/authenticate.md)
300+
274301
### Request Flow
275302

276303
```
@@ -508,6 +535,9 @@ NodeJs Backend API
508535
│ │ │ ├── debug.js # Debug utilities
509536
│ │ │ └── workerUtils.js # Worker pool utilities
510537
│ │ │
538+
│ │ ├── 🌐 multilingual/ # Multilingual support
539+
│ │ │ └── multilingual.js # Language utilities
540+
│ │ │
511541
│ │ └── 👷 workers/ # Worker threads
512542
│ │ ├── workerPool.js # Worker pool manager
513543
│ │ └── cpuTaskWorker.js # CPU task worker
@@ -541,6 +571,125 @@ NodeJs Backend API
541571
└── 📄 README.md # This file
542572
```
543573

574+
## 📚 API Documentation
575+
576+
### Authentication & User Management
577+
578+
**Complete Documentation**: [Authentication Router](./api/router/authenticate/authenticate.md)
579+
580+
**Endpoints:**
581+
- `POST /{MODE}/auth/login-with-password` - Login with email/phone and password
582+
- `POST /{MODE}/auth/login-with-otp` - Login with OTP
583+
- `POST /{MODE}/auth/send-one-time-password` - Send OTP via email/SMS/WhatsApp
584+
- `POST /{MODE}/auth/verify-one-time-password` - Verify OTP
585+
- `POST /{MODE}/auth/verify` - Signup/Register with OTP
586+
- `POST /{MODE}/auth/set-password` - Set password for authenticated user
587+
- `POST /{MODE}/auth/change-password` - Change user password
588+
- `POST /{MODE}/auth/forget-password` - Reset password with OTP
589+
- `POST /{MODE}/auth/refresh-token` - Refresh access tokens
590+
- `POST /{MODE}/auth/logout` - Logout and revoke tokens
591+
- `POST /{MODE}/auth/token-info` - Get token information
592+
- `POST /{MODE}/auth/check-user-availability` - Check email/phone availability
593+
- `POST /{MODE}/auth/verify-email-and-phone` - Verify email/phone with OTP
594+
595+
**Profile Management**: [Profile Router](./api/router/authenticate/profile.md)
596+
597+
**Endpoints:**
598+
- `GET /{MODE}/settings/profile` - Get user profile
599+
- `GET /{MODE}/settings/profile/{user_id}` - Get profile by ID
600+
- `POST /{MODE}/settings/profile-picture` - Update profile picture
601+
- `PUT /{MODE}/settings/profile` - Update user profile
602+
- `POST /{MODE}/settings/change-email` - Change email with OTP verification
603+
- `POST /{MODE}/settings/change-phone` - Change phone with OTP verification
604+
- `POST /{MODE}/settings/profile-accessibility` - Update profile accessibility
605+
- `POST /{MODE}/settings/profile-language` - Update profile language
606+
- `POST /{MODE}/settings/update-theme` - Update theme preference
607+
- `POST /{MODE}/settings/update-timezone` - Update timezone
608+
- `GET /{MODE}/settings` - Get user settings
609+
- `POST /{MODE}/settings/deactivate-account` - Deactivate account
610+
- `POST /{MODE}/settings/delete-account` - Delete account
611+
612+
### Permissions & Groups
613+
614+
**Complete Documentation**: [Permissions Router](./api/router/permissions/permissions.md)
615+
616+
**Endpoints:**
617+
- `GET /{MODE}/permissions` - Get all permissions
618+
- `GET /{MODE}/permissions/{permission_id}` - Get permission by ID
619+
- `POST /{MODE}/permissions` - Create new permission
620+
- `PUT /{MODE}/permissions/{permission_id}` - Update permission
621+
- `DELETE /{MODE}/permissions/{permission_id}` - Delete permission
622+
- `GET /{MODE}/groups` - Get all groups
623+
- `GET /{MODE}/groups/{group_id}` - Get group by ID
624+
- `POST /{MODE}/groups` - Create new group
625+
- `PUT /{MODE}/groups/{group_id}` - Update group
626+
- `DELETE /{MODE}/groups/{group_id}` - Delete group
627+
- `POST /{MODE}/groups/{group_id}/permissions` - Assign permissions to group
628+
- `GET /{MODE}/users/{user_id}/groups` - Get user groups
629+
- `GET /{MODE}/users/{user_id}/permissions` - Get user permissions
630+
- `POST /{MODE}/users/{user_id}/groups` - Assign groups to user
631+
- `GET /{MODE}/users/me/groups` - Get current user groups
632+
- `GET /{MODE}/users/me/permissions` - Get current user permissions
633+
634+
### Dashboard & Analytics
635+
636+
**Complete Documentation**: [Dashboard Router](./api/router/dashboard/dashboard.md)
637+
638+
**Endpoints:**
639+
- `GET /{MODE}/dashboard/overview` - Get dashboard overview statistics
640+
- `GET /{MODE}/dashboard/users-by-status` - Get users grouped by status
641+
- `GET /{MODE}/dashboard/users-by-type` - Get users grouped by type
642+
- `GET /{MODE}/dashboard/users-by-auth-type` - Get users grouped by auth type
643+
- `GET /{MODE}/dashboard/users-by-country` - Get users grouped by country
644+
- `GET /{MODE}/dashboard/users-by-language` - Get users grouped by language
645+
- `GET /{MODE}/dashboard/user-growth` - Get user growth statistics
646+
- `GET /{MODE}/dashboard/role-statistics` - Get role/group statistics
647+
- `GET /{MODE}/dashboard/recent-sign-ins` - Get recent sign-in activity
648+
- `GET /{MODE}/dashboard/all-statistics` - Get all statistics
649+
650+
### File Upload
651+
652+
**Complete Documentation**: [Upload Router](./api/router/upload/upload.md)
653+
654+
**Endpoints:**
655+
- `POST /{MODE}/upload/media` - Upload media file (direct upload or URL)
656+
- `DELETE /{MODE}/upload/media/{file_id}` - Delete uploaded media
657+
658+
**Features:**
659+
- Direct file upload with multipart/form-data
660+
- URL-based upload (downloads and stores file from URL)
661+
- Google Cloud Storage integration
662+
- Automatic file validation and processing
663+
- Support for images, videos, and documents
664+
665+
### Activity Logging
666+
667+
**Complete Documentation**: [Activity Router](./api/router/activity/activity.md)
668+
669+
**Endpoints:**
670+
- `GET /{MODE}/activity` - Get activity logs with filtering
671+
- `GET /{MODE}/activity/{log_id}` - Get specific activity log
672+
- `POST /{MODE}/activity` - Create activity log entry
673+
674+
**Features:**
675+
- Comprehensive audit trail
676+
- User action tracking
677+
- Request/response logging
678+
- Error logging with details
679+
- Metadata storage (JSONB)
680+
681+
### Health Monitoring
682+
683+
**Complete Documentation**: [Health Router](./api/router/health/health.md)
684+
685+
**Endpoints:**
686+
- `GET /health` - Basic health check (no prefix)
687+
- `GET /{MODE}/health` - Detailed health check
688+
- `GET /{MODE}/health/system` - System health with metrics
689+
- `GET /{MODE}/health/database` - Database connection health
690+
- `GET /{MODE}/health/storage` - Storage (GCS) health check
691+
- `GET /{MODE}/health/test-sentry` - Test Sentry integration
692+
544693
## 📦 Installation & Setup
545694

546695
### Prerequisites
@@ -1191,6 +1340,7 @@ docker network inspect nodejs_backend_with_postgresql_network
11911340
│ │ │ Cache Storage │ │ │
11921341
│ │ │ - OTP cache │ │ │
11931342
│ │ │ - Session storage │ │ │
1343+
│ │ │ - Token blacklist │ │ │
11941344
│ │ │ - Rate limiting data │ │ │
11951345
│ │ └──────────────────────────────────────────────────┘ │ │
11961346
│ └────────────────────────────────────────────────────────┘ │
@@ -1249,6 +1399,49 @@ Port 9080 (Host) ──► Nginx ──► Port 3000 ──► API Service
12491399
└─► Redis (Port 6379)
12501400
```
12511401

1402+
## 🔐 Authentication System
1403+
1404+
### Multi-Token Architecture
1405+
1406+
The authentication system uses a **three-token approach** similar to Instagram:
1407+
1408+
1. **Access Token** (1 hour)
1409+
- Lightweight token for API authentication
1410+
- Minimal payload for fast validation
1411+
- Includes JTI (JWT ID) for efficient blacklisting
1412+
1413+
2. **Session Token** (7 days) - **Recommended**
1414+
- Contains full user profile and permissions
1415+
- Fastest validation (no database lookup needed)
1416+
- Preferred for frontend API calls
1417+
1418+
3. **Refresh Token** (30 days)
1419+
- Used to obtain new tokens when they expire
1420+
- Cannot be used for API authentication
1421+
- Rotates on each refresh for security
1422+
1423+
**Complete Documentation**: [Authentication Router](./api/router/authenticate/authenticate.md)
1424+
1425+
### Token Usage
1426+
1427+
**Recommended Approach (Session Token):**
1428+
```javascript
1429+
// Store tokens after login
1430+
{
1431+
"access_token": "...",
1432+
"session_token": "...", // RECOMMENDED for API calls
1433+
"refresh_token": "...",
1434+
"session_id": "..."
1435+
}
1436+
1437+
// Use session_token for API calls (fastest validation)
1438+
headers = {
1439+
"X-Session-Token": session_token // Preferred
1440+
// OR
1441+
"Authorization": `Bearer ${session_token}` // Also works
1442+
}
1443+
```
1444+
12521445
---
12531446

12541447
## 📄 License & Open Source

0 commit comments

Comments
 (0)