fpavon-ee-shared 1.0.21 → 1.0.23

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.
@@ -1,4 +1,27 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
2
25
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
26
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
27
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -13,18 +36,17 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
13
36
  };
14
37
  Object.defineProperty(exports, "__esModule", { value: true });
15
38
  exports.obtenerUnidadPadre = exports.unidadesJoinFuncion = exports.getChildrenUnitIds = exports.getGerencia = exports.getChildrenLabelNumbers = exports.descifrarToken = exports.cifrado = exports.extraerNivel = exports.validarToken = void 0;
16
- const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
39
+ const jwt = __importStar(require("jsonwebtoken"));
17
40
  const connection_sql_1 = require("../bd/connection.sql"); // Asegúrate de ajustar la ruta a tu configuración de base de datos
18
41
  const axios_1 = __importDefault(require("axios"));
19
42
  function getSecret() {
20
43
  let secretString = process.env.SECRET;
21
44
  if (!secretString) {
22
- console.error("ERROR: La variable de entorno 'SECRET' no está configurada.");
23
45
  throw new Error("SECRET_NOT_CONFIGURED");
24
46
  }
25
- // 1. Limpia cualquier espacio/salto de línea invisible
47
+ // 1. Limpia el string de cualquier carácter invisible o espacio
26
48
  secretString = secretString.trim();
27
- // 2. Devuelve la clave como un Buffer codificado en UTF-8 (el encoding más común)
49
+ // 2. Convierte a Buffer binario, forzando la codificación UTF-8
28
50
  return Buffer.from(secretString, 'utf8');
29
51
  }
30
52
  const asyncHandlerWrapper = (req, res, next) => {
@@ -47,62 +69,61 @@ const validarToken = (req, res, next) => __awaiter(void 0, void 0, void 0, funct
47
69
  token = token.replace(/['"]+/g, '');
48
70
  console.error("token: validarToken ", token);
49
71
  const secret = getSecret();
50
- let data = jsonwebtoken_1.default.verify(token, secret);
51
- const { afiliado, idNavegador } = data;
52
- // Verificar si el usuario está deslogueado
53
- const queryVerificar = `SELECT logueado, idNavegador FROM Usuarios WHERE afiliado = '${data.afiliado}'`;
54
- const result = yield (0, connection_sql_1.getConnection)(queryVerificar);
55
- if (result.recordset.length === 0) {
56
- res.status(401).json({ status: false, mensaje: "Usuario no encontrado" });
57
- return;
58
- }
59
- const usuario = result.recordset[0];
60
- if (usuario.logueado === 0) {
61
- res.status(401).json({ status: false, mensaje: "Usuario deslogueado por inactividad" });
62
- return; // Terminar ejecución pero sin retornar res
63
- }
64
- //ACTIVAR LO SIGUIENTE PARA DESLOGUEO POR MISMO USUARIO EN DISTINTOS DISPOSITIVOS
65
- // if (!usuario.idNavegador || usuario.idNavegador !== idNavegador) {
66
- // res.status(401).json({ status: false, mensaje: "Sesión inválida. Posible login desde otro dispositivo." });
67
- // return;
72
+ let data = jwt.verify(token, secret);
73
+ // const { afiliado, idNavegador } = data;
74
+ // // Verificar si el usuario está deslogueado
75
+ // const queryVerificar = `SELECT logueado, idNavegador FROM Usuarios WHERE afiliado = '${data.afiliado}'`;
76
+ // const result = await getConnection(queryVerificar);
77
+ // if (result.recordset.length === 0) {
78
+ // res.status(401).json({ status: false, mensaje: "Usuario no encontrado" });
79
+ // return;
68
80
  // }
69
- req.body.token = token;
70
- req.body.nombreGerencia = data.nombreGerencia;
71
- req.body.uid = data.afiliado;
72
- req.body.nivel = data.grupoAD;
73
- req.body.nombreCompleto = data.apellido + ", " + data.nombre;
74
- req.body.cargo = data.cargo;
75
- req.body.unidad = data.unidad;
76
- req.body.unidadSuperior = data.unidadSuperior;
77
- req.body.gerencia = data.gerencia;
78
- req.body.nombreUnidad = data.nombreUnidad;
79
- req.body.documento = data.documento;
80
- req.body.usuario = {
81
- uid: data.afiliado,
82
- nivel: data.grupoAD,
83
- nombreCompleto: data.apellido + ", " + data.nombre,
84
- cargo: data.cargo,
85
- unidad: data.unidad,
86
- unidadSuperior: data.unidadSuperior,
87
- gerencia: data.gerencia,
88
- nombreUnidad: data.nombreUnidad,
89
- nombreGerencia: data.nombreGerencia,
90
- roles: data.roles,
91
- grupos: data.grupos,
92
- documento: data.documento,
93
- mail: data.mail
94
- };
95
- // Esto bloque está porque la gente de PAI no agregó la gerencia donde corresponde
96
- if (data.gerencia != 0) {
97
- req.body.gerencia = data.gerencia;
98
- }
99
- else {
100
- req.body.gerencia = data.unidad;
101
- }
102
- // Esto bloque está porque la gente de PAI no agregó la gerencia donde corresponde
103
- // Actualizar lastActivity
104
- const queryActualizar = `UPDATE Usuarios SET lastActivity = CURRENT_TIMESTAMP WHERE afiliado = '${data.afiliado}'`;
105
- yield (0, connection_sql_1.getConnection)(queryActualizar);
81
+ // const usuario = result.recordset[0];
82
+ // if (usuario.logueado === 0) {
83
+ // res.status(401).json({ status: false, mensaje: "Usuario deslogueado por inactividad" });
84
+ // return; // Terminar ejecución pero sin retornar res
85
+ // }
86
+ // //ACTIVAR LO SIGUIENTE PARA DESLOGUEO POR MISMO USUARIO EN DISTINTOS DISPOSITIVOS
87
+ // // if (!usuario.idNavegador || usuario.idNavegador !== idNavegador) {
88
+ // // res.status(401).json({ status: false, mensaje: "Sesión inválida. Posible login desde otro dispositivo." });
89
+ // // return;
90
+ // // }
91
+ // req.body.token = token;
92
+ // req.body.nombreGerencia = data.nombreGerencia;
93
+ // req.body.uid = data.afiliado;
94
+ // req.body.nivel = data.grupoAD;
95
+ // req.body.nombreCompleto = data.apellido + ", " +data.nombre;
96
+ // req.body.cargo = data.cargo;
97
+ // req.body.unidad = data.unidad;
98
+ // req.body.unidadSuperior = data.unidadSuperior;
99
+ // req.body.gerencia = data.gerencia;
100
+ // req.body.nombreUnidad = data.nombreUnidad;
101
+ // req.body.documento = data.documento;
102
+ // req.body.usuario = {
103
+ // uid: data.afiliado,
104
+ // nivel: data.grupoAD,
105
+ // nombreCompleto : data.apellido + ", " +data.nombre,
106
+ // cargo: data.cargo,
107
+ // unidad: data.unidad,
108
+ // unidadSuperior: data.unidadSuperior,
109
+ // gerencia: data.gerencia,
110
+ // nombreUnidad: data.nombreUnidad,
111
+ // nombreGerencia : data.nombreGerencia,
112
+ // roles: data.roles,
113
+ // grupos: data.grupos,
114
+ // documento: data.documento,
115
+ // mail: data.mail
116
+ // };
117
+ // // Esto bloque está porque la gente de PAI no agregó la gerencia donde corresponde
118
+ // if (data.gerencia != 0) {
119
+ // req.body.gerencia = data.gerencia;
120
+ // } else {
121
+ // req.body.gerencia = data.unidad;
122
+ // }
123
+ // // Esto bloque está porque la gente de PAI no agregó la gerencia donde corresponde
124
+ // // Actualizar lastActivity
125
+ // const queryActualizar = `UPDATE Usuarios SET lastActivity = CURRENT_TIMESTAMP WHERE afiliado = '${data.afiliado}'`;
126
+ // await getConnection(queryActualizar);
106
127
  next();
107
128
  }
108
129
  else {
@@ -128,12 +149,10 @@ const extraerNivel = (data) => {
128
149
  return nivel;
129
150
  };
130
151
  exports.extraerNivel = extraerNivel;
131
- //Para generar token que se usará en el front end
132
152
  const cifrado = (usuario) => {
133
- const secreto = getSecret();
153
+ const secretoBuffer = getSecret();
134
154
  return new Promise((resolve, reject) => {
135
- jsonwebtoken_1.default.sign(usuario, secreto, { expiresIn: '12h' }, (err, token) => {
136
- console.error("token: cifrado ", token);
155
+ jwt.sign(usuario, secretoBuffer, { expiresIn: '12h' }, (err, token) => {
137
156
  return err ? reject("no se pudo generar el JWT") : resolve(token);
138
157
  });
139
158
  });
@@ -142,7 +161,7 @@ exports.cifrado = cifrado;
142
161
  const descifrarToken = (token) => {
143
162
  token = token.replace(/['"]+/g, '');
144
163
  try {
145
- let data = jsonwebtoken_1.default.verify(token, (process.env.SECRET || ''));
164
+ let data = jwt.verify(token, (process.env.SECRET || ''));
146
165
  return data;
147
166
  }
148
167
  catch (error) {
@@ -1,5 +1,5 @@
1
1
  import { Request, Response, NextFunction, RequestHandler } from 'express';
2
- import jwt from 'jsonwebtoken';
2
+ import * as jwt from 'jsonwebtoken';
3
3
  import { getConnection } from '../bd/connection.sql'; // Asegúrate de ajustar la ruta a tu configuración de base de datos
4
4
  import axios from 'axios';
5
5
 
@@ -7,14 +7,13 @@ function getSecret(): Buffer {
7
7
  let secretString = process.env.SECRET;
8
8
 
9
9
  if (!secretString) {
10
- console.error("ERROR: La variable de entorno 'SECRET' no está configurada.");
11
10
  throw new Error("SECRET_NOT_CONFIGURED");
12
11
  }
13
12
 
14
- // 1. Limpia cualquier espacio/salto de línea invisible
13
+ // 1. Limpia el string de cualquier carácter invisible o espacio
15
14
  secretString = secretString.trim();
16
15
 
17
- // 2. Devuelve la clave como un Buffer codificado en UTF-8 (el encoding más común)
16
+ // 2. Convierte a Buffer binario, forzando la codificación UTF-8
18
17
  return Buffer.from(secretString, 'utf8');
19
18
  }
20
19
 
@@ -40,73 +39,76 @@ const validarToken = async (req: Request, res: Response, next: NextFunction): Pr
40
39
  // Limpio el token de comillas por las dudas
41
40
  token = token.replace(/['"]+/g, '');
42
41
  console.error("token: validarToken ", token)
42
+
43
+
44
+
43
45
 
44
46
  const secret = getSecret();
45
47
  let data: any = jwt.verify(token, secret);
46
- const { afiliado, idNavegador } = data;
48
+ // const { afiliado, idNavegador } = data;
47
49
 
48
- // Verificar si el usuario está deslogueado
49
- const queryVerificar = `SELECT logueado, idNavegador FROM Usuarios WHERE afiliado = '${data.afiliado}'`;
50
- const result = await getConnection(queryVerificar);
50
+ // // Verificar si el usuario está deslogueado
51
+ // const queryVerificar = `SELECT logueado, idNavegador FROM Usuarios WHERE afiliado = '${data.afiliado}'`;
52
+ // const result = await getConnection(queryVerificar);
51
53
 
52
- if (result.recordset.length === 0) {
53
- res.status(401).json({ status: false, mensaje: "Usuario no encontrado" });
54
- return;
55
- }
54
+ // if (result.recordset.length === 0) {
55
+ // res.status(401).json({ status: false, mensaje: "Usuario no encontrado" });
56
+ // return;
57
+ // }
56
58
 
57
- const usuario = result.recordset[0];
59
+ // const usuario = result.recordset[0];
58
60
 
59
- if (usuario.logueado === 0) {
60
- res.status(401).json({ status: false, mensaje: "Usuario deslogueado por inactividad" });
61
- return; // Terminar ejecución pero sin retornar res
62
- }
63
-
64
- //ACTIVAR LO SIGUIENTE PARA DESLOGUEO POR MISMO USUARIO EN DISTINTOS DISPOSITIVOS
65
- // if (!usuario.idNavegador || usuario.idNavegador !== idNavegador) {
66
- // res.status(401).json({ status: false, mensaje: "Sesión inválida. Posible login desde otro dispositivo." });
67
- // return;
61
+ // if (usuario.logueado === 0) {
62
+ // res.status(401).json({ status: false, mensaje: "Usuario deslogueado por inactividad" });
63
+ // return; // Terminar ejecución pero sin retornar res
68
64
  // }
65
+
66
+ // //ACTIVAR LO SIGUIENTE PARA DESLOGUEO POR MISMO USUARIO EN DISTINTOS DISPOSITIVOS
67
+ // // if (!usuario.idNavegador || usuario.idNavegador !== idNavegador) {
68
+ // // res.status(401).json({ status: false, mensaje: "Sesión inválida. Posible login desde otro dispositivo." });
69
+ // // return;
70
+ // // }
69
71
 
70
- req.body.token = token;
72
+ // req.body.token = token;
71
73
 
72
- req.body.nombreGerencia = data.nombreGerencia;
73
- req.body.uid = data.afiliado;
74
- req.body.nivel = data.grupoAD;
75
- req.body.nombreCompleto = data.apellido + ", " +data.nombre;
76
- req.body.cargo = data.cargo;
77
- req.body.unidad = data.unidad;
78
- req.body.unidadSuperior = data.unidadSuperior;
79
- req.body.gerencia = data.gerencia;
80
- req.body.nombreUnidad = data.nombreUnidad;
81
- req.body.documento = data.documento;
74
+ // req.body.nombreGerencia = data.nombreGerencia;
75
+ // req.body.uid = data.afiliado;
76
+ // req.body.nivel = data.grupoAD;
77
+ // req.body.nombreCompleto = data.apellido + ", " +data.nombre;
78
+ // req.body.cargo = data.cargo;
79
+ // req.body.unidad = data.unidad;
80
+ // req.body.unidadSuperior = data.unidadSuperior;
81
+ // req.body.gerencia = data.gerencia;
82
+ // req.body.nombreUnidad = data.nombreUnidad;
83
+ // req.body.documento = data.documento;
82
84
 
83
- req.body.usuario = {
84
- uid: data.afiliado,
85
- nivel: data.grupoAD,
86
- nombreCompleto : data.apellido + ", " +data.nombre,
87
- cargo: data.cargo,
88
- unidad: data.unidad,
89
- unidadSuperior: data.unidadSuperior,
90
- gerencia: data.gerencia,
91
- nombreUnidad: data.nombreUnidad,
92
- nombreGerencia : data.nombreGerencia,
93
- roles: data.roles,
94
- grupos: data.grupos,
95
- documento: data.documento,
96
- mail: data.mail
97
- };
85
+ // req.body.usuario = {
86
+ // uid: data.afiliado,
87
+ // nivel: data.grupoAD,
88
+ // nombreCompleto : data.apellido + ", " +data.nombre,
89
+ // cargo: data.cargo,
90
+ // unidad: data.unidad,
91
+ // unidadSuperior: data.unidadSuperior,
92
+ // gerencia: data.gerencia,
93
+ // nombreUnidad: data.nombreUnidad,
94
+ // nombreGerencia : data.nombreGerencia,
95
+ // roles: data.roles,
96
+ // grupos: data.grupos,
97
+ // documento: data.documento,
98
+ // mail: data.mail
99
+ // };
98
100
 
99
- // Esto bloque está porque la gente de PAI no agregó la gerencia donde corresponde
100
- if (data.gerencia != 0) {
101
- req.body.gerencia = data.gerencia;
102
- } else {
103
- req.body.gerencia = data.unidad;
104
- }
105
- // Esto bloque está porque la gente de PAI no agregó la gerencia donde corresponde
101
+ // // Esto bloque está porque la gente de PAI no agregó la gerencia donde corresponde
102
+ // if (data.gerencia != 0) {
103
+ // req.body.gerencia = data.gerencia;
104
+ // } else {
105
+ // req.body.gerencia = data.unidad;
106
+ // }
107
+ // // Esto bloque está porque la gente de PAI no agregó la gerencia donde corresponde
106
108
 
107
- // Actualizar lastActivity
108
- const queryActualizar = `UPDATE Usuarios SET lastActivity = CURRENT_TIMESTAMP WHERE afiliado = '${data.afiliado}'`;
109
- await getConnection(queryActualizar);
109
+ // // Actualizar lastActivity
110
+ // const queryActualizar = `UPDATE Usuarios SET lastActivity = CURRENT_TIMESTAMP WHERE afiliado = '${data.afiliado}'`;
111
+ // await getConnection(queryActualizar);
110
112
 
111
113
  next();
112
114
  } else {
@@ -138,24 +140,14 @@ export const extraerNivel = (data)=>{
138
140
 
139
141
 
140
142
 
141
- //Para generar token que se usará en el front end
142
-
143
- export const cifrado = (usuario:any)=>{
144
-
145
-
146
- const secreto:any= getSecret();
147
- return new Promise((resolve:any,reject:any)=>{
148
-
149
- jwt.sign(usuario, secreto ,{expiresIn:'12h'},(err,token)=>{
150
- console.error("token: cifrado ", token)
143
+ export const cifrado = (usuario: any) => {
144
+ const secretoBuffer: Buffer = getSecret();
151
145
 
152
- return err ? reject("no se pudo generar el JWT") : resolve(token);
146
+ return new Promise((resolve: any, reject: any) => {
147
+ jwt.sign(usuario, secretoBuffer, {expiresIn:'12h'}, (err, token) => {
148
+ return err ? reject("no se pudo generar el JWT") : resolve(token);
153
149
  });
154
-
155
150
  });
156
-
157
-
158
-
159
151
  }
160
152
 
161
153
  export const descifrarToken = (token:string)=>{
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fpavon-ee-shared",
3
- "version": "1.0.21",
3
+ "version": "1.0.23",
4
4
  "description": "Carpeta compartida entre servicios de Expediente Electronio",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",