Add complete authentication infrastructure including: - Password hashing utilities with bcrypt - JWT token generation and verification - Auth service with register, login, refresh, and logout - Auth controller with Zod validation - Auth middleware for route protection - Auth routes mounted at /api/auth Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
45 lines
1.1 KiB
TypeScript
45 lines
1.1 KiB
TypeScript
import type { Request, Response, NextFunction } from 'express';
|
|
import { verifyToken } from '../utils/token.js';
|
|
import { AppError } from './error.middleware.js';
|
|
import type { JWTPayload, Role } from '@horux/shared';
|
|
|
|
declare global {
|
|
namespace Express {
|
|
interface Request {
|
|
user?: JWTPayload;
|
|
}
|
|
}
|
|
}
|
|
|
|
export function authenticate(req: Request, res: Response, next: NextFunction) {
|
|
const authHeader = req.headers.authorization;
|
|
|
|
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
|
return next(new AppError(401, 'Token no proporcionado'));
|
|
}
|
|
|
|
const token = authHeader.split(' ')[1];
|
|
|
|
try {
|
|
const payload = verifyToken(token);
|
|
req.user = payload;
|
|
next();
|
|
} catch (error) {
|
|
next(new AppError(401, 'Token inválido o expirado'));
|
|
}
|
|
}
|
|
|
|
export function authorize(...roles: Role[]) {
|
|
return (req: Request, res: Response, next: NextFunction) => {
|
|
if (!req.user) {
|
|
return next(new AppError(401, 'No autenticado'));
|
|
}
|
|
|
|
if (roles.length > 0 && !roles.includes(req.user.role)) {
|
|
return next(new AppError(403, 'No autorizado'));
|
|
}
|
|
|
|
next();
|
|
};
|
|
}
|