System Overview
The Portal Self-Service Backend API is built with a modern, scalable architecture using Node.js and Microsoft SQL Server. The system follows an MVC-style pattern with clear separation of concerns.Technology Stack
- Runtime: Node.js (ES Modules)
- Framework: Express.js v5.1.0
- Database: Microsoft SQL Server
- ORM: Sequelize v6.37.7
- Real-time: Socket.io v4.8.3
- Authentication: Azure AD (OAuth2 JWT)
Key Features
- JWT-based authentication
- Role-based access control (RBAC)
- Real-time notifications
- Request approval workflows
- File upload management
- Swagger API documentation
Architecture Layers
The application follows a layered architecture pattern:Core Components
1. Server Initialization
The server bootstraps inserver.js, setting up both HTTP and WebSocket servers:
server.js
- Creates HTTP server wrapping Express app (server.js:14)
- Initializes Socket.io on the same server (server.js:17)
- Ensures database connectivity before accepting requests (server.js:22)
2. Express Application
The Express app is configured insrc/app.js:
src/app.js
- CORS enabled for frontend communication (src/app.js:12-17)
- JSON body parsing (src/app.js:21)
- Swagger UI at
/docsendpoint (src/app.js:24) - Static file serving for uploads (src/app.js:28)
3. Database Configuration
Sequelize ORM connects to SQL Server with connection pooling:src/config/db.config.js
- Connection pooling (max 10 connections) (src/config/db.config.js:13-17)
- Automatic timezone handling (UTC-6) (src/models/index.js:35)
- Sequelize ORM with model associations (src/models/index.js:65-69)
Authentication Flow
The API uses Azure AD for authentication with a multi-step middleware chain:Token Validation
The This middleware:
authenticateAndExtract middleware validates the JWT token from Azure AD:src/middleware/authMiddleware.js
- Validates JWT signature using Azure’s JWKS endpoint (src/middleware/authMiddleware.js:13-19)
- Verifies token issuer and audience claims
- Extracts user identity from token payload (src/middleware/authMiddleware.js:41-50)
User Loading
The This step:
cargarUsuario middleware loads the full user record from the database:src/middleware/cargarUsuario.js
- Finds user by Azure Object ID (src/middleware/cargarUsuario.js:16)
- Loads role and vacation data (src/middleware/cargarUsuario.js:17-20)
- Attaches full user object to request (src/middleware/cargarUsuario.js:30)
Middleware Chain Example
Here’s how the middleware chain works for protected routes:src/routes/solicitudRoutes.js
Request Approval Workflow
The system implements a sophisticated approval workflow for employee requests (vacation, absence, profile updates):Request Creation
Employees create requests through the API:The system:
src/controllers/solicitudController.js (line 135)
- Validates request data and date ranges
- Calculates requested days for time-off requests
- Creates request with PENDING status (id_estado_solicitud: 1)
Notification Dispatch
Administrators are notified via real-time notifications:Notifications are sent through Socket.io for instant delivery.
src/controllers/solicitudController.js (line 187)
Admin Review
Admins can approve or reject requests:The approval logic:
src/controllers/solicitudController.js (line 468)
- Validates request is still pending (src/controllers/solicitudController.js:487-489)
- Prevents self-approval (commented for testing)
- Handles different request types with specific logic (src/controllers/solicitudController.js:509-572)
Transaction Processing
Approvals use database transactions for data consistency:For vacation requests:
- Deducts days from employee’s vacation balance
- Updates request status to APPROVED
- Records approval metadata
- Applies proposed changes to employee record
- Updates request status
- Maintains audit trail
All state changes are atomic - either all operations succeed or none do, ensuring data integrity.
Real-time Notifications with Socket.io
The system uses Socket.io for instant notification delivery:Socket Authentication
src/config/socket.js (line 37)
- JWT authentication for WebSocket connections (src/config/socket.js:39-44)
- User identification via Azure AD token (src/config/socket.js:58-66)
- Personal rooms for each user (src/config/socket.js:79-84)
Event Flow
src/config/socket.js (line 92)
- Created by the notification service
- Emitted via internal EventEmitter
- Delivered to user’s Socket.io room
- Received by connected clients in real-time
API Routes Structure
Routes are organized by resource type:src/routes/indexRoutes.js
/api (src/app.js:34).
Route Protection Example
src/routes/solicitudRoutes.js
Service Layer Pattern
Controllers delegate business logic to service modules:- Controllers: Handle HTTP concerns (validation, responses)
- Services: Implement business rules and transactions
- Models: Define database schema and relationships
Data Models
The system uses Sequelize models with associations:src/models/index.js
- Empleado: Employee records with Azure AD integration
- Solicitud: Request/application records
- Vacaciones: Vacation balance tracking
- Notificacion: Notification system
Security Considerations
Authentication
- JWT tokens validated against Azure AD
- Token signature verification using JWKS
- Token expiration enforced
- User existence verified in local database
Authorization
- Role-based access control (RBAC)
- Resource ownership validation
- Admin-only endpoint protection
- Self-approval prevention (commented for testing)
Data Protection
- SQL injection prevention via Sequelize ORM
- Environment variable configuration
- Encrypted database connections (TLS)
- Connection pooling for resource management
Input Validation
- Request body validation in controllers
- Date range validation
- State transition validation
- File upload restrictions
Performance Optimization
Database Connection Pooling
The application uses connection pooling to manage database resources efficiently:src/config/db.config.js
Eager Loading
Related data is loaded efficiently using Sequelize includes:src/middleware/cargarUsuario.js
Error Handling
The application implements consistent error handling:- 200: Success
- 201: Resource created
- 400: Bad request / validation error
- 401: Unauthorized (invalid token)
- 403: Forbidden (insufficient permissions)
- 404: Resource not found
- 500: Internal server error
Next Steps
API Reference
Explore detailed endpoint documentation
Quickstart
Set up your development environment
Authentication Guide
Learn about Azure AD integration
Database Setup
Configure database connections