-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharchivos.txt
More file actions
2835 lines (2372 loc) · 81.2 KB
/
archivos.txt
File metadata and controls
2835 lines (2372 loc) · 81.2 KB
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Backend/src/shared/types/DeepPartial.ts
// src/shared/types/DeepPartial.ts
/**
* Tipo que permite hacer partial (opcional) de manera recursiva.
*/
export type DeepPartial<T> = {
[P in keyof T]?: T[P] extends Array<infer U>
? Array<DeepPartial<U>>
: T[P] extends object
? DeepPartial<T[P]>
: T[P];
};
// Backend/src/shared/db/SupabaseClient.ts
import {createClient} from '@supabase/supabase-js';
import * as process from 'process';
const {SUPABASE_URL, SUPABASE_ANON_KEY} = process.env;
if (!SUPABASE_URL || !SUPABASE_ANON_KEY) {
throw new Error('Faltan variables de entorno para Supabase');
}
export const supabaseClient = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
// Backend/src/shared/db/MongoClient.ts
import mongoose from "mongoose";
import dotenv from "dotenv";
dotenv.config();
/**
* Conexión global a Mongo usando Mongoose.
*/
let isConnected = false;
export async function connectMongo(): Promise<void> {
if (isConnected) return;
const mongoUri =
process.env.MONGO_URL || "mongodb://localhost:27017/QueykSearch";
try {
await mongoose.connect(mongoUri);
isConnected = true;
console.log("Conexión exitosa a MongoDB en ", mongoUri);
} catch (error) {
console.error("Error al conectar a MongoDB:", error);
throw error;
}
}
// Backend/src/middlewares/auth.ts
// import jwt from "express-jwt";
// import jwksRsa from "jwks-rsa";
// import { Request, Response, NextFunction } from "express";
// /**
// * Middleware para verificar el JWT emitido por Auth0.
// */
// export const checkJwt = jwt({
// secret: jwksRsa.expressJwtSecret({
// cache: true,
// rateLimit: true,
// jwksRequestsPerMinute: 5,
// jwksUri: `https://<your-auth0-domain>/.well-known/jwks.json`, // Reemplaza con tu dominio de Auth0
// }),
// audience: "<YOUR_API_IDENTIFIER>", // Reemplaza con tu identificador de API en Auth0
// issuer: `https://<your-auth0-domain>/`, // Reemplaza con tu dominio de Auth0
// algorithms: ["RS256"],
// });
// /**
// * Middleware para verificar los roles del usuario.
// * @param requiredRoles - Rol o roles requeridos para acceder a la ruta
// */
// export const checkRoles = (requiredRoles: string | string[]) => {
// return (req: Request, res: Response, next: NextFunction) => {
// const user = req.user as any;
// if (!user || !user.roles) {
// return res.status(403).json({ message: "Forbidden" });
// }
// const roles: string[] = user.roles;
// if (typeof requiredRoles === "string") {
// if (!roles.includes(requiredRoles)) {
// return res.status(403).json({ message: "Forbidden" });
// }
// } else {
// const hasRole = requiredRoles.some((role) => roles.includes(role));
// if (!hasRole) {
// return res.status(403).json({ message: "Forbidden" });
// }
// }
// next();
// };
// };
// Backend/src/index.ts
import { startServer } from "./app/server";
/**
* Punto de entrada principal de la aplicación.
* Llama a la función que inicia el servidor.
*/
startServer();
// Backend/src/app/server.ts
// src/app/server.ts
import express, { Application, Request, Response, NextFunction } from "express";
import dotenv from "dotenv";
import { router } from "./routes";
import { connectMongo } from "../shared/db/MongoClient";
import cors from "cors"; // Importar cors
// Cargar variables de entorno
dotenv.config();
export async function startServer() {
try {
// Conectar a Mongo antes de levantar el servidor
await connectMongo();
// Inicializar la aplicación Express
const app: Application = express();
// Configurar CORS
app.use(cors()); // Usar CORS con configuración por defecto
// Middlewares para parseo de JSON y URL-encoded
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// Registrar rutas
app.use("/api/v1", router);
// Middleware de depuración para rutas no encontradas
app.use((req: Request, res: Response) => {
console.log(`Ruta no encontrada: ${req.method} ${req.url}`);
res.status(404).send(`Cannot ${req.method} ${req.url}`);
});
// Iniciar el servidor
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => {
console.log(`Servidor corriendo en http://localhost:${PORT}`);
});
// Listar rutas registradas
listRoutes(app);
} catch (error) {
console.error("Error al iniciar el servidor:", error);
process.exit(1);
}
}
function listRoutes(app: Application) {
console.log("Listado de rutas registradas:");
app._router.stack.forEach(function (middleware: any) {
if (middleware.route) {
// rutas registradas
console.log(
`${middleware.route.stack[0].method.toUpperCase()} ${
middleware.route.path
}`
);
} else if (middleware.name === "router") {
// rutas anidadas
middleware.handle.stack.forEach(function (handler: any) {
const route = handler.route;
if (route) {
console.log(
`${handler.route.stack[0].method.toUpperCase()} ${route.path}`
);
}
});
}
});
}
// // Configurar CORS con opciones personalizadas
// const corsOptions = {
// origin: "http://localhost:3000", // Origen permitido
// methods: ["GET", "POST", "PUT", "DELETE"], // Métodos HTTP permitidos
// credentials: true, // Permitir el envío de cookies si es necesario
// };
// app.use(cors(corsOptions));
// const allowedOrigins = ["http://localhost:3000", "http://example.com"];
// const corsOptions = {
// origin: function (origin: any, callback: any) {
// // Permitir solicitudes sin origen (por ejemplo, mobile apps, curl, etc.)
// if (!origin) return callback(null, true);
// if (allowedOrigins.indexOf(origin) === -1) {
// const msg = "El origen CORS no está permitido por la política de este servidor.";
// return callback(new Error(msg), false);
// }
// return callback(null, true);
// },
// methods: ["GET", "POST", "PUT", "DELETE"],
// credentials: true,
// };
// app.use(cors(corsOptions));
// Backend/src/app/routes.ts
import { Router } from "express";
import { ttController } from "../modules/tt/infrastructure/index";
import { userController } from "../modules/user/infrastructure/index";
// import { checkJwt, checkRoles } from '../middlewares/auth'; // Middlewares para Auth0
/**
* Creamos un Router principal
*/
export const router = Router();
// // Rutas específicas para el módulo TT
// router.post("/tts", checkJwt, checkRoles('academico'), ttController.createTT, ttController.createTTHandler);
// router.get("/tts", checkJwt, checkRoles(['academico', 'gestor']), ttController.listTT);
// router.get("/tts/:ttId", checkJwt, checkRoles(['academico', 'gestor']), ttController.getTTById);
// router.put("/tts/:ttId", checkJwt, checkRoles('gestor'), ttController.updateTT);
// router.delete("/tts/:ttId", checkJwt, checkRoles('gestor'), ttController.deleteTT);
// // Rutas específicas para el módulo Usuario
// router.post("/users", userController.createUser); // Registro de usuarios, podría estar protegido si solo admins pueden crear usuarios
// router.get("/users", checkJwt, checkRoles(['admin']), userController.listUsers);
// router.get("/users/:userId", checkJwt, checkRoles(['admin', 'self']), userController.getUserById);
// router.put("/users/:userId", checkJwt, checkRoles(['admin', 'self']), userController.updateUser);
// router.delete("/users/:userId", checkJwt, checkRoles('admin'), userController.deleteUser);
// router.post("/login", userController.loginUser); // Opcional: Ruta de login si es necesario
router.get("/tts/semantic", ttController.searchSemanticTT);
router.post(
"/tts/metadata",
ttController.createTT,
ttController.extractMetadata
);
router.post("/tts/multiple", ttController.getMultipleTTs);
router.post("/tts", ttController.createTT, ttController.createTTHandler);
router.get("/tts", ttController.listTT);
router.get("/tts/:ttId", ttController.getTTById);
router.put("/tts/:ttId", ttController.updateTT);
router.delete("/tts/:ttId", ttController.deleteTT);
router.get("/tts/:ttId/download", ttController.downloadTT);
router.patch("/tts/:ttId/approve", ttController.approveTT);
router.patch("/tts/:ttId/reject", ttController.rejectTT);
// Rutas específicas para el módulo Usuario
router.post("/users", userController.createUser); // Registro de usuarios, podría estar protegido si solo admins pueden crear usuarios
router.get("/users", userController.listUsers);
router.get("/users/:userId", userController.getUserById);
router.put("/users/:userId", userController.updateUser);
router.delete("/users/:userId", userController.deleteUser);
router.post("/refresh-token", userController.refreshToken); // Opcional: Ruta de refresco de token
router.post("/login", userController.loginUser); // Opcional: Ruta de login si es necesario
router.post("/login-with-token", userController.loginUserWithToken); // Opcional: Ruta de login con token
router.post("/users/:userId/history", userController.addTTToHistory);
router.get("/users/:userId/history", userController.getUserHistory);
// Ruta de prueba para verificar que las rutas están funcionando
router.get("/test", (req, res) => {
res.send("Ruta de test funcionando correctamente");
});
// Backend/src/modules/user/application/useCases/GetUserHistoryUseCase.ts
import { UserRepositoryPort } from "../../domain/UserRepositoryPort";
export class GetUserHistoryUseCase {
constructor(private readonly userRepository: UserRepositoryPort) {}
/**
* Ejecuta el caso de uso para obtener el historial de TT's de un usuario.
* @param userId - ID del usuario
* @returns Array de IDs de TT's
*/
public async execute(userId: string): Promise<string[]> {
if (!userId) {
throw new Error("User ID is required");
}
const history = await this.userRepository.getHistory(userId);
return history;
}
}
// Backend/src/modules/user/application/useCases/UpdateUserUseCase.ts
import { UserRepositoryPort } from "../../domain/UserRepositoryPort";
import { UserEntity } from "../../domain/entities/UserEntity";
import { DeepPartial } from "../../../../shared/types/DeepPartial";
/**
* Caso de uso para actualizar un Usuario existente.
*/
export class UpdateUserUseCase {
constructor(private readonly userRepository: UserRepositoryPort) {}
/**
* Ejecuta el caso de uso para actualizar un Usuario.
* @param id - ID del Usuario a actualizar
* @param updateData - Datos a actualizar
* @returns UsuarioEntity actualizada o null si no se encuentra
*/
public async execute(
id: string,
updateData: DeepPartial<UserEntity>
): Promise<UserEntity | null> {
// Si se actualiza el email, verificar si ya existe en Auth0
if (updateData.email) {
const existingUser = await this.userRepository.findUserByEmail(
updateData.email
);
if (existingUser && existingUser._id !== id) {
throw new Error("El email ya está en uso");
}
// Actualizar el email en Auth0 también si es necesario
// await this.auth0Service.updateUserEmail(id, updateData.email);
}
// Actualizar el Usuario en la base de datos (solo datos adicionales si es necesario)
return await this.userRepository.updateUserById(id, updateData);
}
}
// Backend/src/modules/user/application/useCases/GetUserByIdUseCase.ts
import { UserRepositoryPort } from "../../domain/UserRepositoryPort";
import { UserEntity } from "../../domain/entities/UserEntity";
/**
* Caso de uso para obtener un Usuario por su ID.
*/
export class GetUserByIdUseCase {
constructor(private readonly userRepository: UserRepositoryPort) {}
/**
* Ejecuta el caso de uso para obtener un Usuario por ID.
* @param id - ID del Usuario
* @returns UsuarioEntity o null si no se encuentra
*/
public async execute(id: string): Promise<UserEntity | null> {
return await this.userRepository.findUserById(id);
}
}
// Backend/src/modules/user/application/useCases/AddTTToHistoryUseCase.ts
import { UserRepositoryPort } from "../../domain/UserRepositoryPort";
export class AddTTToHistoryUseCase {
constructor(private readonly userRepository: UserRepositoryPort) {}
/**
* Ejecuta el caso de uso para agregar un TT al historial del usuario.
* @param userId - ID del usuario
* @param ttId - ID del TT visitado
* @param maxLength - Máximo de TT's en el historial (por defecto 45)
*/
public async execute(
userId: string,
ttId: string,
maxLength: number = 45
): Promise<void> {
if (!userId || !ttId) {
throw new Error("User ID and TT ID are required");
}
await this.userRepository.addToHistory(userId, ttId, maxLength);
}
}
// Backend/src/modules/user/application/useCases/DeleteUserUseCase.ts
import { UserRepositoryPort } from "../../domain/UserRepositoryPort";
/**
* Caso de uso para eliminar un Usuario.
*/
export class DeleteUserUseCase {
constructor(private readonly userRepository: UserRepositoryPort) {}
/**
* Ejecuta el caso de uso para eliminar un Usuario.
* @param id - ID del Usuario a eliminar
* @returns true si se eliminó, false si no se encontró
*/
public async execute(id: string): Promise<boolean> {
// Eliminar el Usuario en Auth0 también si es necesario
// await this.auth0Service.deleteUser(id);
const result = await this.userRepository.deleteUserById(id);
return result.deletedCount > 0;
}
}
// Backend/src/modules/user/application/useCases/CreateUserUseCase.ts
import {UserRepositoryPort} from "../../domain/UserRepositoryPort";
import {UserEntity} from "../../domain/entities/UserEntity";
import {AuthResponse} from "@supabase/supabase-js";
import {supabaseClient} from "../../../../shared/db/SupabaseClient";
import {CreateUserDTO} from "../../infrastructure/dtos/CreateUserDTO";
/**
* Caso de uso para crear un nuevo Usuario.
*/
export class CreateUserUseCase {
constructor(private readonly userRepository: UserRepositoryPort) {}
/**
* Ejecuta el caso de uso para crear un Usuario.
* @param createUserDTO - Datos del Usuario a crear
* @returns Usuario creado
*/
public async execute(createUserDTO: CreateUserDTO): Promise<UserEntity> {
if (await this.userRepository.findUserByEmail(createUserDTO.email)) {
throw new Error("El email ya está en uso");
}
const signUpResponse: AuthResponse = await supabaseClient.auth.signUp({
email: createUserDTO.email,
password: createUserDTO.password,
});
if (signUpResponse.error) {
throw new Error(signUpResponse.error.message);
}
// Aquí, en lugar de crear el usuario en la base de datos, deberíamos crear el usuario en Auth0.
// Luego, almacenar cualquier información adicional en nuestra base de datos si es necesario.
// Por simplicidad, asumiremos que Auth0 maneja la creación y solo almacenaremos datos adicionales.
// Puedes integrar con Auth0 usando su SDK o API.
// Ejemplo de integración con Auth0:
// const auth0User = await this.auth0Service.createUser(userData);
// userData._id = auth0User.id;
// Crear el Usuario en la base de datos (solo datos adicionales si es necesario)
return await this.userRepository.createUser({
nombreCompleto: createUserDTO.nombreCompleto,
email: createUserDTO.email,
roles: createUserDTO.roles || ["user"],
});
}
}
// Backend/src/modules/user/application/useCases/ListUsersUseCase.ts
import { UserRepositoryPort } from "../../domain/UserRepositoryPort";
import { UserEntity } from "../../domain/entities/UserEntity";
/**
* Caso de uso para listar Usuarios con filtros y paginación.
*/
export class ListUsersUseCase {
constructor(private readonly userRepository: UserRepositoryPort) {}
/**
* Ejecuta el caso de uso para listar Usuarios.
* @param filters - Filtros de búsqueda y paginación
* @returns Lista de Usuarios con total, página, límite y datos
*/
public async execute(filters: {
nombreCompleto?: string;
email?: string;
role?: string;
limit?: number;
page?: number;
}): Promise<{
total: number;
page: number;
limit: number;
data: UserEntity[];
}> {
return await this.userRepository.listUsers(filters);
}
}
// Backend/src/modules/user/application/useCases/LoginUserWithTokenUseCase.ts
import {UserRepositoryPort} from "../../domain/UserRepositoryPort";
import {UserEntity} from "../../domain/entities/UserEntity";
import {UserResponse} from "@supabase/supabase-js";
import {supabaseClient} from "../../../../shared/db/SupabaseClient";
import {RefreshUserTokenUseCase} from "./RefreshUserTokenUseCase";
export class LoginUserWithTokenUseCase {
constructor(private readonly userRepository: UserRepositoryPort, private readonly refreshUserTokenUseCase: RefreshUserTokenUseCase) {
}
public async execute(params: {
accessToken: string,
refreshToken: string,
expiresAt: number,
}): Promise<{
accessToken: string,
refreshToken: string,
expiresAt: number,
user: UserEntity
}> {
const now = new Date().getTime();
if (params.expiresAt < now) {
return await this.refreshUserTokenUseCase.execute({refresh_token: params.refreshToken});
}
const response: UserResponse = await supabaseClient.auth.getUser(params.accessToken);
if (response.error) {
switch (response.error.code) {
case 'session_expired': {
return await this.refreshUserTokenUseCase.execute({refresh_token: params.refreshToken});
}
case 'user_not_found':
throw new Error("Usuario no encontrado");
case 'email_not_confirmed':
throw new Error("Email no confirmado");
case 'invalid_credentials':
throw new Error("Credenciales inválidas");
default:
throw new Error("Error al iniciar sesión");
}
}
if (!response.data.user) {
throw new Error("Usuario no encontrado");
}
const {user} = response.data;
if (!user.email) {
throw new Error("Email del usuario no encontrado");
}
const userEntity: UserEntity | null = await this.userRepository.findUserByEmail(user.email);
if (!userEntity) {
throw new Error("Usuario no encontrado");
}
return {
accessToken: params.accessToken,
refreshToken: params.refreshToken,
expiresAt: params.expiresAt,
user: userEntity
}
}
}
// Backend/src/modules/user/application/useCases/LoginUserUseCase.ts
import {UserRepositoryPort} from "../../domain/UserRepositoryPort";
import {UserEntity} from "../../domain/entities/UserEntity";
import {AuthTokenResponsePassword} from "@supabase/supabase-js";
import {supabaseClient} from "../../../../shared/db/SupabaseClient";
export class LoginUserUseCase {
constructor(private readonly userRepository: UserRepositoryPort) {
}
public async execute(params: {
email: string,
password: string,
}): Promise<{
accessToken: string,
refreshToken: string,
expiresAt: number,
user: UserEntity
}> {
const response: AuthTokenResponsePassword = await supabaseClient.auth.signInWithPassword(params);
if (response.error) {
switch (response.error.code) {
case 'invalid_credentials':
throw new Error("Credenciales inválidas");
case 'user_not_found':
throw new Error("Usuario no encontrado");
case 'email_not_confirmed':
throw new Error("Email no confirmado");
default:
throw new Error("Error al iniciar sesión");
}
}
if (!response.data.user) {
throw new Error("Usuario no encontrado");
}
const {session} = response.data;
const {access_token, refresh_token, expires_at} = session;
const userEntity: UserEntity | null = await this.userRepository.findUserByEmail(params.email);
if (!userEntity) {
throw new Error("Usuario no encontrado");
}
return {
accessToken: access_token,
refreshToken: refresh_token,
expiresAt: expires_at || 0,
user: userEntity
}
}
}
// Backend/src/modules/user/application/useCases/RefreshUserTokenUseCase.ts
import {UserRepositoryPort} from "../../domain/UserRepositoryPort";
import {UserEntity} from "../../domain/entities/UserEntity";
import {supabaseClient} from "../../../../shared/db/SupabaseClient";
import {AuthResponse} from "@supabase/supabase-js";
export class RefreshUserTokenUseCase {
constructor(private readonly userRepository: UserRepositoryPort) {
}
public async execute(params: {
refresh_token: string,
}): Promise<{
accessToken: string,
refreshToken: string,
expiresAt: number,
user: UserEntity
}> {
const response: AuthResponse = await supabaseClient.auth.refreshSession(params);
if (response.error) {
switch (response.error.code) {
case 'refresh_token_not_found':
throw new Error("Token de refresco no encontrado");
case 'refresh_token_already_used':
throw new Error("Token de refresco ya utilizado");
default:
throw new Error("Error al refrescar sesión");
}
}
const {session} = response.data;
if (!session) {
throw new Error("Sesión no encontrada");
}
if (!session.user.email) {
throw new Error("Email del usuario no encontrado");
}
const {access_token, refresh_token, expires_at} = session;
const userEntity: UserEntity | null = await this.userRepository.findUserByEmail(session.user.email);
if (!userEntity) {
throw new Error("Usuario no encontrado");
}
return {
accessToken: access_token,
refreshToken: refresh_token,
expiresAt: expires_at || 0,
user: userEntity
}
}
}
// Backend/src/modules/user/domain/entities/UserEntity.ts
/**
* Entidad que representa un Usuario.
*/
export interface UserEntity {
_id?: string;
nombreCompleto: string;
email: string;
roles: string[]; // Ejemplo: ['admin', 'user']
fechaRegistro?: Date;
// ultimoLogin?: Date;
history?: string[];
// Otras propiedades que consideres necesarias
}
// Backend/src/modules/user/domain/UserRepositoryPort.ts
import { UserEntity } from "./entities/UserEntity";
import { DeepPartial } from "../../../shared/types/DeepPartial";
/**
* Puerto (interfaz) que define las operaciones del repositorio de Usuarios.
*/
export interface UserRepositoryPort {
createUser(user: UserEntity): Promise<UserEntity>;
listUsers(filters: {
nombreCompleto?: string;
email?: string;
role?: string;
limit?: number;
page?: number;
}): Promise<{
total: number;
page: number;
limit: number;
data: UserEntity[];
}>;
findUserById(id: string): Promise<UserEntity | null>;
findUserByEmail(email: string): Promise<UserEntity | null>;
updateUserById(
id: string,
updateData: DeepPartial<UserEntity>
): Promise<UserEntity | null>;
deleteUserById(id: string): Promise<{ deletedCount: number }>;
/**
* Agrega un TT al historial del usuario, manteniendo un máximo de `maxLength` TTs.
* Si el TT ya está en el historial, lo mueve al inicio.
* @param userId - ID del usuario
* @param ttId - ID del TT visitado
* @param maxLength - Máximo de TT's en el historial
*/
addToHistory(userId: string, ttId: string, maxLength: number): Promise<void>;
/**
* Obtiene el historial de TT's de un usuario.
* @param userId - ID del usuario
* @returns Array de IDs de TT's
*/
getHistory(userId: string): Promise<string[]>;
}
// Backend/src/modules/user/infrastructure/controllers/UserController.ts
// src/modules/user/infrastructure/controllers/UserController.ts
import { Request, Response, NextFunction } from "express";
import { CreateUserUseCase } from "../../application/useCases/CreateUserUseCase";
import { ListUsersUseCase } from "../../application/useCases/ListUsersUseCase";
import { GetUserByIdUseCase } from "../../application/useCases/GetUserByIdUseCase";
import { UpdateUserUseCase } from "../../application/useCases/UpdateUserUseCase";
import { DeleteUserUseCase } from "../../application/useCases/DeleteUserUseCase";
// import { AuthService } from '../services/AuthService';
import { CreateUserDTO } from "../dtos/CreateUserDTO";
import { UpdateUserDTO } from "../dtos/UpdateUserDTO";
import { DeepPartial } from "../../../../shared/types/DeepPartial";
import { UserEntity } from "../../domain/entities/UserEntity";
import { createUserSchema } from "../validators/CreateUserValidator";
import { updateUserSchema } from "../validators/UpdateUserValidator";
import { supabaseClient } from "../../../../shared/db/SupabaseClient";
import { AuthResponse, AuthTokenResponsePassword } from "@supabase/supabase-js";
import { LoginUserUseCase } from "../../application/useCases/LoginUserUseCase";
import { RefreshUserTokenUseCase } from "../../application/useCases/RefreshUserTokenUseCase";
import { LoginUserWithTokenUseCase } from "../../application/useCases/LoginUserWithTokenUseCase";
import { GetUserHistoryUseCase } from "../../application/useCases/GetUserHistoryUseCase";
import { AddTTToHistoryUseCase } from "../../application/useCases/AddTTToHistoryUseCase";
/**
* Controlador para manejar peticiones HTTP relacionadas con Usuarios.
*/
export class UserController {
constructor(
private readonly createUserUseCase: CreateUserUseCase,
private readonly listUsersUseCase: ListUsersUseCase,
private readonly getUserByIdUseCase: GetUserByIdUseCase,
private readonly updateUserUseCase: UpdateUserUseCase,
private readonly deleteUserUseCase: DeleteUserUseCase,
private readonly loginUserUseCase: LoginUserUseCase,
private readonly refreshUserTokenUseCase: RefreshUserTokenUseCase,
private readonly loginUserWithTokenUseCase: LoginUserWithTokenUseCase,
private readonly getUserHistoryUseCase: GetUserHistoryUseCase,
private readonly addTTToHistoryUseCase: AddTTToHistoryUseCase
) {}
/**
* Maneja la creación de un nuevo Usuario.
*/
public createUser = async (
req: Request,
res: Response,
next: NextFunction
): Promise<void> => {
try {
// Validar los datos del body
const { error, value } = createUserSchema.validate(req.body);
if (error) {
res
.status(400)
.json({ message: "Datos inválidos", details: error.details });
return;
}
const body: CreateUserDTO = value;
// Ejemplo simplificado:
const newUser = await this.createUserUseCase.execute(body);
res.status(201).json({
message: "Usuario creado con éxito",
data: newUser,
});
} catch (error: any) {
// Manejo de errores específicos
if (error.message === "El email ya está en uso") {
res.status(409).json({ message: error.message });
return;
}
next(error);
}
};
/**
* Maneja la lista de Usuarios con filtros y paginación.
*/
public listUsers = async (
req: Request,
res: Response,
next: NextFunction
): Promise<void> => {
try {
const filters = {
nombreCompleto: req.query.nombreCompleto as string,
email: req.query.email as string,
role: req.query.role as string,
limit: req.query.limit ? Number(req.query.limit) : 10,
page: req.query.page ? Number(req.query.page) : 1,
};
const result = await this.listUsersUseCase.execute(filters);
res.status(200).json({
message: "Lista de Usuarios obtenida con éxito",
data: result,
});
} catch (error: any) {
next(error);
}
};
/**
* Maneja obtener un Usuario por su ID.
*/
public getUserById = async (
req: Request,
res: Response,
next: NextFunction
): Promise<void> => {
try {
const { userId } = req.params;
if (!userId) {
res.status(400).json({ message: "userId es requerido" });
return;
}
const user = await this.getUserByIdUseCase.execute(userId);
if (!user) {
res.status(404).json({ message: "Usuario no encontrado" });
return;
}
res.status(200).json({
message: "Usuario obtenido con éxito",
data: user,
});
} catch (error: any) {
next(error);
}
};
/**
* Maneja actualizar un Usuario existente.
*/
public updateUser = async (
req: Request,
res: Response,
next: NextFunction
): Promise<void> => {
try {
const { userId } = req.params;
const updateData: UpdateUserDTO = req.body;
if (!userId) {
res.status(400).json({ message: "userId es requerido" });
return;
}
// Validar los datos de actualización
const { error, value } = updateUserSchema.validate(updateData);
if (error) {
res
.status(400)
.json({ message: "Datos inválidos", details: error.details });
return;
}
const updatedUser = await this.updateUserUseCase.execute(
userId,
value as DeepPartial<UserEntity>
);
if (!updatedUser) {
res.status(404).json({ message: "Usuario no encontrado" });
return;
}
res.status(200).json({
message: "Usuario actualizado con éxito",
data: updatedUser,
});
} catch (error: any) {
if (error.message === "El email ya está en uso") {
res.status(409).json({ message: error.message });
return;
}
next(error);
}
};
/**
* Maneja eliminar un Usuario.
*/
public deleteUser = async (
req: Request,
res: Response,
next: NextFunction
): Promise<void> => {
try {
const { userId } = req.params;
if (!userId) {
res.status(400).json({ message: "userId es requerido" });
return;
}
const deleted = await this.deleteUserUseCase.execute(userId);
if (!deleted) {
res.status(404).json({ message: "Usuario no encontrado" });
return;
}
res.status(200).json({
message: "Usuario eliminado con éxito",
});
} catch (error: any) {
next(error);
}
};
public refreshToken = async (
req: Request,
res: Response,
next: NextFunction
): Promise<void> => {
try {
const { refreshToken } = req.body;
if (!refreshToken) {
res.status(400).json({ message: "refreshToken es requerido" });
return;
}
res