nuxt-authenticate-module 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +332 -0
  2. package/dist/module.d.mts +10 -0
  3. package/dist/module.json +9 -0
  4. package/dist/module.mjs +79 -0
  5. package/dist/runtime/assets/main.css +1 -0
  6. package/dist/runtime/components/UserInfo.d.vue.ts +2 -0
  7. package/dist/runtime/components/UserInfo.vue +29 -0
  8. package/dist/runtime/components/UserInfo.vue.d.ts +2 -0
  9. package/dist/runtime/composable/closeSession.d.ts +3 -0
  10. package/dist/runtime/composable/closeSession.js +13 -0
  11. package/dist/runtime/middleware/protected.d.ts +2 -0
  12. package/dist/runtime/middleware/protected.js +6 -0
  13. package/dist/runtime/page/UserLogin.d.vue.ts +2 -0
  14. package/dist/runtime/page/UserLogin.vue +112 -0
  15. package/dist/runtime/page/UserLogin.vue.d.ts +2 -0
  16. package/dist/runtime/page/UserRegister.d.vue.ts +2 -0
  17. package/dist/runtime/page/UserRegister.vue +150 -0
  18. package/dist/runtime/page/UserRegister.vue.d.ts +2 -0
  19. package/dist/runtime/server/api/auth/closeSession.post.d.ts +4 -0
  20. package/dist/runtime/server/api/auth/closeSession.post.js +7 -0
  21. package/dist/runtime/server/api/auth/login.post.d.ts +5 -0
  22. package/dist/runtime/server/api/auth/login.post.js +9 -0
  23. package/dist/runtime/server/api/auth/register.post.d.ts +5 -0
  24. package/dist/runtime/server/api/auth/register.post.js +8 -0
  25. package/dist/runtime/server/middleware/session.d.ts +2 -0
  26. package/dist/runtime/server/middleware/session.js +16 -0
  27. package/dist/runtime/server/modules/auth/auth.errors.d.ts +4 -0
  28. package/dist/runtime/server/modules/auth/auth.errors.js +32 -0
  29. package/dist/runtime/server/modules/auth/auth.user.d.ts +24 -0
  30. package/dist/runtime/server/modules/auth/auth.user.js +10 -0
  31. package/dist/runtime/server/modules/auth/index.d.ts +2 -0
  32. package/dist/runtime/server/modules/auth/index.js +2 -0
  33. package/dist/runtime/server/modules/functions/errors/errors.controler.d.ts +6 -0
  34. package/dist/runtime/server/modules/functions/errors/errors.controler.js +15 -0
  35. package/dist/runtime/server/modules/functions/errors/errors.model.d.ts +10 -0
  36. package/dist/runtime/server/modules/functions/errors/index.d.ts +2 -0
  37. package/dist/runtime/server/modules/functions/errors/index.js +1 -0
  38. package/dist/runtime/server/modules/functions/utils/comparePassword.d.ts +1 -0
  39. package/dist/runtime/server/modules/functions/utils/comparePassword.js +4 -0
  40. package/dist/runtime/server/modules/functions/utils/hashPassword.d.ts +1 -0
  41. package/dist/runtime/server/modules/functions/utils/hashPassword.js +4 -0
  42. package/dist/runtime/server/modules/session/index.d.ts +4 -0
  43. package/dist/runtime/server/modules/session/index.js +3 -0
  44. package/dist/runtime/server/modules/session/session.close.d.ts +12 -0
  45. package/dist/runtime/server/modules/session/session.close.js +7 -0
  46. package/dist/runtime/server/modules/session/session.errors.d.ts +4 -0
  47. package/dist/runtime/server/modules/session/session.errors.js +16 -0
  48. package/dist/runtime/server/modules/session/session.register.d.ts +21 -0
  49. package/dist/runtime/server/modules/session/session.register.js +5 -0
  50. package/dist/runtime/server/modules/session/session.types.d.ts +31 -0
  51. package/dist/runtime/server/modules/users/index.d.ts +5 -0
  52. package/dist/runtime/server/modules/users/index.js +4 -0
  53. package/dist/runtime/server/modules/users/user.checkIsExist.d.ts +14 -0
  54. package/dist/runtime/server/modules/users/user.checkIsExist.js +8 -0
  55. package/dist/runtime/server/modules/users/user.errors.d.ts +4 -0
  56. package/dist/runtime/server/modules/users/user.errors.js +64 -0
  57. package/dist/runtime/server/modules/users/user.register.d.ts +21 -0
  58. package/dist/runtime/server/modules/users/user.register.js +10 -0
  59. package/dist/runtime/server/modules/users/user.repository.d.ts +10 -0
  60. package/dist/runtime/server/modules/users/user.validator.d.ts +9 -0
  61. package/dist/runtime/server/modules/users/user.validator.js +16 -0
  62. package/dist/runtime/server/service/index.d.ts +3 -0
  63. package/dist/runtime/server/service/index.js +3 -0
  64. package/dist/runtime/server/service/login.service.d.ts +8 -0
  65. package/dist/runtime/server/service/login.service.js +13 -0
  66. package/dist/runtime/server/service/registrarionUser.service.d.ts +5 -0
  67. package/dist/runtime/server/service/registrarionUser.service.js +6 -0
  68. package/dist/runtime/server/service/sesionClose.service.d.ts +5 -0
  69. package/dist/runtime/server/service/sesionClose.service.js +8 -0
  70. package/dist/runtime/server/tsconfig.json +3 -0
  71. package/dist/runtime/server/types/auth.d.ts +25 -0
  72. package/dist/runtime/server/utility/getSessionRepository.d.ts +13 -0
  73. package/dist/runtime/server/utility/getSessionRepository.js +10 -0
  74. package/dist/runtime/server/utility/getUserRepository.d.ts +13 -0
  75. package/dist/runtime/server/utility/getUserRepository.js +10 -0
  76. package/dist/runtime/server/utility/index.d.ts +2 -0
  77. package/dist/runtime/server/utility/index.js +2 -0
  78. package/dist/runtime/tsconfig.json +3 -0
  79. package/dist/runtime/utility/fetchError.d.ts +28 -0
  80. package/dist/runtime/utility/fetchError.js +4 -0
  81. package/dist/runtime/utility/index.d.ts +1 -0
  82. package/dist/runtime/utility/index.js +1 -0
  83. package/dist/types.d.mts +3 -0
  84. package/package.json +69 -0
@@ -0,0 +1,150 @@
1
+ <script setup>
2
+ import * as z from "zod";
3
+ import { useFetchError } from "../utility";
4
+ const fields = [{
5
+ name: "userName",
6
+ type: "text",
7
+ label: "Nombre de usuario",
8
+ description: "El nombre de usuario se utilizar\xE1 para iniciar sesi\xF3n",
9
+ placeholder: "Ingresa tu nombre de usuario",
10
+ required: true,
11
+ ui: {
12
+ wrapper: "mb-6"
13
+ }
14
+ }, {
15
+ name: "password",
16
+ label: "Contrase\xF1a",
17
+ type: "password",
18
+ placeholder: "Ejemplo: @MiContrase\xF1a01",
19
+ required: true
20
+ }, {
21
+ name: "password2",
22
+ label: "Repetir Contrase\xF1a",
23
+ type: "password",
24
+ placeholder: "Ingresa de nuevo la contrase\xF1a",
25
+ required: true
26
+ }, {
27
+ name: "name",
28
+ label: "Nombre",
29
+ type: "text",
30
+ placeholder: "Nombre",
31
+ required: true
32
+ }, {
33
+ name: "lastName",
34
+ label: "Apellido",
35
+ type: "text",
36
+ placeholder: "Apellido",
37
+ help: "",
38
+ required: true
39
+ }, {
40
+ name: "personId",
41
+ label: "C\xE9dula",
42
+ type: "text",
43
+ placeholder: "7-777-7777",
44
+ required: true
45
+ }];
46
+ const personIdRegex = /^\d{1,4}-\d{1,4}-\d{1,4}$/;
47
+ const schema = z.object({
48
+ userName: z.string("Nombre de usuario requerido").nonempty("Nombre de usuario requerido"),
49
+ password: z.string("Contrase\xF1a obligatoria").min(8, "La contrase\xF1a debe tener al menos 8 caracteres").regex(/(?=.*[a-z])/, "Debe contener al menos una letra min\xFAscula").regex(/(?=.*[A-Z])/, "Debe contener al menos una letra may\xFAscula").regex(/(?=.*\d)/, "Debe contener al menos un n\xFAmero").regex(/(?=.*[@$!%*?&])/, "Debe contener al menos un car\xE1cter especial (@$!%*?&)"),
50
+ password2: z.string("Confirme la contrase\xF1a"),
51
+ name: z.string("Nombre requerido").min(3, "El nombre de usuairo debe contener al menos 3 caracteres"),
52
+ lastName: z.string("Apellido requerido").min(3, "El apellido debe contener al menos 3 caracteres"),
53
+ personId: z.string("C\xE9dula requerida").regex(personIdRegex, "Formato de c\xE9dula inv\xE1lida")
54
+ }).refine((data) => data.password === data.password2, {
55
+ message: "Las contrase\xF1as no coinciden",
56
+ path: ["password2"]
57
+ // Marca el error en el campo "password2"
58
+ });
59
+ const errorRef = useFetchError();
60
+ async function onSubmit(payload) {
61
+ try {
62
+ const res = await $fetch("/api/auth/register", {
63
+ method: "POST",
64
+ body: {
65
+ userName: payload.data.userName,
66
+ password: payload.data.password,
67
+ name: payload.data.name,
68
+ lastName: payload.data.lastName,
69
+ personId: payload.data.personId
70
+ }
71
+ });
72
+ useToast().add({
73
+ color: "success",
74
+ title: `(${res.userName}) registrado con \xE9xito`
75
+ });
76
+ await useRouter().push("/login");
77
+ } catch (error) {
78
+ const fetchError = error;
79
+ errorRef.value = fetchError;
80
+ }
81
+ }
82
+ </script>
83
+
84
+ <template>
85
+ <div
86
+ class="flex items-center justify-center"
87
+ :style="{
88
+ minHeight: '100vh'
89
+ }"
90
+ >
91
+ <UPageCard class="w-full max-w-md">
92
+ <UAuthForm
93
+ :schema="schema"
94
+ :fields="fields"
95
+ title="Registro de Usuario"
96
+ icon="i-lucide-lock"
97
+ :submit="{
98
+ label: 'Registrar usuario',
99
+ class: 'cursor-pointer'
100
+ }"
101
+ :separator="{
102
+ icon: 'i-lucide-user'
103
+ }"
104
+ @submit="onSubmit"
105
+ >
106
+ <template #description>
107
+ <span>Registro de usuario Salva Mar SA</span>
108
+ </template>
109
+ <template #providers>
110
+ <UBadge
111
+ color="warning"
112
+ variant="soft"
113
+ size="lg"
114
+ >
115
+ <span class="text-center">
116
+ El usuario debe ser habilitado por el administrador del sistema luego del registro
117
+ </span>
118
+ </UBadge>
119
+ </template>
120
+ <template #password-description>
121
+ <ClientOnly>
122
+ <div>La contraseña debe cumplir con: </div>
123
+ <ul>
124
+ <li> ✓ Mínimo 8 caracteres</li>
125
+ <li> ✓ Al menos una letra minúscula</li>
126
+ <li> ✓ Al menos una letra mayúscula</li>
127
+ <li> ✓ Al menos un carácter especial (@$!%*?&)</li>
128
+ <li> ✓ Al menos un número [0-9]</li>
129
+ </ul>
130
+ </ClientOnly>
131
+ </template>
132
+ <template #validation>
133
+ <UAlert
134
+ v-if="errorRef"
135
+ color="error"
136
+ icon="i-lucide-info"
137
+ :title="`Error ${errorRef.statusCode}`"
138
+ :description="errorRef.data.message"
139
+ />
140
+ </template>
141
+ <template #footer>
142
+ <ULink
143
+ to="/login"
144
+ class="text-primary font-medium"
145
+ >Ir a inicio de sesión</ULink>.
146
+ </template>
147
+ </UAuthForm>
148
+ </UPageCard>
149
+ </div>
150
+ </template>
@@ -0,0 +1,2 @@
1
+ declare const _default: import("vue").DefineComponent<{}, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<{}> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
2
+ export default _default;
@@ -0,0 +1,4 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<{
2
+ message: string;
3
+ }>>;
4
+ export default _default;
@@ -0,0 +1,7 @@
1
+ import { defineEventHandler } from "h3";
2
+ import { getSessionRepository } from "utility";
3
+ import { handleCloseSession } from "service";
4
+ export default defineEventHandler(async (event) => {
5
+ const sessionRepository = getSessionRepository(event);
6
+ return await handleCloseSession(event, sessionRepository);
7
+ });
@@ -0,0 +1,5 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<{
2
+ id: number;
3
+ user: string;
4
+ }>>;
5
+ export default _default;
@@ -0,0 +1,9 @@
1
+ import { handleUserLogin } from "service";
2
+ import { getSessionRepository, getUserRepository } from "utility";
3
+ import { defineEventHandler, readBody } from "h3";
4
+ export default defineEventHandler(async (event) => {
5
+ const user = await readBody(event);
6
+ const sessionRepository = getSessionRepository(event);
7
+ const userRepository = getUserRepository(event);
8
+ return await handleUserLogin(event, userRepository, user, sessionRepository);
9
+ });
@@ -0,0 +1,5 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<{
2
+ id: number;
3
+ userName: string;
4
+ }>>;
5
+ export default _default;
@@ -0,0 +1,8 @@
1
+ import { defineEventHandler, readBody } from "h3";
2
+ import { getUserRepository } from "utility/getUserRepository";
3
+ import { handleUserRegistration } from "service";
4
+ export default defineEventHandler(async (event) => {
5
+ const user = await readBody(event);
6
+ const userRepository = getUserRepository(event);
7
+ return await handleUserRegistration(userRepository, user);
8
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<void>>;
2
+ export default _default;
@@ -0,0 +1,16 @@
1
+ import { defineEventHandler } from "h3";
2
+ export default defineEventHandler(async (event) => {
3
+ const session = await getUserSession(event);
4
+ console.log(session.user?.sessionId, event.node.req.url);
5
+ if (session?.user?.sessionId) {
6
+ event.context.sessionId = session.user.sessionId;
7
+ console.log("Session ID set in context:", event.context.sessionId);
8
+ await replaceUserSession(event, {
9
+ user: {
10
+ name: session.user.name,
11
+ sessionId: session.user.sessionId,
12
+ activityTime: (/* @__PURE__ */ new Date()).getTime()
13
+ }
14
+ });
15
+ }
16
+ });
@@ -0,0 +1,4 @@
1
+ import { ErrorControler } from '../functions/errors/index.js';
2
+ declare const authErrors: ErrorControler<"NO_TOKEN" | "INVALID_TOKEN" | "EXPIRED_TOKEN" | "UNAUTHORIZED" | "NO_REGISTER" | "INVALID_PASSWORD" | "USER_NOT_ENABLED">;
3
+ type AuthErrorsCode = keyof typeof authErrors.errorMap;
4
+ export { authErrors, AuthErrorsCode };
@@ -0,0 +1,32 @@
1
+ import { ErrorControler } from "../functions/errors/index.js";
2
+ const authErrors = new ErrorControler({
3
+ NO_TOKEN: {
4
+ statusCode: 401,
5
+ message: "No se ha iniciado sesi\xF3n."
6
+ },
7
+ INVALID_TOKEN: {
8
+ statusCode: 401,
9
+ message: "Sesi\xF3n Inv\xE1lida."
10
+ },
11
+ EXPIRED_TOKEN: {
12
+ statusCode: 401,
13
+ message: "La sesi\xF3n a experado."
14
+ },
15
+ UNAUTHORIZED: {
16
+ statusCode: 403,
17
+ message: "Acceso no autorizado."
18
+ },
19
+ NO_REGISTER: {
20
+ statusCode: 404,
21
+ message: "El usuario no est\xE1 registrado."
22
+ },
23
+ INVALID_PASSWORD: {
24
+ statusCode: 401,
25
+ message: "Contrase\xF1a inv\xE1lida."
26
+ },
27
+ USER_NOT_ENABLED: {
28
+ statusCode: 403,
29
+ message: "El usuario no est\xE1 habilitado"
30
+ }
31
+ });
32
+ export { authErrors };
@@ -0,0 +1,24 @@
1
+ import type { User, IUserRepository } from 'modules/users';
2
+ export interface LoginData {
3
+ userName: User['userName'];
4
+ password: User['password'];
5
+ }
6
+ /**
7
+ * Autentica a un usuario verificando que exis ta y que la contraseña proporcionada coincida con la almacenada.
8
+ * @param userRepository Repositorio de usuarios para acceder a los datos de los usuarios.
9
+ * @param user Datos de inicio de sesión que incluyen el nombre de usuario y la contraseña.
10
+ * @returns El registro del usuario autenticado obtenido de la base de datos.
11
+ * @throws {AuthError} Cuando el usuario no está registrado o la contraseña es inválida.
12
+ */
13
+ export declare function authUser(userRepository: IUserRepository, user: LoginData): Promise<{
14
+ sessionId: number | null;
15
+ name: string;
16
+ userName: string;
17
+ password: string;
18
+ lastName: string;
19
+ personId: string;
20
+ id: number;
21
+ createdAt: Date;
22
+ updatedAt: Date;
23
+ enable: boolean;
24
+ }>;
@@ -0,0 +1,10 @@
1
+ import { authErrors } from "./auth.errors.js";
2
+ import { comparePassword } from "../functions/utils/comparePassword.js";
3
+ export async function authUser(userRepository, user) {
4
+ const uniqueUser = await userRepository.findUniqueByUserName(user.userName);
5
+ if (!uniqueUser) throw authErrors.error("NO_REGISTER");
6
+ if (!uniqueUser.enable) throw authErrors.error("USER_NOT_ENABLED");
7
+ const isMatch = await comparePassword(user.password, uniqueUser.password);
8
+ if (!isMatch) throw authErrors.error("INVALID_PASSWORD");
9
+ return uniqueUser;
10
+ }
@@ -0,0 +1,2 @@
1
+ export * from './auth.user.js';
2
+ export * from './auth.errors.js';
@@ -0,0 +1,2 @@
1
+ export * from "./auth.user.js";
2
+ export * from "./auth.errors.js";
@@ -0,0 +1,6 @@
1
+ import type { ErrorMap } from './errors.model.js';
2
+ export declare class ErrorControler<T extends string> {
3
+ errorMap: ErrorMap<T>;
4
+ constructor(errorMap: ErrorMap<T>);
5
+ error(code: keyof ErrorMap<T>): import("h3").H3Error<unknown>;
6
+ }
@@ -0,0 +1,15 @@
1
+ import { createError } from "h3";
2
+ export class ErrorControler {
3
+ errorMap;
4
+ constructor(errorMap) {
5
+ this.errorMap = errorMap;
6
+ }
7
+ error(code) {
8
+ return createError(
9
+ this.errorMap[code] || {
10
+ statusCode: 500,
11
+ message: "Internal Server Error"
12
+ }
13
+ );
14
+ }
15
+ }
@@ -0,0 +1,10 @@
1
+ export type ErrorCode<T extends string> = {
2
+ code: T
3
+ }
4
+
5
+ export type ErrorInfo = {
6
+ statusCode: number
7
+ message: string
8
+ }
9
+
10
+ export type ErrorMap<T extends string> = Record<T, ErrorInfo>
@@ -0,0 +1,2 @@
1
+ export * from './errors.controler.js';
2
+ export type * from './errors.model';
@@ -0,0 +1 @@
1
+ export * from "./errors.controler.js";
@@ -0,0 +1 @@
1
+ export declare function comparePassword(password: string, hash: string): Promise<boolean>;
@@ -0,0 +1,4 @@
1
+ import bcrypt from "bcrypt";
2
+ export async function comparePassword(password, hash) {
3
+ return await bcrypt.compare(password, hash);
4
+ }
@@ -0,0 +1 @@
1
+ export declare function hashPassword(password: string): Promise<string>;
@@ -0,0 +1,4 @@
1
+ import bcrypt from "bcrypt";
2
+ export async function hashPassword(password) {
3
+ return await bcrypt.hash(password, 10);
4
+ }
@@ -0,0 +1,4 @@
1
+ export * from './session.register.js';
2
+ export * from './session.close.js';
3
+ export * from './session.errors.js';
4
+ export type * from './session.types';
@@ -0,0 +1,3 @@
1
+ export * from "./session.register.js";
2
+ export * from "./session.close.js";
3
+ export * from "./session.errors.js";
@@ -0,0 +1,12 @@
1
+ import type { Session, ISessionRepository } from './session.types.js';
2
+ /**
3
+ * Cierra todas las sesiones activas de un usuario específico.
4
+ *
5
+ * Esta función valida el payload del token y luego actualiza todas las sesiones
6
+ * activas del usuario estableciendo su fecha de expiración al momento actual,
7
+ * efectivamente cerrando todas las sesiones.
8
+ *
9
+ * @throws {Error} Lanza un error 'SESION_NO_VALID' si no se encuentran sesiones activas para cerrar
10
+ * @returns Una promesa que se resuelve cuando las sesiones han sido cerradas exitosamente
11
+ */
12
+ export declare function sessionClose(sessionRepository: Partial<ISessionRepository>, sessionId: Session['id']): Promise<boolean>;
@@ -0,0 +1,7 @@
1
+ import { sessionErrors } from "./session.errors.js";
2
+ export async function sessionClose(sessionRepository, sessionId) {
3
+ if (!sessionRepository.sessionClose) throw sessionErrors.error("SESSION_REPOSITORY_SESSIONSCLOSE");
4
+ const affect = await sessionRepository.sessionClose(sessionId);
5
+ if (affect !== 1) throw sessionErrors.error("SESION_NO_VALID");
6
+ return true;
7
+ }
@@ -0,0 +1,4 @@
1
+ import { ErrorControler } from '../functions/errors/index.js';
2
+ declare const sessionErrors: ErrorControler<"SESION_NO_VALID" | "SESSION_REPOSITORY_CREATESESSION" | "SESSION_REPOSITORY_SESSIONSCLOSE">;
3
+ type SessionErrorsCode = keyof typeof sessionErrors.errorMap;
4
+ export { sessionErrors, SessionErrorsCode };
@@ -0,0 +1,16 @@
1
+ import { ErrorControler } from "../functions/errors/index.js";
2
+ const sessionErrors = new ErrorControler({
3
+ SESION_NO_VALID: {
4
+ statusCode: 401,
5
+ message: "La sesi\xF3n no es v\xE1lida o ha expirado."
6
+ },
7
+ SESSION_REPOSITORY_CREATESESSION: {
8
+ statusCode: 500,
9
+ message: "Error en el repositorio de sesiones al crear una sesi\xF3n."
10
+ },
11
+ SESSION_REPOSITORY_SESSIONSCLOSE: {
12
+ statusCode: 500,
13
+ message: "Error en el repositorio de sesiones al cerrar las sesiones."
14
+ }
15
+ });
16
+ export { sessionErrors };
@@ -0,0 +1,21 @@
1
+ import type { UserModel } from '../../../../../playground/generated/prisma/models.js';
2
+ import type { ISessionRepository } from './session.types.js';
3
+ /**
4
+ * Crea un nuevo registro de sesión en la base de datos para un usuario.
5
+ *
6
+ * @param sessionRepository - El repositorio de sesión para interactuar con la base de datos
7
+ * @param userId - El identificador único del usuario para crear una sesión
8
+ * @returns Una promesa que resuelve al objeto de sesión creado
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * const session = await sessionRegister(sessionRepository, 'user123');
13
+ * console.log(session.id); // ID de sesión
14
+ * ```
15
+ */
16
+ export declare function sessionRegister(sessionRepository: Partial<ISessionRepository>, userId: UserModel['id']): Promise<{
17
+ id: number;
18
+ createdAt: Date;
19
+ userId: number;
20
+ expiresAt: Date | null;
21
+ }>;
@@ -0,0 +1,5 @@
1
+ import { sessionErrors } from "./session.errors.js";
2
+ export async function sessionRegister(sessionRepository, userId) {
3
+ if (!sessionRepository.createSession) throw sessionErrors.error("SESSION_REPOSITORY_CREATESESSION");
4
+ return await sessionRepository.createSession(userId);
5
+ }
@@ -0,0 +1,31 @@
1
+ import type { User } from 'modules/users'
2
+ import type { Session } from '../../../../../playground/generated/prisma/client'
3
+
4
+ export { Session }
5
+
6
+ export interface SessionPayload {
7
+ sessionId: number
8
+ userId: number
9
+ userName: string
10
+ }
11
+
12
+ type rowsAffected = number
13
+ /**
14
+ * Interfaz de repositorio para gestionar sesiones de usuario.
15
+ *
16
+ * Proporciona métodos para crear una nueva sesión para un usuario y cerrar una sesión existente.
17
+ *
18
+ * Notas:
19
+ * - Los tipos referenciados (User['id'], Session, rowsAffected) deben documentarse en sus declaraciones.
20
+ * - Sí: puedes comentar los tipos y sus miembros con TSDoc en sus propias declaraciones.
21
+ *
22
+ * @param createSession.userId - El identificador del usuario (User['id']).
23
+ * @returns Promesa que se resuelve con la Session creada.
24
+ *
25
+ * @param sessionClose.sessionId - El identificador de la sesión a cerrar (Session['id']).
26
+ * @returns Promesa que se resuelve con el número de filas afectadas (rowsAffected).
27
+ */
28
+ export interface ISessionRepository {
29
+ createSession: (userId: User['id']) => Promise<Session>
30
+ sessionClose: (sessionId: Session['id']) => Promise<rowsAffected>
31
+ }
@@ -0,0 +1,5 @@
1
+ export * from './user.validator.js';
2
+ export * from './user.errors.js';
3
+ export * from './user.register.js';
4
+ export * from './user.checkIsExist.js';
5
+ export type * from './user.repository';
@@ -0,0 +1,4 @@
1
+ export * from "./user.validator.js";
2
+ export * from "./user.errors.js";
3
+ export * from "./user.register.js";
4
+ export * from "./user.checkIsExist.js";
@@ -0,0 +1,14 @@
1
+ import type { User } from '~/generated/prisma/client';
2
+ import type { IUserRepository } from './user.repository.js';
3
+ /**
4
+ * Verifica si existe un usuario con el ID proporcionado en la base de datos.
5
+ *
6
+ * Realiza una consulta con Prisma para buscar el usuario por su identificador.
7
+ * Si no se encuentra ningún registro, lanza un error de negocio con el código "UNREGISTER".
8
+ *
9
+ * @param userRepository - Repositorio de usuarios para realizar la consulta.
10
+ * @param userId - Identificador único del usuario a verificar.
11
+ * @returns Promesa que se resuelve sin valor si el usuario existe.
12
+ * @throws Error si el usuario no está registrado (código "UNREGISTER").
13
+ */
14
+ export declare function userCheckIsExist(userRepository: Partial<IUserRepository>, userId: User['id']): Promise<void>;
@@ -0,0 +1,8 @@
1
+ import { userErrors } from "./user.errors.js";
2
+ export async function userCheckIsExist(userRepository, userId) {
3
+ if (!userRepository?.findUniqueByUserId) throw userErrors.error("REPOSITORY_NOT_IMPLEMENTED");
4
+ const response = await userRepository.findUniqueByUserId(userId).catch(() => {
5
+ throw userErrors.error("INTERNAL_SERVER_ERROR");
6
+ });
7
+ if (!response) throw userErrors.error("UNREGISTER");
8
+ }
@@ -0,0 +1,4 @@
1
+ import { ErrorControler } from '../functions/errors/index.js';
2
+ declare const userErrors: ErrorControler<"P2002" | "P2003" | "P2000" | "P2011" | "P2012" | "P2014" | "P2015" | "P2010" | "EMPTY" | "UNREGISTER" | "PASSWORD_NOT_VALID" | "PERSONID_NOT_VALID" | "REPOSITORY_NOT_IMPLEMENTED" | "REPOSITORY_USER_REGISTER_NOT_IMPLEMENTED" | "INTERNAL_SERVER_ERROR">;
3
+ type UserErrorsCode = keyof typeof userErrors.errorMap;
4
+ export { userErrors, UserErrorsCode };
@@ -0,0 +1,64 @@
1
+ import { ErrorControler } from "../functions/errors/index.js";
2
+ const userErrors = new ErrorControler({
3
+ P2002: {
4
+ statusCode: 409,
5
+ message: "Restricci\xF3n de unicidad fallida. El usuario ya existe."
6
+ },
7
+ P2003: {
8
+ statusCode: 400,
9
+ message: "Fall\xF3 la restricci\xF3n de clave for\xE1nea. Referencia inv\xE1lida."
10
+ },
11
+ P2000: {
12
+ statusCode: 400,
13
+ message: "Valor demasiado largo para la columna."
14
+ },
15
+ P2011: {
16
+ statusCode: 400,
17
+ message: "Fall\xF3 la restricci\xF3n NOT NULL. Un campo obligatorio es nulo."
18
+ },
19
+ P2012: {
20
+ statusCode: 400,
21
+ message: "Falta un valor obligatorio."
22
+ },
23
+ P2014: {
24
+ statusCode: 400,
25
+ message: "Violaci\xF3n de relaci\xF3n obligatoria."
26
+ },
27
+ P2015: {
28
+ statusCode: 404,
29
+ message: "Registro relacionado no encontrado."
30
+ },
31
+ P2010: {
32
+ statusCode: 400,
33
+ message: "La consulta sin procesar fall\xF3."
34
+ },
35
+ EMPTY: {
36
+ statusCode: 400,
37
+ message: "No se aceptan valores vac\xEDos."
38
+ },
39
+ UNREGISTER: {
40
+ statusCode: 404,
41
+ message: "El usuario no est\xE1 registrado."
42
+ },
43
+ PASSWORD_NOT_VALID: {
44
+ statusCode: 400,
45
+ message: "La contrase\xF1a tiene un formato inv\xE1lido."
46
+ },
47
+ PERSONID_NOT_VALID: {
48
+ statusCode: 400,
49
+ message: "La c\xE9dula no contiene un formato v\xE1lido."
50
+ },
51
+ REPOSITORY_NOT_IMPLEMENTED: {
52
+ statusCode: 500,
53
+ message: "El repositorio de usuarios no est\xE1 implementado correctamente."
54
+ },
55
+ REPOSITORY_USER_REGISTER_NOT_IMPLEMENTED: {
56
+ statusCode: 500,
57
+ message: "El m\xE9todo userRegister del repositorio de usuarios no est\xE1 implementado."
58
+ },
59
+ INTERNAL_SERVER_ERROR: {
60
+ statusCode: 500,
61
+ message: "Error interno del servidor."
62
+ }
63
+ });
64
+ export { userErrors };
@@ -0,0 +1,21 @@
1
+ import type { User } from '~/generated/prisma/client';
2
+ import type { IUserRepository } from './user.repository.js';
3
+ export interface PayloadUserRegister extends Record<string, unknown> {
4
+ userName: User['userName'];
5
+ password: User['password'];
6
+ name: User['name'];
7
+ personId: User['personId'];
8
+ lastName: User['lastName'];
9
+ }
10
+ export declare function register(userRepository: Partial<IUserRepository>, user: PayloadUserRegister): Promise<{
11
+ sessionId: number | null;
12
+ name: string;
13
+ userName: string;
14
+ password: string;
15
+ lastName: string;
16
+ personId: string;
17
+ id: number;
18
+ createdAt: Date;
19
+ updatedAt: Date;
20
+ enable: boolean;
21
+ }>;
@@ -0,0 +1,10 @@
1
+ import { hashPassword } from "../functions/utils/hashPassword.js";
2
+ import { userErrors } from "./user.errors.js";
3
+ export async function register(userRepository, user) {
4
+ if (!userRepository?.userRegister) throw userErrors.error("REPOSITORY_USER_REGISTER_NOT_IMPLEMENTED");
5
+ const userCreated = await userRepository.userRegister({
6
+ ...user,
7
+ password: await hashPassword(user.password)
8
+ });
9
+ return userCreated;
10
+ }
@@ -0,0 +1,10 @@
1
+ import type { User } from '../../../../../playground/generated/prisma/client'
2
+ import type { PayloadUserRegister } from './user.register'
3
+
4
+ interface IUserRepository {
5
+ findUniqueByUserId(userId: User['id']): Promise<User | null>
6
+ userRegister(user: PayloadUserRegister): Promise<User>
7
+ findUniqueByUserName(userName: User['userName']): Promise<User | null>
8
+ }
9
+
10
+ export type { IUserRepository, User }