Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 | 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 2x 2x 1x 1x 1x 1x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x | import { Elysia, t } from 'elysia';
import { UserService, InvalidRoleError } from '../services/userService';
import {
createUserValidator,
loginUserValidator,
resetPasswordValidator,
updateUserValidator
} from '../utils/schemaValidator';
import { createErrorResponse } from '../utils/firebaseErrors';
import { VALID_ROLES } from '../constants/roles';
export function registerUserRoutes(app: Elysia<any>) {
app
.post(
'/newUser',
async ({ body, error }) => {
try {
const { email, password } = body as any;
const role = body.role || 'auditor'; // Valor por defecto si no se proporciona
// Intentamos crear el usuario - el servicio validará el rol
const user = await UserService.createUser(email, password, role);
return {
success: true,
message: 'Usuario creado exitosamente',
userId: user.uid,
role: role,
};
} catch (err: any) {
// Si es un error de rol inválido, devolvemos un error personalizado
if (
err instanceof InvalidRoleError ||
err.code === 'auth/invalid-role'
) {
const invalidRole = body?.role;
return error(400, {
success: false,
message: `El rol '${invalidRole}' no es válido`,
details: {
role: `Debe ser uno de los siguientes: ${VALID_ROLES.join(
', '
)}`,
},
invalidValues: { role: invalidRole },
});
}
// Para otros errores de Firebase, usamos el sistema existente
const errorResponse = createErrorResponse(
err,
'Error general de servidor'
);
return error(400, {
success: false,
message: errorResponse.message,
errorCode: errorResponse.errorCode,
});
}
},
{
body: createUserValidator,
response: {
200: t.Object({
success: t.Boolean(),
message: t.String(),
userId: t.String(),
role: t.String(),
}),
400: t.Object({
success: t.Boolean(),
message: t.String(),
details: t.Optional(t.Record(t.String(), t.String())),
invalidValues: t.Optional(t.Record(t.String(), t.Any())),
errorCode: t.Optional(t.String()),
}),
409: t.Object({
success: t.Boolean(),
message: t.String(),
errorCode: t.Optional(t.String()),
}),
500: t.Object({
success: t.Boolean(),
message: t.String(),
errorCode: t.Optional(t.String()),
}),
},
detail: {
summary: 'Crea un nuevo usuario',
description:
'Crea un nuevo usuario en Firebase con email y contraseña',
tags: ['Usuarios'],
},
}
)
.post(
'/login',
async ({ body, error }) => {
// Validación de rol - lanza error específico
try {
const { email, password } = body as any;
const user = await UserService.loginUser(email, password);
const userData = await UserService.getUserData(user.uid);
return {
success: true,
message: 'Inicio de sesión exitoso',
userId: user.uid,
role: userData.role,
};
// Si el inicio de sesión es exitoso, devolvemos el ID del usuario
} catch (err: any) {
const errorResponse = createErrorResponse(
err,
'Error al iniciar sesión'
);
// Si el error es 400, 401 o 404, devolvemos un error específico
if (errorResponse.status === 404) {
return error(404, {
success: false,
message: errorResponse.message,
errorCode: errorResponse.errorCode,
});
} else if (errorResponse.status === 401) {
return error(401, {
success: false,
message: errorResponse.message,
errorCode: errorResponse.errorCode,
});
} else {
return error(400, {
success: false,
message: errorResponse.message,
errorCode: errorResponse.errorCode,
});
}
}
},
{
body: loginUserValidator,
response: {
200: t.Object({
success: t.Boolean(),
message: t.String(),
userId: t.String(),
role: t.String(),
}),
400: t.Object({
success: t.Boolean(),
message: t.String(),
errorCode: t.Optional(t.String()),
}),
401: t.Object({
success: t.Boolean(),
message: t.String(),
errorCode: t.Optional(t.String()),
}),
404: t.Object({
success: t.Boolean(),
message: t.String(),
errorCode: t.Optional(t.String()),
}),
},
detail: {
summary: 'Inicia sesión de usuario',
description:
'Inicia sesión de usuario en Firebase con email y contraseña',
tags: ['Usuarios'],
},
}
)
.get(
'/getUsers',
async ({ error }) => {
try {
const users = await UserService.getAllUsers();
return {
success: true,
message: 'Usuarios obtenidos exitosamente',
users: users.map((user) => ({
uid: user.id,
email: user.email,
role: user.role,
createdAt: user.createdAt.toISOString(),
updatedAt: user.updatedAt.toISOString(),
})),
};
} catch (err: any) {
const errorResponse = createErrorResponse(
err,
'Error al obtener usuarios'
);
return error(500, {
success: false,
message: errorResponse.message,
errorCode: errorResponse.errorCode,
});
}
},
{
response: {
200: t.Object({
success: t.Boolean(),
message: t.String(),
users: t.Array(
t.Object({
uid: t.String(),
email: t.String(),
role: t.String(),
createdAt: t.String(),
updatedAt: t.String(),
})
),
}),
500: t.Object({
success: t.Boolean(),
message: t.String(),
errorCode: t.Optional(t.String()),
}),
},
detail: {
summary: 'Obtiene todos los usuarios',
description:
'Obtiene la lista de todos los usuarios registrados en Firestore',
tags: ['Usuarios'],
},
}
)
.post(
'/resetPassword',
async ({ body, error }) => {
try {
const { email } = body as { email: string };
await UserService.resetPassword(email);
return {
success: true,
message:
'Se ha enviado un enlace de recuperación al correo electrónico proporcionado',
};
} catch (err: any) {
const errorResponse = createErrorResponse(
err,
'Error al enviar el correo de recuperación'
);
if (errorResponse.status === 404) {
return error(404, {
success: false,
message: 'El correo electrónico no está registrado',
errorCode: errorResponse.errorCode,
});
} else {
return error(400, {
success: false,
message: errorResponse.message,
errorCode: errorResponse.errorCode,
});
}
}
},
{
body: resetPasswordValidator,
response: {
200: t.Object({
success: t.Boolean(),
message: t.String(),
}),
400: t.Object({
success: t.Boolean(),
message: t.String(),
errorCode: t.Optional(t.String()),
}),
404: t.Object({
success: t.Boolean(),
message: t.String(),
errorCode: t.Optional(t.String()),
}),
},
detail: {
summary: 'Recuperación de contraseña',
description:
'Envía un correo electrónico con un enlace para restablecer la contraseña',
tags: ['Usuarios'],
},
}
)
.put(
'update/:id',
async ({ params, body, error }) => {
try {
const { id } = params;
const updateData = body as { email?: string; role?: string };
// Verificamos que haya al menos un campo para actualizar
if (!updateData.email && !updateData.role) {
return error(400, {
success: false,
message: 'Debe proporcionar al menos un campo para actualizar (email o role)',
});
}
// Actualizamos el usuario
const updatedUser = await UserService.updateUser(id, updateData);
return {
success: true,
message: 'Usuario actualizado exitosamente',
user: {
uid: updatedUser.id,
email: updatedUser.email,
role: updatedUser.role,
updatedAt: updatedUser.updatedAt.toISOString(),
},
};
} catch (err: any) {
// Si es un error de rol inválido, devolvemos un error personalizado
if (
err instanceof InvalidRoleError ||
err.code === 'auth/invalid-role'
) {
const invalidRole = body?.role;
return error(400, {
success: false,
message: `El rol '${invalidRole}' no es válido`,
details: {
role: `Debe ser uno de los siguientes: ${VALID_ROLES.join(
', '
)}`,
},
invalidValues: { role: invalidRole },
});
}
// Para errores de usuario no encontrado
if (err.code === 'auth/user-not-found') {
return error(404, {
success: false,
message: 'Usuario no encontrado',
errorCode: err.code,
});
}
// Para otros errores de Firebase, usamos el sistema existente
const errorResponse = createErrorResponse(
err,
'Error al actualizar el usuario'
);
return error(400, {
success: false,
message: errorResponse.message,
errorCode: errorResponse.errorCode,
});
}
},
{
params: t.Object({
id: t.String(),
}),
body: updateUserValidator,
response: {
200: t.Object({
success: t.Boolean(),
message: t.String(),
user: t.Object({
uid: t.String(),
email: t.String(),
role: t.String(),
updatedAt: t.String(),
}),
}),
400: t.Object({
success: t.Boolean(),
message: t.String(),
details: t.Optional(t.Record(t.String(), t.String())),
invalidValues: t.Optional(t.Record(t.String(), t.Any())),
errorCode: t.Optional(t.String()),
}),
404: t.Object({
success: t.Boolean(),
message: t.String(),
errorCode: t.Optional(t.String()),
}),
},
detail: {
summary: 'Actualiza un usuario por ID',
description:
'Actualiza los datos de un usuario existente por su ID (email y/o rol)',
tags: ['Usuarios'],
},
}
)
.delete(
'delete/:id',
async ({ params, error }) => {
try {
const { id } = params;
// Eliminamos el usuario
await UserService.deleteUser(id);
return {
success: true,
message: 'Usuario eliminado exitosamente',
};
} catch (err: any) {
// Para errores de usuario no encontrado
if (err.code === 'auth/user-not-found') {
return error(404, {
success: false,
message: 'Usuario no encontrado',
errorCode: err.code,
});
}
// Para otros errores de Firebase, usamos el sistema existente
const errorResponse = createErrorResponse(
err,
'Error al eliminar el usuario'
);
return error(500, {
success: false,
message: errorResponse.message,
errorCode: errorResponse.errorCode,
});
}
},
{
params: t.Object({
id: t.String(),
}),
response: {
200: t.Object({
success: t.Boolean(),
message: t.String(),
}),
404: t.Object({
success: t.Boolean(),
message: t.String(),
errorCode: t.Optional(t.String()),
}),
500: t.Object({
success: t.Boolean(),
message: t.String(),
errorCode: t.Optional(t.String()),
}),
},
detail: {
summary: 'Elimina un usuario por ID',
description:
'Elimina permanentemente un usuario existente por su ID',
tags: ['Usuarios'],
},
}
);
return app;
}
|