Enterprise-ready, scalable RESTful API engine for Article Publishing with Role-Based Access Control (RBAC), Dual-Token JWT Authentication, Google Gemini AI Content Generation, and Supabase Cloud Storage.
β¨ Key Features β’ ποΈ System Architecture β’ π Project Structure β’ β‘ Quick Start β’ π API Reference β’ ποΈ Database Schema β’ π‘οΈ Security & Reliability
The ITS2020 RAD Article Backend API is an asynchronous, strongly-typed RESTful microservice built using Express 5 and TypeScript. Developed as part of the Rapid Application Development (RAD) curriculum, this backend provides a robust foundation for modern digital publishing platforms.
It features complete separation of concerns via a clean Controller-Service-Router-Model architecture, complete with Google Gemini Flash AI integration for autonomous summary generation, Supabase Object Storage for media uploads, and Dockerized MongoDB database persistence.
- π Dual-Token JWT Authentication: Secure access token generation (
30mlifespan) and persistent refresh token rotation (7dlifespan) usingbcryptjsfor salted password hashing. - π‘οΈ Role-Based Access Control (RBAC): Fine-grained authorization middleware checking roles across
ADMIN,WRITTER, andUSER. - π€ Google Gemini AI Integration: Powered by
@google/genai(gemini-3.5-flash-lite) to dynamically generate article descriptions and summaries from prompt keywords. - βοΈ Supabase Cloud Storage with Fallback: Memory-stream image uploads via
multerto Supabase Storage with graceful automatic fallback to Base64 data URIs. - π Paginated & Populated Article Feed: High-performance querying with Mongoose pagination (
page,limit), metadata calculations, and author population. - π³ Containerized MongoDB: Includes a production-ready
docker-compose.ymlfor isolated MongoDB 7.0 database deployment. - π Network Resilience: Integrated custom DNS resolution fallback (
8.8.8.8) ensuring dependable connection strings for MongoDB clusters and external APIs.
flowchart TD
Client["Client Applications<br/>(React / Mobile / cURL / Postman)"]
subgraph ExpressGateway["Express 5 Server (Node.js & TypeScript)"]
Cors["CORS & express.json()"]
AuthMiddleware["authenticate Middleware<br/>(JWT Verification)"]
RoleMiddleware["requireRole Middleware<br/>(RBAC Guard)"]
UploadMiddleware["Multer Memory Storage<br/>(Single File 'image')"]
subgraph Controllers["Controller Layer"]
AuthController["Auth Controller<br/>register, login, refresh, me"]
ArticleController["Article Controller<br/>create, getAll, aiGenerate"]
end
subgraph ServiceLayer["Service & Utility Layer"]
AIService["Google Gemini Service<br/>(gemini-3.5-flash-lite)"]
StorageService["Supabase Upload Service<br/>(Object Bucket + Base64 Fallback)"]
JWTUtil["JWT Utilities<br/>(signAccessToken, signRefreshToken)"]
end
end
subgraph DataPersistence["External & Cloud Services"]
MongoDB[("MongoDB 7.0<br/>(Users & Articles Collections)")]
SupabaseBucket[("Supabase Storage<br/>('articles' bucket)")]
GeminiAPI["Google Gemini AI Engine"]
end
Client -->|HTTP Requests| Cors
Cors --> AuthController
Cors --> UploadMiddleware --> AuthMiddleware --> RoleMiddleware --> ArticleController
AuthController --> JWTUtil
AuthController --> MongoDB
ArticleController --> AIService --> GeminiAPI
ArticleController --> StorageService --> SupabaseBucket
ArticleController --> MongoDB
rad-article-api/
βββ .env # Local environment secrets (ignored by git)
βββ .example.env # Sample environment configuration template
βββ .gitignore # Git ignore rules for node_modules & logs
βββ docker-compose.yml # MongoDB 7.0 container specification
βββ package.json # Dependencies, scripts, and project metadata
βββ tsconfig.json # TypeScript compiler configuration
βββ src/
βββ index.ts # Application entry point & database connection
βββ config/
β βββ superbase.ts # Supabase client initialization
βββ controllers/
β βββ article.controller.ts # Article creation, pagination, AI generation
β βββ auth.controller.ts # Authentication, login, register, token refresh
βββ middleware/
β βββ auth.ts # Bearer token verification & user attachment
β βββ role.ts # Role-based access control (RBAC) guard
β βββ upload.ts # Multer in-memory file upload handler
βββ models/
β βββ article.model.ts # Mongoose Article schema & TypeScript interface
β βββ user.model.ts # Mongoose User schema, UserRole enum & interface
βββ routes/
β βββ article.routers.ts # Article endpoints (/api/v1/article)
β βββ auth.routers.ts # Auth endpoints (/api/v1/auth)
βββ services/
β βββ ai.service.ts # Google Gemini Flash generative content service
β βββ storage.service.ts # Storage export abstraction
β βββ upload.service.ts # Supabase cloud upload with fallback logic
βββ util/
βββ jwt_token.ts # Access and refresh token generation & verification
| Category | Technology | Purpose |
|---|---|---|
| Runtime & Language | Node.js 22+ / TypeScript 7.x | Type-safe asynchronous JavaScript runtime |
| Development Engine | tsx | Ultra-fast TypeScript watcher & executor without manual build steps |
| Framework | Express 5.2 | Next-generation minimalist web application framework |
| Database & ODM | MongoDB 7.0 / Mongoose 9.10 | NoSQL Document database with schema modeling |
| Artificial Intelligence | @google/genai 2.31 | Generative AI SDK using gemini-3.5-flash-lite |
| Cloud Storage | @supabase/supabase-js 2.118 | Cloud object storage bucket integration for media assets |
| Authentication & Crypto | jsonwebtoken / bcryptjs | JWT dual token signing and salted password hashing |
| File Handling | multer 2.4 | Multipart/form-data middleware using memory storage buffer |
| Containerization | Docker & Docker Compose | Local containerized MongoDB service environment |
Ensure you have the following installed on your machine:
- Node.js: v18.0.0 or higher
- npm or pnpm or yarn
- Docker Desktop (optional, for local MongoDB container)
git clone https://github.com/chathunga2007/ITS2020-RAD-Article-Backend.git
cd ITS2020-RAD-Article-Backend
npm installdocker compose up -dThis starts MongoDB 7.0 on port
27017with credentialsadmin/1234.
Copy .example.env to .env and provide your secrets:
cp .example.env .envEdit your .env file:
PORT=3000
MONGO_LOCAL_URL=mongodb://admin:1234@localhost:27017/rad_article_db?authSource=admin
JWT_SECRET=super_secret_access_jwt_key_32_characters_long
JWT_REFRESH_SECRET=super_secret_refresh_jwt_key_32_characters_long
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_KEY=your-supabase-service-or-anon-key
GEMINI_API_KEY=your-google-gemini-api-keynpm run devThe server will boot with live reload on:
DB connected..!
Server is running on http://localhost:3000
Base URL: http://localhost:3000/api/v1
Registers a new user in the system with encrypted password and default USER role.
- Method:
POST - URL:
/api/v1/auth/register - Request Body:
{ "name": "Chathunga Bimsara", "email": "chathunga@example.com", "password": "Password123!" } - Response (201 Created):
{ "message": "User registered successfully..!" }
Authenticates user credentials and issues both Access Token and Refresh Token.
- Method:
POST - URL:
/api/v1/auth/login - Request Body:
{ "email": "chathunga@example.com", "password": "Password123!" } - Response (200 OK):
{ "message": "OK", "data": { "email": "chathunga@example.com", "roles": ["USER"], "access_token": "eyJhbGciOiJIUzI1NiIsIn...", "refresh_token": "eyJhbGciOiJIUzI1NiIsIn..." } }
Issues a new Access Token using a valid Refresh Token.
- Method:
POST - URL:
/api/v1/auth/refresh - Request Body:
{ "refreshToken": "eyJhbGciOiJIUzI1NiIsIn..." } - Response (200 OK):
{ "data": { "accessToken": "eyJhbGciOiJIUzI1NiIsIn..." } }
Retrieves authenticated user profile information based on token payload.
- Method:
GET - URL:
/api/v1/auth/me - Headers:
Authorization: Bearer <ACCESS_TOKEN> - Response (200 OK):
{ "message": "ok", "data": { "id": "670498bf89f1...", "email": "chathunga@example.com", "roles": ["USER"] } }
Uploads an article with optional image banner. Requires authentication and any role of (ADMIN, WRITTER, USER).
- Method:
POST - URL:
/api/v1/article/create - Headers:
Authorization: Bearer <ACCESS_TOKEN>Content-Type: multipart/form-data
- Form-Data Body:
title:Understanding Rapid Application Developmentcontent:Full Markdown or HTML content for the article...tags:TypeScript, RAD, Node.js(or JSON array["TypeScript", "RAD"])image: (File: binary image)
- Response (201 Created):
{ "_id": "6705128df01a...", "title": "Understanding Rapid Application Development", "content": "Full Markdown or HTML content for the article...", "author": "670498bf89f1...", "imageURL": "https://xyz.supabase.co/storage/v1/object/public/articles/uuid-photo.jpg", "tags": ["TypeScript", "RAD", "Node.js"], "isVisible": true, "favorites": [], "createdAt": "2026-10-27T08:30:00.000Z", "updatedAt": "2026-10-27T08:30:00.000Z" }
Fetches public visible articles sorted by latest first with author info.
- Method:
GET - URL:
/api/v1/article?page=1&limit=10 - Response (200 OK):
{ "data": [ { "_id": "6705128df01a...", "title": "Understanding Rapid Application Development", "content": "Full Markdown or HTML content...", "author": { "_id": "670498bf89f1...", "name": "Chathunga Bimsara", "email": "chathunga@example.com" }, "imageURL": "https://xyz.supabase.co/storage/v1/object/public/articles/banner.png", "tags": ["TypeScript", "RAD"], "isVisible": true, "createdAt": "2026-10-27T08:30:00.000Z" } ], "meta": { "total": 42, "page": 1, "limit": 10, "totalPages": 5 } }
Generates a concise article summary or concept definition using Google Gemini AI.
- Method:
POST - URL:
/api/v1/article/ai - Request Body:
{ "text": "Microservices Architecture in Node.js" } - Response (200 OK):
{ "data": "Microservices architecture in Node.js is a design pattern where an application is broken down into small, independently deployable services that communicate over lightweight protocols such as HTTP REST or message queues..." }
interface IUser {
name: string; // Full user name
email: string; // Unique indexed email address
password: string; // Bcrypt hashed password string
roles: UserRole[]; // ["ADMIN" | "WRITTER" | "USER"]
approve: boolean; // Account activation status
createdAt: Date; // Managed by Mongoose timestamps
updatedAt: Date;
}interface IArticle {
title: string; // Article headline
content: string; // Main body content
author: Types.ObjectId; // References system_users collection
imageURL: string; // Supabase Public CDN URL or Base64 URI
tags: string[]; // Searchable keywords
isVisible: boolean; // Visibility switch (default: true)
favorites: Types.ObjectId[]; // References to liking users
createdAt: Date;
updatedAt: Date;
}- Salted Password Hashing: Passwords are never stored as plain text. Every password undergoes 10 salt rounds with
bcryptjs. - JWT Protection with Expiration: Access tokens are kept short-lived (
30 minutes) to mitigate token-theft risks. Long-lived refresh tokens (7 days) can generate fresh tokens without re-authenticating. - DNS Resolution Safeguard: Resolves SRV / lookup issues encountered when connecting to remote cloud MongoDB clusters through Google DNS servers (
8.8.8.8). - Resilient Media Storage Fallback: In case of network interruptions or permission errors with Supabase Storage, the upload handler safely encodes the image into an inline Data URI (
data:${mimetype};base64,...) without dropping article creation.
- Developer: Chathunga Bimsara
- GitHub: @chathunga2007
- Course: ITS2020 - Rapid Application Development (RAD)
Contributions and pull requests are warmly welcomed! Please open an issue first to discuss substantial modifications.
This project is licensed under the ISC License.