SMTP email configuration OTP Not Send in my email? - smtp

Hi everyone,I have some problem in SMTP mail otp befor some days otp
sent in our mail, but now otp not send what is the issue in this code,
could you suggestion from this code, should any change this code?
router.post("/userexisting", async (req, res) => {
// Generate test SMTP service account from ethereal.email
// Only needed if you don't have a real mail account for testing
let otpNumber = Math.floor((Math.random() * 900000) + 100000);
let transporter = nodemailer.createTransport({
service: 'gmail',
host: 'smtp.gmail.com',
auth: {
user: "keerthidevelopment#gmail.com",
pass: "indraamma18"
}
});
connection.query("call user_existing(?)", [req.body.user_existing], (error, results, fields) => {
if (!error) {
if (results[0][0].Result == "YOUR EXISTING") {
const mailOptions = {
from: "purchasing#cce.com.sg", // sender address
to: results[0][0].user_email, // list of receivers
subject: "OTP ", // Subject line
html: `<h4>Dear Sir/Madam,</h4>
<br>
<p>Please use the otp given below for reset the password</p>
<h4>${otpNumber}</h4>
<p>Thanks and Regards</p>
<p>Ticketing Team</p>`
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function (err, info) {
if (err) {
res.status(400).json({ Result: err, otp: 'failed to send mail', code: 1 });
} else {
res.status(200).json({ Result: 'mail send', otp: otpNumber, code: 2 });
}
})
} else {
res.status(200).json({ Result: 'User not exists', code: 1 });
}
} else {
res.status(400).json({ Result: 'something went wrong', code: 0 })
}
}
)
})

Related

if the email is not registered in the database, then data cannot be transferred to the email, I use NodeJs, NodeMailer and MYSQL for the database

permission to ask the temperature, so I use NodeMailer to send data email, the problem is that emails that are not registered in the database can still send the data. registered"
const sendMail = async (req, res) => {
const querySearch = 'SELECT * FROM user WHERE email="' + req.body.email + '"';
const email = req.body.email;
koneksi.query(querySearch, async (err, rows, field) => {
const random = require("simple-random-number-generator");
let params = {
min: 0000,
max: 9999,
integer: true
};
const CodeRandom = random(params);
const querySql = 'UPDATE user SET ? WHERE email = ?';
koneksi.query(querySql, [{ code_verification: CodeRandom, }, req.body.email], (err, rows, field) => {
// error handling
if (err) {
return res.status(500).json({ message: 'Gagal update code!', data: { code_verification: "" } });
}
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '***********#gmail.com',
pass: '*********'
}
});
const mailOptions = {
from: 'muthiazraihan27#gmail.com',
to: req.body.email,
subject: 'Kode Verifikasi Lupa Password',
html: '<h2>Berikut kode reset password anda:</h2><h1> ' + CodeRandom + '</h1> '
};
transporter.sendMail(mailOptions, (err, info) => {
if (err) {
console.log(err)
res.status(500).json({ message: 'Ada kesalahan', error: err })
} else {
res.status(200).json({
success: true, data: rows[0]
})
}
})
})
})
};
in order to answer my question

TypeError : res.status is not a function returning Login message and Token

i am getting this as error
TypeError : res.status is not a function
I do not know why, but i am getting this Error
My code is looking thus :
app.post('/api/v1/user/login', async function(req,res){
var email = req.body.email;
var password = req.body.password;
dbConn.query(`SELECT * FROM XXXXXXXXX_users WHERE email = ${dbConn.escape(req.body.email)};`,(err,result)=>{
if(err){
throw err;
return res.status(400).send({message: err,})
}
if(!result.length){
return res.status(400).send({message: 'Username and password incorrect!',})
}
bcrypt.compare(req.body.password,result[0]['password'],(err,res)=>{
if(err){
throw err;
return res.status(400).send({message: 'Username and password Incorrect!'});
}
if(result){
const token = jwt.sign({email: result[0].email,id:result[0].id},'the-super-strong-secrect',{ expiresIn: '1h' });
return res.status(200).send({message: 'OK', token}) // Error is here
}
return res.status(400).send({message: 'User and pass incorrect'})
})
})
})
I am trying to implement Login system backend API please I would like to know why this is not working as its supposed to. Kindly help. A bit new to this
Issue is in this line
bcrypt.compare(req.body.password,result[0]['password'],(err,res) //<-- Using res keyword here
See how you are using (err, res) for this callback. This interferes with
app.post('/api/v1/user/login', async function(req,res) //<-- Also using res keyword here
I would suggest you to use async/await for better cleanup.
app.post('/api/v1/user/login', async function(req, res) {
let email = req.body.email;
let password = req.body.password;
try {
const queryResult = await dbConn.query(`SELECT * FROM XXXXXXXXX_users WHERE email = ${dbConn.escape(req.body.email)};`)
if (!queryResult.length) {
return res.status(400).send({
message: 'Username and password incorrect!',
})
}
const compareResult = await bcrypt.compare(req.body.password, queryResult[0]['password'])
if (compareResult) {
const token = jwt.sign({
email: queryResult[0].email,
id: queryResult[0].id
}, 'the-super-strong-secrect', {
expiresIn: '1h'
});
return res.status(200).send({
message: 'OK',
token
})
}
return res.status(400).send({
message: 'User and pass incorrect'
})
}
catch (err) {
res.status(500).json({
err
});
}

How to store token in cookies in reactjs frontend on call by login post method to server

this is my login post method in the reactjs frontend
const login = () => {
Axios.post("http://localhost:3001/api/users/login", {
email: values.email,
password: values.password,
}).then((response) => {
console.log(response.data);
}).catch(err =>{
console.log(err)
})
};
this is my expressjs server side, here i have login post method for reactjs frontend, where iam on response i want to send token to set in cookie whenever user post on login method, below is code for login post method
login: (req, res) => {
const body = req.body;
console.log("req.body :", req.body);
getUserByEmail(body.email, (err, results) => {
console.log("results :", results);
if (err) {
console.log(err);
return;
}
if (!results) {
res.json({
status: "failure",
msg: "Invalid email or password",
});
}
const result = compareSync(body.password, results.password);
const SECRET_KEY = "xyz123";
if (result) {
results.password = undefined;
const jsontoken = sign({ result: results }, SECRET_KEY, {
expiresIn: "1h",
});
// console.log(res)
res.cookie("token", jsontoken, {
httpOnly: true,
domain: "http://localhost:3000/login",
});
return res.json({
status: "Success",
msg: "login Successfully",
token: jsontoken,
});
} else {
return res.json({
status: "failure",
msg: "Invalid email or password",
});
}
});
},
What you could do, that is actually more secure, is tell the browser using headers on the response to create a cookie.
There is a header in HTTP called Set-Cookie, which is responsible to do just that, you can read more about it here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie.
The way you add it to your request on express is by calling the res.cookie function on your express request handler. I would suggest telling the cookie to be httpOnly in order for it to not be accessible through JS code, this is just a way to avoid XSS attacks.
Here you have an example to how to achieve that:
res.cookie('token', jsontoken, { httpOnly: true });
Then in order to access the cookie, you would need to use the cookieParser middleware which is responsible in putting all the cookies the client sent in req.cookies.
You use it this way:
app.use(express.cookieParser());

No Response from mysql database in POST data using nodejs

I am using nodejs and express to connect my local mysql db, everythings look working well except no response when Iam trying to test the API in postman.
here is my code in server.js
//add sales
app.post('/sales',(req, res) => {
var POST_SALES_QUERY = {
username: req.body.username,
password: req.body.password,
fullname: req.body.fullname
}
if (!POST_SALES_QUERY) {
return res.status(400).send({ err: true, message: 'Please username' });
}
dbConn.query("INSERT INTO user_tbl SET ?", (POST_SALES_QUERY, err, results) => {
if(err){
console.log(err);
} else {
return res.send(JSON.stringify({"status": 200, "err" : null, "response": results}));
}
});
});
and in Postman, I get this:
any idea what the problem appears here?
app.post('/sales',(req, res) => {
var POST_SALES_QUERY = {
username: req.body.username,
password: req.body.password,
fullname: req.body.fullname
}
if (!POST_SALES_QUERY) {
return res.status(400).send({ err: true, message: 'Please username' });
}
let query = `INSERT INTO user_tbl (username, password, fullname) VALUES ('${POST_SALES_QUERY.username}','${POST_SALES_QUERY.password}','${POST_SALES_QUERY.fullname}')`;
dbConn.query(query,function(err,results) {
if(err){
console.log(err);
} else {
return res.status(200).json({"status": 200,"err": null,"response": results});
}
});
});
You need to tell express to treat the body as json, by calling the following codes:
app.use(express.json())
As per the documentation:
This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.

send function parameter values into html template using node js

I'm writing a service in node.js. In that, I used to send the mail to user with the verification link.
For that I used nodemailer, all works perfectly. In that, I directly used the html part, So I access the token variable. Now I need to move that html part into separate folder. Now the issue is accessing the token(ie, the params value) My code is like, modules/users.js
let sendNotification = await mailer.sendMail(userDetail.email, token);
When I create user, the token is sent to the userDetail.email. My previous mailer looks like, mailer/applicationMailer.js
async function sendMail(userMail, token) {
// let htmlTemplate = fs.readFileSync(__dirname + '/templates/mail.html');
let transporter = nodemailer.createTransport(smtpTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: {
user: 'xxx#gmail.com',
pass: '********'
}
}));
let mailOptions = {
from: 'xxx#gmail.com',
to: userMail,
cc: '',
subject: 'Account verification',
// html: htmlTemplate
html: `<p>To verify your account click LINK</p>` +
`<p>This link will be expired in two days.</p>` +
`<p><strong>Note:</strong> Contact your ADMIN, if the link is expired</p>`
};
transporter.sendMail(mailOptions, async function (error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
};
I need to move the html part into template/mail.html and access the htmlTemplate variable. There I cant access the token. I need to pass the param value to html page. How to do that?
Thanks in Advance.
You are looking for EJS
const ejs = require("ejs");
ejs.renderFile(__dirname + "/test.ejs", { token }, function (err, data) {
if (err) {
console.log(err);
} else {
const mainOptions = {
from: 'xxx#gmail.com',
to: userMail,
cc: '',
subject: 'Account verification',
html: data
};
transporter.sendMail(mainOptions, function (err, info) {
if (err) {
console.log(err);
} else {
console.log('Message sent: ' + info.response);
}
});
}
});