• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

SyTW2526 / Proyecto-E09 / 20542655055

27 Dec 2025 06:18PM UTC coverage: 15.07% (-0.2%) from 15.266%
20542655055

push

github

alu0101559513
cambio de traducciones

153 of 1697 branches covered (9.02%)

Branch coverage included in aggregate %.

407 of 2019 relevant lines covered (20.16%)

0.71 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

16.22
/src/server/middleware/authMiddleware.ts
1
import { Request, Response, NextFunction } from 'express';
2
import jwt from 'jsonwebtoken';
3

4
/**
5
 * Interfaz extendida de Request para incluir el userId después de validar el token
6
 */
7
export interface AuthRequest extends Request {
8
  userId?: string;
9
  username?: string;
10
  io?: any;
11
}
12

13
/**
14
 * Middleware de autenticación con JWT
15
 * Valida el token enviado en el header Authorization
16
 *
17
 * Uso:
18
 * router.get('/protected-route', authMiddleware, (req, res) => { ... })
19
 */
20
export const authMiddleware = (
1✔
21
  req: AuthRequest,
22
  res: Response,
23
  next: NextFunction
24
): void => {
25
  try {
×
26
    // Obtener el token del header Authorization
27
    const authHeader = req.headers.authorization;
×
28

29
    if (!authHeader) {
×
30
      res.status(401).send({ error: 'Token no proporcionado' });
×
31
      return;
×
32
    }
33

34
    // El formato esperado es: "Bearer <token>"
35
    const parts = authHeader.split(' ');
×
36
    if (parts.length !== 2 || parts[0] !== 'Bearer') {
×
37
      res
×
38
        .status(401)
39
        .send({ error: 'Formato de token inválido. Use: Bearer <token>' });
40
      return;
×
41
    }
42

43
    const token = parts[1];
×
44
    const secret = process.env.JWT_SECRET || 'tu-clave-secreta';
×
45

46
    // Verificar y decodificar el token
47
    const decoded = jwt.verify(token, secret) as {
×
48
      userId: string;
49
      username: string;
50
    };
51

52
    // Guardar información del usuario en la request para usarla en la ruta
53
    req.userId = decoded.userId;
×
54
    req.username = decoded.username;
×
55

56
    next();
×
57
  } catch (error) {
58
    if (error instanceof jwt.TokenExpiredError) {
×
59
      res.status(401).send({ error: 'Token expirado' });
×
60
    } else if (error instanceof jwt.JsonWebTokenError) {
×
61
      res.status(401).send({ error: 'Token inválido' });
×
62
    } else {
63
      res
×
64
        .status(500)
65
        .send({ error: (error as Error).message ?? 'Error al validar token' });
×
66
    }
67
  }
68
};
69

70
/**
71
 * Middleware opcional de autenticación.
72
 * Si viene un token válido en Authorization lo decodifica y pone req.userId/username.
73
 * Si no viene token o es inválido, no bloquea la petición — simplemente continúa sin user info.
74
 */
75
export const optionalAuthMiddleware = (
1✔
76
  req: AuthRequest,
77
  _res: Response,
78
  next: NextFunction
79
): void => {
80
  try {
9✔
81
    const authHeader = req.headers.authorization;
9✔
82
    if (!authHeader) {
9!
83
      return next();
9✔
84
    }
85
    const parts = authHeader.split(' ');
×
86
    if (parts.length !== 2 || parts[0] !== 'Bearer') {
×
87
      return next();
×
88
    }
89
    const token = parts[1];
×
90
    const secret = process.env.JWT_SECRET || 'tu-clave-secreta';
×
91
    try {
9✔
92
      const decoded = jwt.verify(token, secret) as {
9✔
93
        userId: string;
94
        username: string;
95
      };
96
      req.userId = decoded.userId;
9✔
97
      req.username = decoded.username;
9✔
98
    } catch (e) {
99
      // token inválido: no bloqueamos, solo no seteamos userId
100
    }
101
    return next();
×
102
  } catch (error) {
103
    return next();
×
104
  }
105
};
106

107
/**
108
 * Middleware para Socket.io
109
 * Valida el token antes de permitir la conexión a Socket
110
 */
111
export const socketAuthMiddleware = (socket: any, next: any) => {
1✔
112
  try {
×
113
    const token = socket.handshake.auth.token;
×
114

115
    if (!token) {
×
116
      return next(new Error('Token no proporcionado'));
×
117
    }
118

119
    const secret = process.env.JWT_SECRET || 'tu-clave-secreta';
×
120
    const decoded = jwt.verify(token, secret) as {
×
121
      userId: string;
122
      username: string;
123
    };
124

125
    // Guardar información del usuario en el socket
126
    socket.userId = decoded.userId;
×
127
    socket.username = decoded.username;
×
128

129
    next();
×
130
  } catch (error) {
131
    next(new Error('Autenticación fallida: ' + (error as Error).message));
×
132
  }
133
};
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc