send function parameter values into html template using node js - html

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);
}
});
}
});

Related

SMTP email configuration OTP Not Send in my email?

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 })
}
}
)
})

I have a form page that I want to send emails from but

function Getqueryandsend(){
alert("!")
const params = new URLSearchParams(window.location.search);
const fname = params.get("fname")
const lname = params.get("lname")
const email = params.get("email")
const messeage = params.get("fname")
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'example#gmail.com',
pass: 'example'
}
});
var mailOptions = {
from: 'example#gmail.com',
to: "example#gmail.com",
subject: 'from' + fname + ' ' +lname,
text: 'Dear Rashed <br></br>' + messeage
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
alert("something went wrong")
} else {
alert("messeage sent")
}
});
}
The code that in there is JSX it is out of the main function with the return I adde'd the email minute ago could that have affect or if anyone has another solution like SMTP please send it to me. for some reason it only runs a part of the code not the entirety it also doesn't give error message.

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());

Passing authentication token to HTML pages

I have a user authentication system that generates an access token upon successful authentication. I need to pass this token to other pages as the header parameter to allow usage of that page.
module.exports.authenticate=function(req,res){
var email=req.body.email;
var password=req.body.password;
connection.query('SELECT * FROM org WHERE email = ?',[email], function (error, results, fields) {
if (error) {
res.json({
status:false,
message:'query error'
})
}else{
if(results.length >0){
if(bcrypt.compareSync(password, results[0].password)){
var access_token = jwt.sign({ id: email }, 'secretpassword123', {expiresIn: 3600});
var decoded = jwt.decode(access_token, 'secretpassword123');
var expires_in = decoded.exp-decoded.iat;
var token_type = "org";
console.log(decoded);
req.headers.access_token = access_token;
res.cookie('access-token', access_token, { expires: new Date(Date.now() + 3600)})
res.status(200).send({ auth: true, access_token: access_token, expires_in, token_type});
}
else{
res.json({
status:false,
message:"Email or password does not match"
});
}
}
else{
connection.query('SELECT * FROM client WHERE email = ?',[email], function (error, results, fields) {
if (error) {
res.json({
status:false,
message:'query error'
})
}else{
if(results.length >0){
if(bcrypt.compareSync(password, results[0].password)){
var access_token = jwt.sign({ id: email }, 'secretpassword123', {expiresIn: 3600});
var decoded = jwt.decode(access_token, 'secretpassword123');
var expires_in = decoded.exp-decoded.iat;
var token_type = "client";
//res.status(200).send({ auth: true, access_token: access_token, expires_in, token_type});
connection.query('UPDATE client SET fingerprint = ?', access_token, function(error, results, fields){
if(error){
console.log(error);
}
else{
console.log(results);
}
})
return res.redirect('/dashboard.html');
}
else{
res.json({
status:false,
message:"Email and password does not match"
});
}
}
else{
res.json({
status:false,
message:"Email does not exist"
});
}
}
});
}
}
});}
I want to pass the access-token to other pages and controllers as a way to authorize.
For example, this is my get-user controller:
module.exports.getUser = function(req,res){
var email = req.body.email;
req.headers.access_token = authenticate.authenticate.access_token
connection.query('SELECT clientid, email, orgid, name, phone, type, role, fingerprint, verified FROM client WHERE email = ?', req.body.email, function(error,results, fields){
if(error){
console.log(error)
res.redirect('/dashboard.html');
}
else{
console.log(req.headers)
console.log(results)
//res.redirect('/dashboard.html');
res.status(200).send(results);
}
})
}
How should I approach this?
I have added res.cookie to the authentication module, and I can see that the cookie gets stored in the browser. But when I try to read the cookie in another page with req.cookies or req.signedCookies it says undefined.
I ended up using localStorage to store the tokens. This is obviously not secure by oAuth standards, but it works. How can I use cookies to get the same functionality as local storage. I need to use the token generated in the authentication module to verify authorization in other pages.
This is usually achieved using cookies. After a cookie is set, it will be attached to every request the browser makes to the server. E.g. if you're using a framework like express, you could do something like
res.cookie('access-token', access_token, { expires: new Date(Date.now() + 300000), httpOnly: true })
But actually this is just a convenience method to add the "Set-Cookie"-HTTP-Header to your response, which causes the browser to create a cookie: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
Btw, for security reasons you should probably set the 'Secure' and the 'HttpOnly' flags, which make sure, that the cookie is only sent using TLS (HTTPS) and cannot be read by JavaScript respectively. The 'SameSite'-Directive is also useful for preventing CSRF attacks.

Google Authentication using Sails.js

When I have tried to implement Google authentication in my site, using sails JavaScript, and MySQL getting error. I have using passport and passport-Google-auth Strategy. Problem is not getting data to my site from Google
My Express Config(express.js) file is like below,
var passport = require('passport')
, GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
var verifyHandler = function(token, tokenSecret, profile, done) {
process.nextTick(function() {
console.log(profile)
User.findOne({uid: profile.id}, function(err, user) {
if (user) {
return done(null, user);
} else {
var data = {
provider: profile.provider,
uid: profile.id,
name: profile.displayName
};
if (profile.emails && profile.emails[0] && profile.emails[0].value) {
data.email = profile.emails[0].value;
}
if (profile.name && profile.name.givenName) {
data.firstname = profile.name.givenName;
}
if (profile.name && profile.name.familyName) {
data.lastname = profile.name.familyName;
}
User.create(data, function(err, user) {
return done(err, user);
});
}
});
});
};
passport.serializeUser(function(user, done) {
console.log(user)
done(null, user.uid);
});
passport.deserializeUser(function(uid, done) {
User.findOne({uid: uid}, function(err, user) {
done(err, user);
});
});
module.exports.http = {
customMiddleware: function(app) {
passport.use(new GoogleStrategy({
clientID: 'Client Id here',
clientSecret: 'Secret key here',
callbackURL: 'http://localhost:1337/auth/google/callback'
}, verifyHandler));
app.use(passport.initialize());
app.use(passport.session());
}
};
module.exports.cache = {
// The number of seconds to cache files being served from disk
// (only works in production mode)
maxAge: 31557600000
};
module.exports.userlogin = {
userModel: 'user'
};
And My Auth Controller I have added code like below,
google: function(req, res) {
passport.authenticate('google',{
failureRedirect: '/login', scope: ['profile', 'email']
}, function(err, user) {
req.logIn(user, function(err) {
if (err) {
console.log(err);
res.view('500');
return;
}
res.redirect('/');
return;
});
})(req, res);
},
You didn't post your code, so we can't find the exact problem :/
I usually use this method for google/facebook authentication with sails.js.
I follow at first this documentation to add the authentication buttons in the frontend:
https://developers.google.com/identity/sign-in/web/sign-in
Then I post the token that I got from google/facebook to the backend where I can check if the user is banned or whatever... If everything is correct, I create an account for him in the database, I send him his password to his email and finally authenticate him using sessions
(req.session.userId = createdUser.id)
In the next time the user can log in using his email and password or just using google. And both options lead him to the same account :D
My Sails.js function in the authentication controller:
googleAuth: function(req, res) {
if (_.isUndefined(req.param('googleToken'))) {
return res.json({
success: false,
msg: 'Error! Please post your google token'
});
}
var urlToRq = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=" + req.param('googleToken');
// Get information about the google user with the specified access token.
request.get({url: urlToRq}, function(err, response, body) {
if(err) {
return res.json({
success: false,
msg: 'Server Error'
});
}
var receivedData = JSON.parse(body);
var userId = receivedData.sub;
var userEmail = receivedData.email;
var emailVerified = receivedData.email_verified;
var userName = receivedData.name;
var userPicture = receivedData.picture;
if (emailVerified == false) {
return res.json({
success: false,
msg: 'Your email is not verified'
});
}
else {
// AUTHENTICATION VERIFIED, YOU CAN SAVE THE CONNECTED USER IN A SESSION, OR ADD HIM TO THE DATABASE AS A NEW ACCOUNT, OR CHECK IF HE HAS A PREVIOUS ACCOUNT OR WHATEVER YOU WANT...
}
});
},
Of course don't forget to run npm install request --save
If anyone needs the facebookAuth function just tell me :D I will post it for you :)