A comprehensive, production-ready portfolio management system with 65+ API endpoints, dynamic template system, AI-powered PDF processing, and enterprise-grade security.
Features β’ Quick Start β’ API Docs β’ Architecture β’ Contributing
- Overview
- Key Features
- Technology Stack
- Quick Start
- API Reference
- Architecture
- Testing
- Contributing
- License
AUREA Backend is a sophisticated portfolio management platform that enables designers, developers, and creative professionals to build, manage, and deploy stunning portfolio websites. Built with modern technologies and best practices, it offers a complete ecosystem for portfolio creation and management.
- π¨ Dynamic Template System - Schema-driven templates with no-code deployment
- π€ AI-Powered Processing - Gemini AI integration for intelligent PDF extraction
- π Multi-Deployment Options - Vercel deployment or local subdomain hosting
- π± Responsive HTML Generation - Automatic mobile-optimized site generation
- π Enterprise Security - JWT authentication, rate limiting, and role-based access
- β‘ High Performance - Redis caching, database indexing, and optimized queries
- π Analytics & Tracking - View counts, usage statistics, and user insights
- JWT-Based Authentication with secure token management
- Complete User CRUD with profile management and password updates
- Role-Based Access Control (User, Admin, Premium)
- Account Security with password hashing (bcrypt) and validation
- Full Portfolio Lifecycle - Create, Read, Update, Delete operations
- Dynamic Template System - 10+ professional templates with schema validation
- Custom Slug URLs - SEO-friendly portfolio URLs
- Publishing System - Publish/unpublish with version control
- View Analytics - Track portfolio views and engagement
- Schema-Driven Architecture - JSON schema defines form structure
- Real-Time Validation - Content validation against template schema
- Version Control - Template versioning with rollback capability
- Rating System - User-driven template ratings and feedback
- Premium Templates - Support for free and premium template tiers
- 14 Template Endpoints - Complete template lifecycle management
- Structured Project Documentation - Rich case study creation
- Smart Content Transformation - Automatic HTML generation from data
- Linked to Portfolios - Seamless integration with portfolio projects
- Public Access - Share case studies via public URLs
- Responsive Design - Mobile-optimized case study pages
- Vercel Deployment - One-click deployment to Vercel
- Gmail-Style Subdomains β - Custom subdomains (e.g.,
aurea.tool/your-name) - Dual Publishing Modes - Vercel OR local subdomain hosting
- Automatic HTML Generation - Dynamic responsive HTML from portfolio data
- View Tracking - Analytics for published sites
- Portfolio PDF Export - Generate professional PDF portfolios
- Complete Export - Include all case studies in single PDF
- Template-Based Generation - Multiple PDF templates available
- Download or View - Inline viewing or force download
- Automatic Cleanup - Old PDF cleanup functionality
- Gemini AI Integration - Advanced document analysis
- Two-Step Extraction - Complete analysis + pricing focus
- Structured Data Output - Clean, usable JSON format
- Extraction History - Track all processed documents
- Test Endpoints - Verify AI connectivity
- Cloudinary Integration - Professional image hosting
- Single & Batch Upload - Upload one or multiple images
- Image Validation - Format and size validation
- Automatic Optimization - Image optimization on upload
- Delete Functionality - Remove images from cloud storage
- Helmet.js - HTTP security headers
- CORS Protection - Configurable cross-origin policies
- Rate Limiting - Per-endpoint rate limits
- Redis Caching - Optional high-performance caching
- Input Validation - Comprehensive request validation
- Error Handling - Centralized error management
- Request Logging - Detailed API request logs
- Swagger UI - Complete API documentation at
/api-docs - Live Testing - Test endpoints directly from browser
- Request/Response Examples - Comprehensive examples for all endpoints
- Authentication Support - Test protected endpoints with JWT tokens
- Runtime: Node.js 18+
- Framework: Express 5.1.0
- Database: MongoDB 8.18+ (Mongoose ODM)
- Authentication: JWT (JSON Web Tokens)
- File Storage: Cloudinary
- Caching: Redis 4.7+ (optional)
{
"express": "^5.1.0", // Web framework
"mongoose": "^8.18.1", // MongoDB ODM
"jsonwebtoken": "^9.0.2", // JWT authentication
"bcrypt": "^6.0.0", // Password hashing
"cloudinary": "^2.7.0", // Media management
"puppeteer": "^24.25.0", // PDF generation
"@google/genai": "^1.21.0", // AI processing
"helmet": "^8.0.0", // Security headers
"express-rate-limit": "^7.4.0", // Rate limiting
"swagger-ui-express": "^5.0.1", // API documentation
"joi": "^17.13.3", // Validation
"redis": "^4.7.0" // Caching
}- ES6 Modules - Modern JavaScript module system
- Nodemon - Auto-restart on file changes
- Swagger - Interactive API documentation
- dotenv - Environment variable management
Before you begin, ensure you have the following installed and configured:
- β Node.js 18+ - Download
- β MongoDB - Local instance or MongoDB Atlas account
- β Cloudinary Account - Sign up for image storage
- β Redis (Optional) - Download for caching
- β Git - For version control
-
Clone the Repository
git clone https://github.com/your-org/aurea-backend.git cd aurea-backend -
Install Dependencies
npm install
-
Environment Configuration
Create a
.envfile in the root directory:cp .env.example .env
Update the
.envfile with your configuration:# MongoDB Configuration MONGODB_URI=mongodb+srv://username:[email protected]/aurea # JWT Configuration JWT_SECRET=your-super-secret-jwt-key-here JWT_EXPIRE=30d # Server Configuration PORT=5000 NODE_ENV=development # Frontend URL (for CORS) FRONTEND_URL=http://localhost:5173 # Cloudinary Configuration CLOUDINARY_CLOUD_NAME=your-cloud-name CLOUDINARY_API_KEY=your-api-key CLOUDINARY_API_SECRET=your-api-secret # Redis Configuration (Optional - gracefully degrades if unavailable) REDIS_URL=redis://localhost:6379 # Google Gemini AI (Optional - for PDF extraction) GEMINI_API_KEY=your-gemini-api-key # Vercel Configuration (Optional - for Vercel deployments) VERCEL_TOKEN=your-vercel-token VERCEL_ORG_ID=your-org-id VERCEL_PROJECT_ID=your-project-id
-
Seed Initial Data (Optional)
# Seed template data node seeds/templateSeeds.js # Migrate existing portfolios (if upgrading) node seeds/migratePortfolios.js
-
Start Development Server
npm run dev
Expected Output:
π AUREA Backend Server βββββββββββββββββββββββββββββββββββββββ π Environment: development π Port: 5000 β MongoDB Connected: aurea-cluster.mongodb.net β Redis Connected: localhost:6379 (optional) β Cloudinary Configured: your-cloud-name π Templates Initialized: 3 templates loaded π― 65+ API Endpoints Active π API Documentation: http://localhost:5000/api-docs βββββββββββββββββββββββββββββββββββββββ β¨ Server ready at: http://localhost:5000 -
Verify Installation
# Test health endpoint curl http://localhost:5000/health # Expected response: # {"status":"healthy","timestamp":"2025-10-20T...","database":"connected"}
-
Access API Documentation
Open your browser and navigate to:
http://localhost:5000/api-docs
Test the API with these commands:
# 1. Register a new user
curl -X POST http://localhost:5000/api/auth/signup \
-H "Content-Type: application/json" \
-d '{
"name": "John Doe",
"email": "[email protected]",
"password": "SecurePass123!"
}'
# 2. Login and get JWT token
curl -X POST http://localhost:5000/api/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "[email protected]",
"password": "SecurePass123!"
}'
# 3. Get templates (no auth required)
curl http://localhost:5000/api/templates
# 4. Get user profile (auth required - use token from login)
curl http://localhost:5000/api/auth/me \
-H "Authorization: Bearer YOUR_JWT_TOKEN"AUREA Backend provides 65+ RESTful API endpoints organized into 9 main categories:
| Category | Endpoints | Description |
|---|---|---|
| π₯ Health | 1 | Server health and status checks |
| π Authentication | 4 | User signup, login, profile management |
| π€ User Management | 13 | Complete user CRUD operations |
| π Portfolio | 9 | Portfolio lifecycle management |
| π¨ Templates | 14 | Dynamic template system |
| π Case Studies | 6 | Project case study management |
| π Site Publishing | 10 | Vercel & subdomain deployment |
| π PDF Export | 5 | Portfolio PDF generation |
| πΌοΈ Media Upload | 2 | Image upload and management |
| π€ AI Processing | 3 | PDF extraction with Gemini AI |
GET /healthReturns server status, database connectivity, and system info.
POST /api/auth/signup # Register new user
POST /api/auth/login # Login and get JWT token
GET /api/auth/me # Get current user profile (protected)
PUT /api/auth/me # Update current user (protected)Example: User Registration
curl -X POST http://localhost:5000/api/auth/signup \
-H "Content-Type: application/json" \
-d '{
"name": "Jane Designer",
"email": "[email protected]",
"password": "SecurePass123!"
}'Response:
{
"success": true,
"message": "User registered successfully",
"data": {
"user": {
"_id": "6501234567890abcdef12345",
"name": "Jane Designer",
"email": "[email protected]",
"role": "user"
},
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
}GET /api/users/profile # Get current user profile
PUT /api/users/profile # Update profile (name, email, password)
PATCH /api/users/profile/password # Change password
POST /api/users/profile/verify-password # Verify current password
DELETE /api/users/profile # Delete account
GET /api/users/premium/status # Check premium status
# Admin endpoints
GET /api/users # List all users (paginated)
GET /api/users/:id # Get user by ID
PUT /api/users/:id # Update user
DELETE /api/users/:id # Delete user
GET /api/users/:id/portfolios # Get user's portfolios
PUT /api/users/:id/role # Update user role
DELETE /api/users/:id/force # Force delete with portfoliosPOST /api/portfolios # Create new portfolio
GET /api/portfolios/stats # Get portfolio statistics
GET /api/portfolios/user/me # Get current user's portfolios
GET /api/portfolios/check-slug/:slug # Check slug availability
GET /api/portfolios/public/:slug # Get public portfolio
GET /api/portfolios/:id # Get portfolio by ID
PUT /api/portfolios/:id # Update portfolio
DELETE /api/portfolios/:id # Delete portfolio
PUT /api/portfolios/:id/publish # Publish portfolio
PUT /api/portfolios/:id/unpublish # Unpublish portfolioExample: Create Portfolio
curl -X POST http://localhost:5000/api/portfolios \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-d '{
"title": "My Design Portfolio",
"description": "A showcase of my creative work",
"templateId": "echelon",
"customData": {
"hero": {
"title": "Jane Designer",
"subtitle": "UI/UX Designer & Creative Director"
}
}
}'GET /api/templates # Get all templates (with filters)
GET /api/templates/categories # Get template categories
GET /api/templates/default # Get default template
GET /api/templates/:id # Get template by ID
GET /api/templates/:id/schema # Get template schema only
POST /api/templates/:id/validate # Validate content against schema
POST /api/templates/:id/rating # Rate template (1-5 stars)
# Admin endpoints
POST /api/templates # Create new template
PUT /api/templates/:id # Update template
DELETE /api/templates/:id # Deactivate template
POST /api/templates/:id/version # Create new template versionExample: Get Templates with Filters
# Get all minimal category templates
curl "http://localhost:5000/api/templates?category=minimal"
# Get premium templates with specific tags
curl "http://localhost:5000/api/templates?isPremium=true&tags=modern,clean"Example: Validate Portfolio Content
curl -X POST http://localhost:5000/api/templates/echelon/validate \
-H "Content-Type: application/json" \
-d '{
"content": {
"hero": {
"title": "My Portfolio",
"subtitle": "Designer & Developer"
},
"about": {
"name": "John Doe",
"bio": "Passionate about creating beautiful designs"
}
}
}'POST /api/case-studies # Create case study
GET /api/case-studies/:id # Get case study by ID
GET /api/case-studies/portfolio/:portfolioId/project/:projectId
PUT /api/case-studies/:id # Update case study
DELETE /api/case-studies/:id # Delete case study
GET /api/case-studies/public/:portfolioSlug/:projectId# Site publishing
POST /api/sites/publish # Deploy to Vercel
POST /api/sites/sub-publish # Publish to local subdomain β
POST /api/sites/debug-generate # Debug HTML generation
DELETE /api/sites/unpublish/:portfolioId # Unpublish site
# Site access
GET /api/sites/:subdomain # Get site by subdomain
GET /api/sites/:subdomain/raw-html # Get raw HTML
GET /api/sites/:subdomain/case-study/:projectId/raw-html
# Configuration
GET /api/sites/status # Get publishing status
GET /api/sites/config # Get site configuration
PUT /api/sites/config # Update site configuration
POST /api/sites/analytics/view # Record site viewExample: Gmail-Style Subdomain Publishing β
curl -X POST http://localhost:5000/api/sites/sub-publish \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-d '{
"portfolioId": "6501234567890abcdef12345",
"subdomain": "jane-designer"
}'Result:
β
Site published at: aurea.tool/jane-designer
π Files generated in: generated-files/jane-designer/
GET /api/pdf/portfolio/:portfolioId # View portfolio PDF (inline)
GET /api/pdf/portfolio/:portfolioId/complete # Complete PDF with case studies
GET /api/pdf/portfolio/:portfolioId/download # Force download PDF
GET /api/pdf/portfolio/:portfolioId/info # Get PDF generation info
POST /api/pdf/cleanup # Cleanup old PDFs (admin)Example: Export Portfolio as PDF
# View PDF in browser
curl http://localhost:5000/api/pdf/portfolio/6501234567890abcdef12345
# Download PDF file
curl -O http://localhost:5000/api/pdf/portfolio/6501234567890abcdef12345/downloadPOST /api/upload/single # Upload single image
POST /api/upload/multiple # Upload multiple imagesExample: Upload Image
curl -X POST http://localhost:5000/api/upload/single \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-F "image=@/path/to/image.jpg"POST /api/proposal-extract/extract # Extract data from PDF
GET /api/proposal-extract/history # Get extraction history
GET /api/proposal-extract/test-gemini # Test Gemini AI connectionExample: Extract Data from PDF
curl -X POST http://localhost:5000/api/proposal-extract/extract \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-F "pdf=@/path/to/proposal.pdf"π Visit Swagger UI: http://localhost:5000/api-docs
Quick Start Guide (shown in Swagger):
- Register:
/api/auth/signup(no auth required) - Login:
/api/auth/login(get JWT token) - Use token:
Authorization: Bearer <token>header
Interactive Testing:
- β All 65+ endpoints organized by tag
- β Live testing directly in browser
- β JWT token authentication support
- β Request/response examples for each endpoint
- β Standard response format documentation
- β HTTP status code reference
Status: 80% Refactored to Clean Architecture β
AUREA Backend has been substantially refactored from MVC to Clean Architecture with clear separation of concerns. This ensures maintainability, testability, and scalability.
Route β Middleware Chain β Thin Controller β Service (Business Logic) β Repository (Data Access) β Model β Database
-
API Layer (
src/api/, routes & controllers)- Controllers: Thin HTTP handlers (< 360 lines each, mostly routing)
- Routes: Endpoint definitions with middleware chains
- Middlewares: Request processing, validation, authentication
-
Core Layer (
src/core/)- Services (11 total): Business logic, orchestration, validation
- Repositories (5 total): Data access abstraction, query building
- Domain: Business entities and rules
-
Shared Layer (
src/shared/)- Exceptions: Custom error classes (NotFoundError, ValidationError, ForbiddenError, etc.)
- Constants: HTTP status codes, error codes
- Utils: ResponseFormatter for consistent API responses
- DTOs: Data Transfer Objects for API contracts
-
Infrastructure Layer (
src/infrastructure/)- Logging: Structured logging system with sanitization
- Database: Connection management
- External Services: Cloudinary, Vercel, Redis integrations
-
Configuration (
src/config/)- Centralized configuration management
- Environment variable validation
- Service initialization
- β 10/10 Controllers refactored to thin pattern
- β 11 Services created with all business logic
- β 5 Repositories for data access abstraction
- β 100% Centralized Configuration (no scattered process.env)
- β 99% Structured Logging (console.log replaced)
- β Consistent Error Handling with custom exceptions
- β Standardized Responses via responseFormatter
Using Services (Clean Architecture):
// β
CORRECT: Service handles business logic
import portfolioService from '../core/services/PortfolioService.js';
import responseFormatter from '../shared/utils/responseFormatter.js';
export const createPortfolio = async (req, res, next) => {
try {
const portfolio = await portfolioService.createPortfolio(req.user._id, req.body);
return responseFormatter.created(res, { portfolio }, 'Portfolio created');
} catch (error) {
next(error); // Error middleware handles it
}
};Using Repositories:
// β
CORRECT: Service uses repository for data access
class PortfolioService {
async getPortfolio(id) {
const portfolio = await this.repository.findById(id);
if (!portfolio) {
throw NotFoundError.resource('Portfolio', id);
}
return portfolio;
}
}Using Custom Exceptions:
// β
CORRECT: Throw custom exceptions instead of returning errors
if (!portfolio) {
throw NotFoundError.resource('Portfolio', portfolioId);
}
if (portfolio.userId.toString() !== userId) {
throw ForbiddenError.ownershipRequired('portfolio');
}
if (slugTaken) {
throw ConflictError.slugTaken(slug);
}Using Structured Logging:
// β
CORRECT: Use structured logging
import logger from '../infrastructure/logging/Logger.js';
logger.info('Portfolio created', { portfolioId, userId });
logger.error('Database error', { error, context });
logger.service('PortfolioService', 'createPortfolio', { userId });AUREA---Backend/
βββ src/
β βββ config/ # Centralized Configuration (Clean Architecture)
β β βββ index.js # Configuration aggregator
β β βββ database.js # MongoDB connection
β β βββ cloudinary.js # Cloudinary setup
β β βββ swagger.js # Swagger documentation config
β β βββ templateRegistry.js # Template registration
β β βββ envValidator.js # Environment validation
β β
β βββ controllers/ # API Layer - Thin HTTP handlers
β β βββ authController.js # Auth HTTP handlers
β β βββ userController.js # User HTTP handlers
β β βββ portfolioController.js # Portfolio HTTP handlers
β β βββ templateController.js # Template HTTP handlers
β β βββ caseStudyController.js # Case study HTTP handlers
β β βββ siteController.js # Site publishing HTTP handlers
β β βββ pdfExportController.js # PDF HTTP handlers
β β βββ uploadController.js # Upload HTTP handlers
β β βββ proposalExtract*.controller.js # AI extraction handlers
β β
β βββ core/ # Core Layer - Business Logic & Data Access
β β βββ services/ # Services (11 total) - Business Logic
β β β βββ AuthService.js
β β β βββ PortfolioService.js
β β β βββ UserService.js
β β β βββ TemplateService.js
β β β βββ CaseStudyService.js
β β β βββ SubdomainService.js
β β β βββ SiteService.js
β β β βββ PremiumService.js
β β β βββ PDFExportService.js
β β β βββ UploadService.js
β β β βββ ProposalExtractService.js
β β β
β β βββ repositories/ # Repositories (5 total) - Data Access
β β βββ UserRepository.js
β β βββ PortfolioRepository.js
β β βββ TemplateRepository.js
β β βββ CaseStudyRepository.js
β β βββ SiteRepository.js
β β
β βββ models/ # Data Models (Mongoose schemas)
β β βββ User.js # User authentication & profile
β β βββ Portfolio.js # Portfolio with template support
β β βββ Template.js # Dynamic template system
β β βββ CaseStudy.js # Case study documentation
β β βββ Site.js # Published site records
β β
β βββ routes/ # API Route Definitions (9 route files)
β β βββ authRoutes.js
β β βββ userRoutes.js
β β βββ portfolioRoutes.js
β β βββ templateRoutes.js
β β βββ caseStudyRoutes.js
β β βββ siteRoutes.js
β β βββ pdfRoutes.js
β β βββ uploadRoutes.js
β β βββ proposalExtract.routes.js
β β
β βββ middleware/ # Express Middleware
β β βββ auth.js # JWT authentication & authorization
β β βββ ownership.js # Resource ownership verification
β β βββ validation.js # Request validation rules
β β βββ errorHandler.js # Centralized error handling
β β βββ rateLimiter.js # Endpoint rate limiting
β β βββ requestLogger.js # Request/response logging
β β βββ logSanitizer.js # Sanitize sensitive data in logs
β β βββ bruteForcePrevention.js # Brute force protection
β β βββ premium.js # Premium-only route protection
β β βββ upload.js # Multer file upload configuration
β β βββ validatePortfolioContent.js # Portfolio content validation
β β
β βββ shared/ # Shared Layer - Reusable Components
β β βββ exceptions/ # Custom exception classes
β β β βββ ApplicationError.js
β β β βββ ValidationError.js
β β β βββ NotFoundError.js
β β β βββ UnauthorizedError.js
β β β βββ ForbiddenError.js
β β β βββ ConflictError.js
β β β βββ index.js
β β β
β β βββ constants/ # Application constants
β β β βββ httpStatus.js
β β β βββ errorCodes.js
β β β
β β βββ utils/ # Shared utilities
β β βββ responseFormatter.js # Standardized API responses
β β
β βββ infrastructure/ # Infrastructure Layer
β β βββ logging/ # Structured logging system
β β βββ Logger.js # Logger with sanitization
β β
β βββ services/ # Root-level Services (special cases)
β β βββ templateEngine.js # PDF template rendering (Puppeteer)
β β (Note: Use src/core/services/* for new services)
β β
β βββ utils/ # Helper Utilities
β βββ cache.js # Redis caching with graceful degradation
β βββ slugGenerator.js # Slug generation & validation
β βββ subdomainValidator.js # Subdomain format validation
β βββ templateValidator.js # Template schema validation
β
βββ services/ # Business services (root level)
β βββ deploymentService.js # Vercel deployment
β βββ pdfGenerationService.js # PDF export
β βββ templateConvert.js # Template HTML conversion
β
βββ seeds/ # Database seeders
β βββ templateSeeds.js # Seed initial templates
β βββ migratePortfolios.js # Migration scripts
β
βββ scripts/ # Utility scripts
β βββ upgrade-user-to-premium.js
β
βββ test/ # Test suites
β βββ test-template-system.js
β βββ test-custom-subdomain.js
β βββ test-publish-flow.js
β βββ test-*.js
β
βββ uploads/ # Temporary file uploads
β βββ pdfs/
β
βββ generated-files/ # Published site files (Gmail-style subdomains)
β βββ {subdomain}/
β β βββ index.html
β β βββ case-study-*.html
β
βββ server.js # Application entry point
βββ package.json # Dependencies and scripts
βββ swagger.yaml # OpenAPI specification
βββ .env # Environment variables (gitignored)
βββ .env.example # Environment template
βββ README.md # This file
Clean Architecture Flow:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β CLIENT LAYER β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β React β β Mobile β β External β β
β β Frontend β β Apps β β APIs β β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β HTTP/HTTPS
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β API GATEWAY LAYER β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Express.js Server (Port 5000) β β
β β - CORS, Helmet, Compression β β
β β - Rate Limiting (Express-Rate-Limit) β β
β β - Request Logging & Error Handling β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β MIDDLEWARE CHAIN (Clean Architecture) β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β 1. Log Sanitizer β 2. Brute Force Prevention β β
β β 3. JWT Auth β 4. Ownership Check β 5. Rate Limit β β
β β 6. Request Validation β 7. Error Handler β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β API LAYER (Thin Controllers - 10/10) β
β Route Handlers (< 30 lines each) β
β ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ β
β βAuthCtrl β βUserCtrl β βPortCtrl β βTplCtrl β β
β β(Auth) β β(Users) β β(Portfolio)β β(Templates)β β
β ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ β
β ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ β
β β CSCtrl β βSiteCtrl β βPDFCtrl β βUploadCtrlβ β
β β(CaseStd) β β(Sites) β β(PDF) β β(Upload) β β
β ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ β
β ββββββββββββ β
β β AICtrl β (Proposal Extract) β
β ββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β CORE LAYER - SERVICE/REPOSITORY PATTERN β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β SERVICES (11 total) - Business Logic Layer β β
β β βββββββββββββββ βββββββββββββββ βββββββββββββββ β β
β β βAuthService β βPortService β βUserService β β β
β β β (Auth Biz) β β(Port Biz) β β(User Biz) β β β
β β βββββββββββββββ βββββββββββββββ βββββββββββββββ β β
β β βββββββββββββββ βββββββββββββββ βββββββββββββββ β β
β β βTplService β βCSService β βSiteService β β β
β β β(Tmpl Biz) β β(CaseStd Biz)β β(Site Biz) β β β
β β βββββββββββββββ βββββββββββββββ βββββββββββββββ β β
β β βββββββββββββββ βββββββββββββββ βββββββββββββββ β β
β β βSubService β βPDFService β βUploadService β β
β β β(Subdomain) β β(PDF Export) β β(Image Upload) β β
β β βββββββββββββββ βββββββββββββββ βββββββββββββββ β β
β β β β
β β REPOSITORIES (5 total) - Data Access Layer β β
β β βββββββββββββββ βββββββββββββββ βββββββββββββββ β β
β β βUserRepo β βPortRepo β βTplRepo β β β
β β β(User Data) β β(Port Data) β β(Tmpl Data) β β β
β β βββββββββββββββ βββββββββββββββ βββββββββββββββ β β
β β βββββββββββββββ βββββββββββββββ β β
β β βCSRepo β βSiteRepo β β β
β β β(CS Data) β β(Site Data) β β β
β β βββββββββββββββ βββββββββββββββ β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β SHARED LAYER (Reusable Infrastructure) β
β βββββββββββββββββββ ββββββββββββββββ βββββββββββββββββ β
β β Exceptions β β Constants β β Utils β β
β β (Custom Errors) β β (HTTP Status)β β(ResponseFmt) β β
β βββββββββββββββββββ ββββββββββββββββ βββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β INFRASTRUCTURE LAYER (External Integration) β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Structured Logging & Sanitization β β
β β Database Connection Management β β
β β Cloudinary, Redis, Vercel Integration β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β DATABASE & MODELS β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Mongoose ODM with Schema Definitions β β
β β - User Model - Portfolio Model β β
β β - Template Model - CaseStudy Model β β
β β - Site Model (5 Models Total) β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β EXTERNAL SERVICES β
β ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ β
β β MongoDB β β Redis β βCloudinaryβ β Google β β
β β Database β β Cache β β CDN β β Gemini β β
β ββββββββββββ ββββββββββββ ββββββββββββ ββββββββββββ β
β ββββββββββββ ββββββββββββ β
β β Vercel β βPuppeteer β β
β β Deploy β β PDF Gen β β
β ββββββββββββ ββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
User Creates Portfolio (POST /api/portfolios):
1. Client β Request with JWT token
β
2. Express Middleware Stack:
- Log Sanitizer: Sanitize sensitive data
- Brute Force Prevention: Check IP rate limits
- Auth Middleware: Verify JWT, attach user to req.user
- Ownership Middleware: (N/A for create)
- Rate Limiter: Check endpoint limits (30/min for portfolios)
- Request Validator: Validate request body schema
β
3. Router β Route to portfolioController.create
β
4. Controller (Thin Handler):
- Receives validated request (req.body, req.user)
- Calls portfolioService.createPortfolio(userId, data)
- Catches errors and passes to error handler (next(error))
β
5. Service Layer (PortfolioService):
- Business logic: Validate template exists
- Business logic: Validate content against template schema
- Call repository.create(portfolioData)
- Throws custom exception if validation fails
β
6. Repository Layer (PortfolioRepository):
- Data access abstraction
- Call Portfolio.create(data) on Mongoose model
- Return created document
β
7. Database (MongoDB):
- Create portfolio document
- Apply schema validation
- Persist to database
β
8. Back through Service:
- Service returns portfolio object
- Logger records success
- Cache (Redis) invalidates user's portfolio list
β
9. Back through Controller:
- Response formatter: responseFormatter.created(res, data)
- Format response with standardized structure
β
10. Client β Success response with portfolio data
Example Controller Code (Clean Architecture):
export const create = async (req, res, next) => {
try {
// Service handles all business logic
const portfolio = await portfolioService.createPortfolio(
req.user._id,
req.body
);
// Standardized response formatting
return responseFormatter.created(res, { portfolio }, 'Portfolio created');
} catch (error) {
// Error middleware handles all error types
next(error);
}
};Example Service Code (Clean Architecture):
class PortfolioService {
async createPortfolio(userId, data) {
// Validate template exists
const template = await this.repository.findTemplate(data.templateId);
if (!template) {
throw NotFoundError.resource('Template', data.templateId);
}
// Validate content against template schema
if (!this.validateContent(template.schema, data.content)) {
throw ValidationError.invalidContent('Portfolio content does not match template schema');
}
// Repository handles data creation
const portfolio = await this.repository.create({
...data,
userId
});
logger.info('Portfolio created', { portfolioId: portfolio._id, userId });
return portfolio;
}
}# Run all tests
npm test
# Run specific test suites
npm run test:integration # Frontend integration tests
npm run test:user # User management tests
# Run template system tests
node test/test-template-system.js
# Test portfolio creation flow
node test/test-publish-flow.js
# Test PDF generation
node test/test-pdf-generation.js
# Test Vercel deployment
node test/test-vercel-deployment-improved.js
# Test custom subdomain publishing
node test/test-custom-subdomain.jsThe test suite covers:
- β Authentication - Signup, login, token validation
- β User Management - Profile CRUD operations
- β Portfolio System - Create, read, update, delete portfolios
- β Template System - Template selection, validation, rating
- β Case Studies - Case study creation and HTML generation
- β Publishing - Vercel and subdomain deployment
- β PDF Export - Portfolio and case study PDF generation
- β Media Upload - Image upload to Cloudinary
- β AI Processing - PDF extraction with Gemini AI
Using Swagger UI:
- Navigate to http://localhost:5000/api-docs
- Click "Authorize" button
- Enter JWT token:
Bearer YOUR_TOKEN_HERE - Test any endpoint directly from the browser
Using cURL:
# Health check
curl http://localhost:5000/health
# Register user
curl -X POST http://localhost:5000/api/auth/signup \
-H "Content-Type: application/json" \
-d '{"name":"Test User","email":"[email protected]","password":"Test123!"}'
# Login
curl -X POST http://localhost:5000/api/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"[email protected]","password":"Test123!"}'Using Postman:
- Import the Swagger JSON:
http://localhost:5000/api-docs.json - Set up environment variables for
BASE_URLandJWT_TOKEN - Run the collection
- Template System Guide - Complete template management documentation
- Frontend Integration Guide - React integration patterns
- Integration Success Outcomes - Expected results and KPIs
- PDF Performance Guide - PDF generation optimization
- Subdomain Publishing Guide - Gmail-style subdomain setup
- Swagger UI: http://localhost:5000/api-docs
- OpenAPI Spec:
swagger.yaml
- Backend Improvements - Recent enhancements
- Dynamic Template Refactor - Template system architecture
We welcome contributions! Here's how you can help:
-
Fork the repository
git clone https://github.com/your-username/aurea-backend.git
-
Create a feature branch
git checkout -b feature/your-feature-name
-
Make your changes
- Follow the existing code style
- Add tests for new features
- Update documentation
-
Commit your changes
git commit -m "feat: add amazing feature" -
Push to your fork
git push origin feature/your-feature-name
-
Create a Pull Request
Follow Conventional Commits:
feat:- New featurefix:- Bug fixdocs:- Documentation changesstyle:- Code style changes (formatting)refactor:- Code refactoringtest:- Adding or updating testschore:- Maintenance tasks
Examples:
feat: add template rating system
fix: resolve JWT token expiration issue
docs: update API documentation
refactor: improve portfolio controller logic
- Use ES6+ features
- Follow ESLint configuration
- Use async/await for asynchronous code
- Add comments for complex logic
- Keep functions small and focused
- Use meaningful variable names
- Provide clear description of changes
- Reference related issues
- Ensure all tests pass
- Update documentation if needed
- Add screenshots for UI changes
This project is licensed under the ISC License.
AUREA Development Team
- Backend Architecture & API Design
- Template System Development
- Security & Performance Optimization
- π§ Email: [email protected]
- π Bug Reports: GitHub Issues
- π¬ Discussions: GitHub Discussions
- π Documentation: Full Documentation
When reporting issues, please include:
- Description - Clear description of the issue
- Steps to Reproduce - How to reproduce the issue
- Expected Behavior - What you expected to happen
- Actual Behavior - What actually happened
- Environment - Node version, OS, etc.
- Logs - Relevant error messages or logs
- Screenshots - If applicable
- Express.js - Web framework
- MongoDB & Mongoose - Database
- JWT - Authentication
- Cloudinary - Media management
- Puppeteer - PDF generation
- Google Gemini AI - AI processing
- Redis - Caching
- Swagger - API documentation
- Portfolio design best practices
- Modern web architecture patterns
- RESTful API design principles
- 65+ API Endpoints
- 5 Database Models
- 9 Route Modules
- 10+ Middleware Functions
- 3+ AI-Powered Features
- 100% RESTful Design
- Production Ready
Made with β€οΈ by the AUREA Team
β Star on GitHub β’ π Report Bug β’ π Documentation
β¨ Major Features
- Complete authentication and user management system
- Dynamic template system with schema validation
- Portfolio CRUD with template support
- Case study management with smart HTML generation
- Dual publishing system (Vercel + local subdomain)
- PDF export with multiple template options
- AI-powered PDF extraction with Gemini AI
- Professional image upload with Cloudinary
π‘οΈ Security Enhancements
- JWT authentication with role-based access
- Rate limiting on all endpoints
- Input validation and sanitization
- Helmet security headers
- CORS configuration
- Ownership verification middleware
β‘ Performance Improvements
- Redis caching implementation
- Database query optimization
- Response compression
- Connection pooling
- Graceful degradation for optional services
π Documentation
- Complete Swagger/OpenAPI documentation
- Comprehensive README with examples
- Integration guides for frontend
- Template system documentation
- Deployment guides