Files
AsineApi/routes/enviarPassword.js
T
2020-09-20 17:25:21 -05:00

115 lines
3.8 KiB
JavaScript

const connection = require('../conf/connection.js');
const express = require('express');
const nodemailer = require("nodemailer");
var randomstring = require("randomstring");
const bcrypt = require('bcrypt');
var app = express();
function query(consulta) {
return new Promise(function(resolve, reject) {
connection.query(`${consulta}`, (error, results, files) => {
if (error) reject(error);
resolve(results);
});
})
}
async function sendEmail( destination, password ) {
// Generate test SMTP service account from ethereal.email
// Only needed if you don't have a real mail account for testing
let testAccount = await nodemailer.createTestAccount();
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
service: "Gmail",
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: 'asinea103@fa.unam.mx', // generated ethereal user
pass: 'As1n34103++'
},
});
// send mail with defined transport object
let info = await transporter.sendMail({
from: '"ASINEA 2020" <asinea103@fa.unam.mx>', // sender address
to: `"${destination}"`, // list of receivers
subject: "Recupera tu contraseña ASINEA 2020", // Subject line
text: `Se ha solicitado recuperar la contraseña por lo que la nueva contraseña es: ${password}`, // plain text body
});
console.log("Message sent: %s", info.messageId);
// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>
// Preview only available when sending through an Ethereal account
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}
function depurado(cadena) {
if (cadena != null) {
cadena = cadena.replace(/'/g, "''");
cadena = cadena.replace(/;/g, "m");
return cadena;
} else
return null;
}
app.post('/enviarPassword', async(req, res) => {
let idPersona;
try{
if( typeof(req.body.correo) === 'undefined' || req.body.correo === '')
return res.status(200).json({msj: 'Falta el correo'});
let correo = depurado(req.body.correo);
let sqlQuery = `Select idPersona from persona where correo = '${correo}';`;
let ansSql = await query (sqlQuery);
if (ansSql.length == 0)
return res.status(200).json({ error: true, msj: "El correo aún no se ha registrado" });
idPersona = ansSql[0].idPersona;
let nueva = randomstring.generate({
length: 10,
charset: 'alphanumeric'
});
let n_pasword = await bcrypt.hash(nueva, 10);
let cad = `update persona set password='${n_pasword}' where idPersona=${idPersona};`;
let respuesta = query(cad);
respuesta.then(async () => {
await sendEmail(correo, nueva).catch(async error =>{
console.log('Not email: ' + error);
res.status(400).json({ error: true, msj: "No se pudo enviar el Correo"});
return;
}).then( async ans=>{
console.log('Email si fue enviado: ' + ans);
res.status(200).json({ error: false, msj: "El correo fue enviado", enviado: true});
return;
});
}).catch(() => {
return res.status(400).json({ error: true, msj: "error al actualizar la contraseña" });
})
}
catch(error){
return res.status(200).json({ error: true, msj: `error al enviar el correo ${error}` });
}
});
module.exports = app