UNPKG

prg-class

Version:

Clases genéricas utilizadas por microservicios Programamos SPA.

237 lines (236 loc) 7.48 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PrgJwt = void 0; const jwt = require("jwt-simple"); class PrgJwt { constructor() { this.msKeySecret = this.trim(process.env.token_key); this.mlTokenDuration = this.intval(process.env.token_duration); } /** * Crea token de usuario. * @param aiIidUser ID de usuario. * @param aiIdSys ID de sistema. * @param aiIdEmp ID de empresa. * @param aiIdSuc ID de sucursal. * @param asIp ID de usuario. * @param asUserAgent User agent del usuario. */ fnCreateToken(aiIidUser, aiIdSys, aiIdEmp, aiIdSuc, asIp, asUserAgent) { const ldtIni = new Date(); const ldtEnd = this.fnDateAddDays(ldtIni, this.mlTokenDuration); const liIni = this.unixDate(ldtIni); const liEnd = this.unixDate(ldtEnd); const payload = { sub: aiIidUser, ip: asIp, ua: asUserAgent, idsys: aiIdSys, idemp: aiIdEmp, idsuc: aiIdSuc, iat: liIni, exp: liEnd, }; return jwt.encode(payload, this.msKeySecret); } fnTokenValidate(asToken, asIP, asUA) { if (asToken === undefined || asToken == null || asToken === '') { return null; } const loTk = this.decodeToken(asToken); if (loTk == null) { // Token incorrecto. return null; } const ldtNow = new Date(); const liNow = this.unixDate(ldtNow); // Fecha unix actual. if (loTk.exp <= liNow) { // Token expirado. return null; } const lsIpToken = loTk.ip; const lsUAToken = loTk.ua; if (lsIpToken !== undefined) { // Si corresponde, valida dirección IP. if (asIP !== lsIpToken) { // Valida que la dirección IP de la petición coincidan con el token. return null; } if (asUA !== lsUAToken) { // Valida que el user-agent de la petición coincidan con el token. return null; } } return loTk; } fnDecodeToken(asToken) { let loRet = null; if (asToken === '') { return loRet; } const token = asToken.replace(/[''']+/g, ''); try { loRet = jwt.decode(token, this.msKeySecret); } catch (error) { loRet = null; } return loRet; } decodeToken(asToken) { let loRet = null; if (asToken === '') { return loRet; } const token = asToken.replace(/[''']+/g, ''); try { loRet = jwt.decode(token, this.msKeySecret); } catch (error) { loRet = null; } return loRet; } unixDate(aoDate) { if (this.novaluePure(aoDate) || !this.fnIsValidDate(aoDate)) { return 0; } return parseInt((aoDate.getTime() / 1000).toFixed(0)); } fnDateAddDays(adtFec, alDay) { if (adtFec === null || adtFec === undefined || !this.fnIsValidDate(adtFec)) { return adtFec; } alDay = this.intval(alDay); if (alDay === 0) { return adtFec; } const ldtRet = new Date(adtFec.getFullYear(), adtFec.getMonth(), adtFec.getDate()); ldtRet.setDate(ldtRet.getDate() + alDay); return ldtRet; } novaluePure(aoValue) { return (aoValue === undefined || aoValue === null); } fnIsValidDate(aoDate) { if (Object.prototype.toString.call(aoDate) === '[object Date]') { // it is a date if (isNaN(aoDate.getTime())) { // d.valueOf() could also work // date is not valid return false; } else { // date is valid return true; } } else { // not a date return false; } // return aoDate instanceof Date && !isNaN(aoDate.getTime()); } intval(aoValue, abFtoChile = false) { if (this.novalue(aoValue)) { aoValue = '0'; } if (typeof aoValue === 'object') { return 0; } if (typeof aoValue === 'boolean') { aoValue = aoValue === true ? 1 : 0; } let lsVal = aoValue + ''; if (abFtoChile) { // Es un formato de número con separador de decimales (coma) y signo peso. lsVal = this.fnStrReplace('$', '', lsVal); lsVal = this.fnStrReplace('.', '', lsVal); lsVal = this.fnStrReplace(',', '.', lsVal); } let llRet = parseInt(lsVal, 10); if (isNaN(llRet)) { llRet = 0; } return llRet; } fnStrReplace(asCharCambiar, asCharCambio, asTxt) { if (asTxt === null || asTxt === undefined) { return ''; } if (asCharCambiar === null || asCharCambiar === undefined) { asCharCambiar = ''; } if (asCharCambio === null || asCharCambio === undefined) { asCharCambio = ''; } const lsType = typeof (asTxt); if (lsType === 'object') { if (Object.prototype.toString.call(asTxt) === '[object Date]') { const loDt = asTxt; const ldtFec = loDt; asTxt = this.fnGetDateString(ldtFec, false); } else { try { asTxt = JSON.stringify(asTxt); } catch (error) { // fnLogError(`Error en fnStrReplace: ${error}.`); } } } if (lsType !== 'string') { asTxt += ''; } let lsRet = ''; for (let i = 0; i < asTxt.length; i++) { let lsAux = asTxt.charAt(i); if (lsAux === asCharCambiar) { lsAux = asCharCambio; } lsRet += lsAux; } return lsRet; } fnGetDateString(aoDate, abHourMin) { if (aoDate === null || aoDate === undefined) { return ''; } if (!this.fnIsValidDate(aoDate)) { return ''; } let lsRet = ''; const lsSep = '-'; const llM = aoDate.getMonth() + 1; const llD = aoDate.getDate(); const llY = aoDate.getFullYear(); lsRet = llY + lsSep + llM + lsSep + llD; if (abHourMin) { lsRet += ` ${aoDate.getHours()}:${aoDate.getMinutes()}`; } return lsRet; } novalue(aoValue) { return this.novaluePure(aoValue) || aoValue === ''; } fnToString(aoValue) { let lsRet = ''; try { if (this.novaluePure(aoValue)) { aoValue = ''; } if (typeof aoValue === 'number') { aoValue = aoValue.toString(); } if (typeof aoValue === 'boolean') { aoValue = aoValue === true ? '1' : '0'; } if (typeof aoValue !== 'string') { return ''; } lsRet = aoValue.trim(); } catch (error) { // fnLogError(`Error en trim: ${error}.`); } return lsRet; } trim(aoValue) { return this.fnToString(aoValue).trim(); } } exports.PrgJwt = PrgJwt;