Skip to content

Commit

Permalink
3.2.0
Browse files Browse the repository at this point in the history
  • Loading branch information
aaferna committed Jan 3, 2024
1 parent c37a3df commit ffba3fb
Show file tree
Hide file tree
Showing 23 changed files with 4,369 additions and 140 deletions.
7 changes: 6 additions & 1 deletion .env
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,9 @@ PORT=1900
ENABLE_CORS=false
ENABLE_HELMET=false
TRACE=true
PROCESS_HEADER=true
PROCESS_HEADER=true
ENABLE_USERMANAGEMENT=true
SYSTEMUSER_EXPIRE=false
SYSTEMUSER_EXPIRETIME=7d
SYSTEMUSER_SESSIONKEY=6262de2d93269cbc196faf5c11bc1e5c1c112ca65bdc5c4daa4e28c47021c78f504f9c74f502239ff3f3420798808acec86a3f7d294de9cedfdea9334c0426ad
SYSTEMUSER_PASSWORDKEY=b9bf2b09371052c2e5f08ba782fb15d4255a877520df27225141f2bae78f0b266175f6f6645bbf1f5f3d2a3e7e75212f06f3d6bf04b229c4132bd76694c10ca7
108 changes: 4 additions & 104 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,105 +1,5 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
# .env
# .env.test

# parcel-bundler cache (https://parceljs.org/)
.cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port
log/*
db/*
modules/userManagement/src/prisma/client
.DS_Store
node_modules
91 changes: 91 additions & 0 deletions functions/userManagement.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
const jwt = require('jsonwebtoken');

// Middleware para verificar el token JWT
exports.authenticateSession = async (req, res, next) => {
const { id, ip, uri, method } = trx(req);

try {
// Obtener el token Bearer del encabezado de autorización
const authHeader = req.header('Authorization');

if (!authHeader) {
return res.status(401).json({ mensaje: 'Acceso no autorizado. El token no se proporcionó.' });
}

// Verificar si el encabezado de autorización comienza con "Bearer "
const token = authHeader.split(' ')[1];

if (!token) {
return res.status(401).json({ mensaje: 'Acceso no autorizado. El token Bearer no se proporcionó.' });
}

// Verificar el token JWT
const user = await new Promise((resolve, reject) => {
jwt.verify(token, process.env.SYSTEMUSER_SESSIONKEY, async (err, user) => {
if (err) {
reject(err);
} else {
const client = modules['userManagement'].Client();
const usuario = await client.usuario.findUnique({
where: {
token: user.token,
},
});
resolve({ user: user, usuario: usuario });
}
});
});

if (!user.usuario) {
res.status(401).json({ msg: "Existe alguin inconveniente con su session" });
}

req.user = user.user; // Almacenar la información del usuario en la solicitud (opcional)

next(); // Continuar con la siguiente función de middleware
} catch (error) {
log("error", `Existe un inconveniente - ${id} :: ${ip} :: ${uri} :: ${method} :: ${error}`, "userManagement");
res.status(500).json({ msg: "Existe un inconveniente en la solicitud", id });
}
}

// Middleware para verificar el token JWT
exports.authenticateToken = async (req, res, next) => {
const { id, ip, uri, method } = trx(req);

try {
// Obtener el token Bearer del encabezado de autorización
const authHeader = req.header('Authorization');

if (!authHeader) {
return res.status(401).json({ mensaje: 'Acceso no autorizado. El token no se proporcionó.' });
}

// Verificar si el encabezado de autorización comienza con "Bearer "
const token = authHeader.split(' ')[1];

if (!token) {
return res.status(401).json({ mensaje: 'Acceso no autorizado. El token Bearer no se proporcionó.' });
}

const client = modules['userManagement'].Client();
const bearer = await client.token.findUnique({
where: {
bearer: token,
},
});


if (!bearer) {
res.status(401).json({ msg: "Existe alguin inconveniente con su session" });
}

req.bearer = {userid:bearer.userid, tokenid: bearer.tokenid, token: bearer.bearer, permissions: JSON.parse(bearer.permissions)}; // Almacenar la información del usuario en la solicitud (opcional)


next(); // Continuar con la siguiente función de middleware
} catch (error) {
log("error", `Existe un inconveniente - ${id} :: ${ip} :: ${uri} :: ${method} :: ${error}`, "userManagement");
res.status(500).json({ msg: "Existe un inconveniente en la solicitud", id });
}
}
30 changes: 28 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
require('dotenv').config();
const dirFunc = './functions/', port = parseInt(process.env.PORT) || 1900;
const dirFunc = './functions/',
dirModul = './modules/',
port = parseInt(process.env.PORT) || 1900;

global.log = require('./core/log4j').log;
global.logd = require('./core/log4j').ldebug;
global.fun = {};
global.fs = require('fs');
global.path = require('path');
global.codePath = __dirname;
global.fun =[];
global.fun = [];
global.modules = [];

if (process.argv[2] === 'dev') {
process.env.NODE_ENV = process.argv[2]
Expand Down Expand Up @@ -54,6 +57,29 @@ try {
);
}

try {
const moduleFiles = walkSync(dirModul);
moduleFiles.forEach(file => {
if (file.endsWith('/main.js')) {
const moduleDir = path.dirname(file);
const moduleName = path.basename(moduleDir);

try {

modules[moduleName] = require(`./${file}`);
if (process.env.TRACE === 'true' || process.env.NODE_ENV === 'prd') {
log('info', `Módulo ${moduleName} detectado`);
}

} catch (error) {
log('error', `Error al importar el módulo ${moduleName}: ${error}`);
}
}
});
} catch (error) {
log('error', `Error al recorrer los directorios de módulos: ${error}`);
}

const appserver = require('./server');
appserver.listen(port, () => {
log(
Expand Down
Loading

0 comments on commit ffba3fb

Please sign in to comment.