plantilla
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
node_modules/
|
||||
|
||||
.env
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"trailingComma": "es5",
|
||||
"tabWidth": 2,
|
||||
"semi": true,
|
||||
"singleQuote": true
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
# directorio_back
|
||||
|
||||
Código fuente del backend del Directorio Institucional de Acatlán
|
||||
Generated
+1648
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "directorio_back",
|
||||
"version": "1.0.0",
|
||||
"description": "Este es el backend del directorio institucional de acatlán",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "node ./server/config/test",
|
||||
"db:install": "node ./server/db/install",
|
||||
"db:data-fake": "node ./server/db/data-fake",
|
||||
"dev": "nodemon ./server/app",
|
||||
"start": "node ./server/app"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://repositorio.acatlan.unam.mx/CIDWA/directorio_back.git"
|
||||
},
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"body-parser": "^1.19.0",
|
||||
"colors": "^1.4.0",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^8.2.0",
|
||||
"express": "^4.17.1",
|
||||
"jsonwebtoken": "^8.5.1",
|
||||
"mariadb": "^2.5.3",
|
||||
"moment": "^2.29.1",
|
||||
"sequelize": "^6.6.2",
|
||||
"validator": "^13.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"nodemon": "^2.0.7"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
require('./config/config');
|
||||
const colors = require('colors');
|
||||
const bodyParser = require('body-parser');
|
||||
const cors = require('cors');
|
||||
const express = require('express');
|
||||
const app = express();
|
||||
|
||||
app.use(cors());
|
||||
|
||||
app.use(
|
||||
bodyParser.urlencoded({
|
||||
extended: false,
|
||||
})
|
||||
);
|
||||
|
||||
app.use(bodyParser.json());
|
||||
|
||||
app.get('/', (req, res) => res.send('Directorio_back'));
|
||||
|
||||
app.use(require('./routes/index'));
|
||||
|
||||
app.listen(Number(process.env.PORT), () =>
|
||||
console.log(
|
||||
`API directorio corriendo en el puerto: ${process.env.PORT}`.rainbow
|
||||
)
|
||||
);
|
||||
@@ -0,0 +1,11 @@
|
||||
const dotenv = require('dotenv');
|
||||
const colors = require('colors');
|
||||
let result = {};
|
||||
|
||||
try {
|
||||
result = dotenv.config();
|
||||
if (result.error) throw result.error;
|
||||
console.log('El archivo .env se cargado correctamente.'.underline.bold.cyan);
|
||||
} catch (err) {
|
||||
console.log('El archivo .env no se cargo.'.underline.bold.red);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
require('./config');
|
||||
const { Sequelize } = require('sequelize');
|
||||
|
||||
const sequelize = new Sequelize(
|
||||
process.env.DB,
|
||||
process.env.USERDB,
|
||||
process.env.PASSWORDDB,
|
||||
{
|
||||
host: process.env.HOSTDB,
|
||||
dialect: process.env.TYPEDB,
|
||||
logging: false,
|
||||
dialectOptions: {
|
||||
useUTC: false,
|
||||
},
|
||||
timezone: '-05:00',
|
||||
}
|
||||
);
|
||||
|
||||
module.exports = sequelize;
|
||||
@@ -0,0 +1,13 @@
|
||||
const sequelize = require('./sequelize.conf');
|
||||
require('colors');
|
||||
|
||||
sequelize
|
||||
.authenticate()
|
||||
.then(() => {
|
||||
console.log('Se ha conectado a la base de datos exitosamente.'.green);
|
||||
process.exit();
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('Hubo un error al conectarse a la base de datos: '.red, err);
|
||||
process.exit();
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
require('../config/config');
|
||||
const colors = require('colors');
|
||||
// const encriptar = require('../helper/encriptar');
|
||||
const TipoUsuario = require('./tablas/TipoUsuario');
|
||||
const Usuario = require('./tablas/Usuario');
|
||||
|
||||
const drop = async () => {
|
||||
console.log('\nPaso 1) Desinstalando la db.'.bold.blue);
|
||||
|
||||
await Usuario.drop();
|
||||
console.log('La tabla Usuario se desinstalo correctamente.'.magenta);
|
||||
|
||||
await TipoUsuario.drop();
|
||||
console.log('La tabla TipoUsuario se desinstalo correctamente.'.magenta);
|
||||
};
|
||||
|
||||
const sync = async () => {
|
||||
console.log('\nPaso 2) Instalando la db.'.bold.blue);
|
||||
|
||||
await TipoUsuario.sync();
|
||||
console.log('La tabla TipoUsuario se instalo correctamente.'.magenta);
|
||||
|
||||
await Usuario.sync();
|
||||
console.log('La tabla Usuario se instalo correctamente.'.magenta);
|
||||
};
|
||||
|
||||
const exe = async () => {
|
||||
await drop();
|
||||
await sync();
|
||||
console.log(
|
||||
'\nSe ha instalado exitosamente la base de datos.\n'.underline.bold.green
|
||||
);
|
||||
|
||||
process.exit();
|
||||
};
|
||||
|
||||
exe();
|
||||
@@ -0,0 +1,27 @@
|
||||
const { DataTypes, Model } = require('sequelize');
|
||||
const sequelize = require('../../config/sequelize.conf');
|
||||
|
||||
class TipoUsuario extends Model {}
|
||||
TipoUsuario.init(
|
||||
{
|
||||
idTipoUsuario: {
|
||||
type: DataTypes.INTEGER,
|
||||
primaryKey: true,
|
||||
allowNull: false,
|
||||
unique: true,
|
||||
autoIncrement: true,
|
||||
},
|
||||
tipoUsuario: {
|
||||
type: DataTypes.STRING(15),
|
||||
allowNull: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
sequelize,
|
||||
modelName: 'TipoUsuario',
|
||||
tableName: 'tipo_usuario',
|
||||
timestamps: false,
|
||||
}
|
||||
);
|
||||
|
||||
module.exports = TipoUsuario;
|
||||
@@ -0,0 +1,51 @@
|
||||
const { DataTypes, Model } = require('sequelize');
|
||||
const sequelize = require('../../config/sequelize.conf');
|
||||
const TipoUsuario = require('./TipoUsuario');
|
||||
|
||||
class Usuario extends Model {}
|
||||
Usuario.init(
|
||||
{
|
||||
idUsuario: {
|
||||
type: DataTypes.INTEGER,
|
||||
primaryKey: true,
|
||||
allowNull: false,
|
||||
unique: true,
|
||||
autoIncrement: true,
|
||||
},
|
||||
usuario: {
|
||||
type: DataTypes.STRING(100),
|
||||
allowNull: false,
|
||||
unique: true,
|
||||
},
|
||||
password: {
|
||||
type: DataTypes.STRING(60),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
},
|
||||
nombre: {
|
||||
type: DataTypes.STRING(70),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
},
|
||||
activo: {
|
||||
type: DataTypes.BOOLEAN,
|
||||
allowNull: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
sequelize,
|
||||
modelName: 'Usuario',
|
||||
tableName: 'usuario',
|
||||
timestamps: false,
|
||||
}
|
||||
);
|
||||
|
||||
Usuario.belongsTo(TipoUsuario, {
|
||||
foreignKey: {
|
||||
name: 'idTipoUsuario',
|
||||
type: DataTypes.INTEGER,
|
||||
allowNull: false,
|
||||
},
|
||||
});
|
||||
|
||||
module.exports = Usuario;
|
||||
@@ -0,0 +1,34 @@
|
||||
const bcrypt = require('bcrypt');
|
||||
const validar = require('./validar');
|
||||
require('../config/config');
|
||||
|
||||
const comparar = (password, dbPassword) => {
|
||||
let campo = 'password';
|
||||
|
||||
validar.noHay(password, campo);
|
||||
if (typeof password != 'string') validar.noValido(campo);
|
||||
if (!bcrypt.compareSync(password, dbPassword))
|
||||
throw new Error('Usuario o contraseña no validos.');
|
||||
return true;
|
||||
};
|
||||
|
||||
const encriptar = (password) => {
|
||||
let campo = 'password';
|
||||
|
||||
validar.noHay(password, campo);
|
||||
if (typeof password != 'string') validar.noValido(campo);
|
||||
return bcrypt.hashSync(password, Number(process.env.SALT_ROUNDS));
|
||||
};
|
||||
|
||||
const generarPassword = () => {
|
||||
let length = 8;
|
||||
let charset =
|
||||
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
|
||||
let password = '';
|
||||
|
||||
for (let i = 0, n = charset.length; i < length; ++i)
|
||||
password += charset.charAt(Math.floor(Math.random() * n));
|
||||
return password;
|
||||
};
|
||||
|
||||
module.exports = { comparar, encriptar, generarPassword };
|
||||
@@ -0,0 +1,179 @@
|
||||
const moment = require('moment');
|
||||
const validator = require('validator');
|
||||
const Servicio = require('../db/tablas/Servicio');
|
||||
|
||||
const noValido = (campo) => {
|
||||
throw new Error(`${campo} no es valido.`);
|
||||
};
|
||||
|
||||
const noHay = (variable, campo) => {
|
||||
if (!variable) throw new Error(`Falta ${campo}.`);
|
||||
};
|
||||
|
||||
const yaExiste = (campo) => {
|
||||
throw new Error(`${campo} ya se encuentra en uso.`);
|
||||
};
|
||||
|
||||
const validar = (texto, campo, length) => {
|
||||
noHay(texto, campo);
|
||||
if (typeof texto !== 'string' || (length && texto.length > length))
|
||||
noValido(campo);
|
||||
return texto;
|
||||
};
|
||||
|
||||
const validarId = (id) => {
|
||||
let campo = 'El id';
|
||||
|
||||
noHay(id, campo);
|
||||
if (typeof id === 'number') id = id.toString();
|
||||
if (typeof id !== 'string' || !validator.isNumeric(id, { no_symbols: true }))
|
||||
noValido(campo);
|
||||
return Number(id);
|
||||
};
|
||||
|
||||
const validarCorreo = (correo) => {
|
||||
let campo = 'El correo';
|
||||
|
||||
noHay(correo, campo);
|
||||
if (typeof correo !== 'string' || !validator.isEmail(correo)) noValido(campo);
|
||||
return correo;
|
||||
};
|
||||
|
||||
const caracteresEspeciales = (char) => {
|
||||
const charset = [
|
||||
' ',
|
||||
'.',
|
||||
'-',
|
||||
',',
|
||||
'/',
|
||||
'#',
|
||||
'?',
|
||||
'¿',
|
||||
':',
|
||||
';',
|
||||
'"',
|
||||
"'",
|
||||
'_',
|
||||
'%',
|
||||
'\n',
|
||||
];
|
||||
|
||||
for (let i = 0; i < charset.length; i++) if (charset[i] === char) return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
const validarTexto = (texto, campo, length) => {
|
||||
noHay(texto, campo);
|
||||
if (typeof texto !== 'string' || texto.length > length) noValido(campo);
|
||||
for (let i = 0; i < texto.length; i++) {
|
||||
if (caracteresEspeciales(texto[i])) continue;
|
||||
if (!validator.isAlpha(texto[i], 'es-ES')) noValido(campo);
|
||||
}
|
||||
return texto;
|
||||
};
|
||||
|
||||
const validarAlfanumerico = (texto, campo, length) => {
|
||||
noHay(texto, campo);
|
||||
if (typeof texto !== 'string' || texto.length > length) noValido(campo);
|
||||
for (let i = 0; i < texto.length; i++) {
|
||||
if (caracteresEspeciales(texto[i])) continue;
|
||||
if (!validator.isAlphanumeric(texto[i], 'es-ES')) noValido(campo);
|
||||
}
|
||||
return texto;
|
||||
};
|
||||
|
||||
const validarNumeroCuenta = (numeroCuenta) => {
|
||||
let campo = 'El numero de cuenta';
|
||||
|
||||
noHay(numeroCuenta, campo);
|
||||
if (
|
||||
typeof numeroCuenta !== 'string' ||
|
||||
!validator.isNumeric(numeroCuenta, { no_symbols: true }) ||
|
||||
numeroCuenta.length > 9
|
||||
)
|
||||
noValido(campo);
|
||||
return numeroCuenta;
|
||||
};
|
||||
|
||||
const validarFecha = (fecha) => {
|
||||
let campo = 'La fecha';
|
||||
let fechaMoment = moment(fecha);
|
||||
|
||||
noHay(fecha, campo);
|
||||
if (!fechaMoment.isValid()) noValido(campo);
|
||||
return fechaMoment;
|
||||
};
|
||||
|
||||
const validarNumero = (numero, length) => {
|
||||
let campo = 'El numero';
|
||||
|
||||
noHay(numero, campo);
|
||||
if (
|
||||
typeof numero !== 'string' ||
|
||||
!validator.isNumeric(numero, { no_symbols: true }) ||
|
||||
(length && numero.length > length)
|
||||
)
|
||||
noValido(campo);
|
||||
return numero;
|
||||
};
|
||||
|
||||
const validarPreTermino = (idServicio) => {
|
||||
return Servicio.findOne({ where: { idServicio } })
|
||||
.then((res) => {
|
||||
if (
|
||||
res.idCuestionarioPrograma &&
|
||||
res.idCuestionarioAlumno &&
|
||||
res.cartaTermino &&
|
||||
res.informeGlobal
|
||||
)
|
||||
return Servicio.update({ idStatus: 5 }, { where: { idServicio } });
|
||||
return false;
|
||||
})
|
||||
.then((res) => {
|
||||
if (res)
|
||||
return 'Este Servicio Social paso a Termino, espera a que COESI autorice tu liberación.';
|
||||
return '';
|
||||
});
|
||||
};
|
||||
|
||||
const validarAccesibilidad = (usuariosValidos = [], idTipoUsuario) => {
|
||||
for (let i = 0; i < usuariosValidos.length; i++)
|
||||
if (idTipoUsuario === usuariosValidos[i]) return;
|
||||
throw new Error('Este usuario no tiene permitido usar esta linea de la API.');
|
||||
};
|
||||
|
||||
const isObjectEmpty = (obj) => {
|
||||
for (let key in obj) {
|
||||
if (obj.hasOwnProperty(key)) return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const crearDDMMAAAA = (date) => {
|
||||
const fechaMoment = moment(date);
|
||||
let ddmmaaaa = '';
|
||||
|
||||
if (fechaMoment.isValid())
|
||||
ddmmaaaa = `${fechaMoment.date()}/${
|
||||
fechaMoment.month() + 1
|
||||
}/${fechaMoment.year()}`;
|
||||
return ddmmaaaa;
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
validar,
|
||||
noValido,
|
||||
yaExiste,
|
||||
noHay,
|
||||
validarCorreo,
|
||||
validarId,
|
||||
validarTexto,
|
||||
validarAlfanumerico,
|
||||
validarNumeroCuenta,
|
||||
validarFecha,
|
||||
validarNumero,
|
||||
validarPreTermino,
|
||||
validarAccesibilidad,
|
||||
isObjectEmpty,
|
||||
crearDDMMAAAA,
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
require('../config/config');
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
const verificaToken = (req, res, next) => {
|
||||
let token = req.headers.token;
|
||||
|
||||
if (!token)
|
||||
return res.status(400).json({
|
||||
message: 'No hay token',
|
||||
});
|
||||
jwt.verify(token, process.env.KEY, (err, decoded) => {
|
||||
if (err)
|
||||
return res.status(401).json({
|
||||
message: err.message,
|
||||
});
|
||||
req.decoded = decoded;
|
||||
next();
|
||||
});
|
||||
};
|
||||
|
||||
const crearToken = (info) => {
|
||||
return jwt.sign({ info }, process.env.KEY, {
|
||||
expiresIn: Number(process.env.CADUCIDAD_TOKEN),
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = { verificaToken, crearToken };
|
||||
@@ -0,0 +1,6 @@
|
||||
const express = require("express");
|
||||
const app = express();
|
||||
|
||||
// app.use(require("./"));
|
||||
|
||||
module.exports = app;
|
||||
Reference in New Issue
Block a user