LeadSmart API uses Express.js middleware for request processing, authentication, error handling, and more. This document outlines the middleware components used in the application.Authentication Middleware#
JWT Authentication#
File: src/middlewares/auth.middleware.ts
Validates JSON Web Tokens (JWT) in request headers and attaches the authenticated user to the request object.Extracts JWT from Authorization header
Verifies token signature and expiration
Attaches decoded user information to request object
Handles token validation errors
Role-Based Access Control#
File: src/middlewares/roleCheck.middleware.ts
Verifies that the authenticated user has the required role to access a resource.Checks user role against required roles
Returns 403 Forbidden if user lacks required permissions
Supports multiple role requirements
Company Membership Check#
File: src/middlewares/companyMembership.middleware.ts
Verifies that the authenticated user is a member of the specified company.Extracts company ID from request parameters
Checks if user is a member of the company
Returns 403 Forbidden if user is not a member
Request Processing#
Request Validation#
File: src/middlewares/validation.middleware.ts
Validates request data against Zod schemas.Validates request body, query parameters, and URL parameters
Returns 400 Bad Request with validation errors
Sanitizes and transforms data based on schema
Rate Limiting#
File: src/middlewares/rateLimit.middleware.ts
Limits the number of requests that can be made to specific endpoints.Tracks request counts by IP address or user ID
Enforces configurable rate limits
Returns 429 Too Many Requests when limit is exceeded
Error Handling#
Global Error Handler#
File: src/middlewares/errorHandler.middleware.ts
Centralized error handling middleware that processes all errors thrown in the application.Catches all errors that occur during request processing
Formats errors into a standardized response format
Maps specific error types to appropriate HTTP status codes
Handles Sequelize database errors
Provides detailed error information in development environment
Security Middleware#
CORS Configuration#
Configures Cross-Origin Resource Sharing (CORS) policies.Specifies allowed origins, methods, and headers
Handles preflight requests
Sets appropriate security headers
Sets various HTTP headers to enhance security.Prevents common web vulnerabilities
Configures Content Security Policy
Sets XSS protection headers
Prevents clickjacking attacks
Logging Middleware#
Request Logging#
File: src/middlewares/logger.middleware.ts
Logs information about incoming requests and their responses.Logs request method, URL, and timing
Logs response status code
Captures request and response size
Includes user ID for authenticated requests
Middleware Registration#
Middleware is registered in the Express application in src/configs/app.ts
:Creating Custom Middleware#
Custom middleware functions in LeadSmart API follow this pattern: Modificado em 2025-04-24 22:31:58