UNPKG

backend-mcp

Version:

Generador automático de backends con Node.js, Express, Prisma y módulos configurables. Servidor MCP compatible con npx para agentes IA. Soporta PostgreSQL, MySQL, MongoDB y SQLite.

358 lines (281 loc) 7.43 kB
# 📦 Módulo auth **Versión:** 1.0.0 **Categoría:** security **Descripción:** Sistema completo de autenticación JWT con roles y permisos ## 📊 Estado del Módulo | Componente | Estado | |------------|--------| | Script de inicialización | ✅ Disponible | | Templates | ✅ Disponible | | Ejemplos | ❌ Faltante | ## 🔗 Dependencias ### Requeridas - `database` - `email` ### Opcionales - `logging` - `websockets` ## 🤖 Triggers para IA Este módulo se activa automáticamente cuando se detectan las siguientes palabras clave: - **user_wants_auth**: true - **needs_login**: true - **requires_jwt**: true - **has_user_roles**: true - **mentions_authentication**: true ## ✨ Características - login - register - refresh-tokens - email-verification - password-reset - role-based-access - permission-guards - audit-logging - rate-limiting - password-policies ## 📖 Documentación Completa # Auth Module Authentication and authorization module for MCP Backend framework. ## Features - ✅ JWT token-based authentication - ✅ User registration and login - ✅ Password hashing with bcrypt - ✅ Role-based access control (RBAC) - ✅ Token refresh mechanism - ✅ Password reset functionality - ✅ Account verification - ✅ Session management ## Installation This module is automatically installed when using the MCP Backend Generator. ## Configuration ### Environment Variables - `JWT_SECRET` (required) - Secret key for JWT token signing - `JWT_EXPIRES_IN` (optional) - Token expiration time (default: 7d) - `JWT_REFRESH_EXPIRES_IN` (optional) - Refresh token expiration (default: 30d) - `BCRYPT_ROUNDS` (optional) - Bcrypt hashing rounds (default: 12) - `AUTH_ENABLED` (optional) - Enable/disable auth module (default: true) ### Configuration File ```typescript // src/config/auth.ts export const authConfig = { jwtSecret: process.env.JWT_SECRET, jwtExpiresIn: process.env.JWT_EXPIRES_IN || '7d', jwtRefreshExpiresIn: process.env.JWT_REFRESH_EXPIRES_IN || '30d', bcryptRounds: parseInt(process.env.BCRYPT_ROUNDS || '12'), enabled: process.env.AUTH_ENABLED !== 'false' }; ``` ## Usage ### Service ```typescript import { authService } from './services/auth'; // Register user const user = await authService.register({ email: 'user@example.com', password: 'securePassword', name: 'John Doe' }); // Login user const { token, refreshToken } = await authService.login({ email: 'user@example.com', password: 'securePassword' }); // Verify token const payload = await authService.verifyToken(token); // Refresh token const newTokens = await authService.refreshToken(refreshToken); ``` ### Middleware ```typescript import { authMiddleware } from './middleware/auth'; import { requireRole } from './middleware/auth'; // Protect routes router.get('/protected', authMiddleware, (req, res) => { res.json({ user: req.user }); }); // Role-based protection router.get('/admin', authMiddleware, requireRole('admin'), (req, res) => { res.json({ message: 'Admin only' }); }); ``` ### Controller ```typescript import { authController } from './controllers/auth'; // Use in routes router.post('/register', authController.register); router.post('/login', authController.login); router.post('/refresh', authController.refreshToken); router.post('/logout', authMiddleware, authController.logout); router.get('/me', authMiddleware, authController.getProfile); ``` ## API Endpoints ### POST /auth/register Register a new user. **Request:** ```json { "email": "user@example.com", "password": "securePassword", "name": "John Doe", "role": "user" } ``` **Response:** ```json { "success": true, "data": { "user": { "id": "user_id", "email": "user@example.com", "name": "John Doe", "role": "user" }, "token": "jwt_token", "refreshToken": "refresh_token" } } ``` ### POST /auth/login Authenticate user and get tokens. **Request:** ```json { "email": "user@example.com", "password": "securePassword" } ``` **Response:** ```json { "success": true, "data": { "user": { "id": "user_id", "email": "user@example.com", "name": "John Doe", "role": "user" }, "token": "jwt_token", "refreshToken": "refresh_token" } } ``` ### POST /auth/refresh Refresh access token. **Request:** ```json { "refreshToken": "refresh_token" } ``` **Response:** ```json { "success": true, "data": { "token": "new_jwt_token", "refreshToken": "new_refresh_token" } } ``` ### GET /auth/me Get current user profile (requires authentication). **Headers:** ``` Authorization: Bearer jwt_token ``` **Response:** ```json { "success": true, "data": { "user": { "id": "user_id", "email": "user@example.com", "name": "John Doe", "role": "user", "createdAt": "2023-01-01T00:00:00.000Z" } } } ``` ### POST /auth/logout Logout user and invalidate tokens (requires authentication). **Headers:** ``` Authorization: Bearer jwt_token ``` **Response:** ```json { "success": true, "message": "Logged out successfully" } ``` ## Database Schema ```sql CREATE TABLE users ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), email VARCHAR(255) UNIQUE NOT NULL, password_hash VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, role VARCHAR(50) DEFAULT 'user', email_verified BOOLEAN DEFAULT false, email_verification_token VARCHAR(255), password_reset_token VARCHAR(255), password_reset_expires TIMESTAMP, last_login TIMESTAMP, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE refresh_tokens ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID REFERENCES users(id) ON DELETE CASCADE, token VARCHAR(255) UNIQUE NOT NULL, expires_at TIMESTAMP NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE INDEX idx_users_email ON users(email); CREATE INDEX idx_refresh_tokens_token ON refresh_tokens(token); CREATE INDEX idx_refresh_tokens_user_id ON refresh_tokens(user_id); ``` ## Security Features - **Password Hashing**: Uses bcrypt with configurable rounds - **JWT Security**: Signed tokens with expiration - **Token Refresh**: Secure token refresh mechanism - **Rate Limiting**: Built-in rate limiting for auth endpoints - **Input Validation**: Comprehensive input validation - **SQL Injection Protection**: Parameterized queries - **XSS Protection**: Input sanitization - **CSRF Protection**: CSRF token validation ## Testing ```bash npm test -- auth ``` ## Dependencies - bcrypt - jsonwebtoken - joi (validation) - database - logging ## Integration - Integrates with `database` module for user storage - Integrates with `validation` module for input validation - Integrates with `logging` module for audit trails - Integrates with `email` module for verification emails ## Error Handling The module provides comprehensive error handling: - `AuthenticationError`: Invalid credentials - `AuthorizationError`: Insufficient permissions - `TokenExpiredError`: Expired JWT token - `TokenInvalidError`: Invalid JWT token - `UserNotFoundError`: User doesn't exist - `UserAlreadyExistsError`: Email already registered - `ValidationError`: Invalid input data ## License MIT ## 🔗 Enlaces - [Volver al índice de módulos](./README.md) - [Documentación principal](../README.md) - [Código fuente](../../modules/auth/)