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

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

Related

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.

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.

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

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

How do I add routes before jsonwebtoken?

I'm working with jsonwebtoken and Im not entirely sure how it works. I have normal sign in sign up routes that should go before the .verify function. Ive used jwt many times but never had tried using routes before it.
Here is my routes files
var express = require('express');
var router = express.Router();
var usersController = require('../controllers').users;
var jwt = require('jsonwebtoken');
router.post('/signup', function(req,res,next) {
return usersController.signup(req,res);
});
router.post('/signin', function(req,res,next) {
return usersController.signin(req,res);
});
router.post('/social-signin', function(req,res,next) {
return usersController.authSignin(req,res);
});
router.use('/auth', function (req,res,next) {
jwt.verify(req.query.token, 'secret', function (err, decoded) {
if (err) {
return res.status(401).json({
title: 'You are not authorized to do that',
error: "Please sign out and sign back in"
})
}
});
next();
});
router.get('/auth', function(req,res){
return usersController.getUser(req, res);
});
router.patch('/auth/update/:userId', function(req,res) {
return usersController.update(req,res);
});
router.delete('/auth/delete', function(req,res,next) {
return usersController.destroy(req,res);
});
module.exports = router;
Im receiving this error when doing a GET request for getUser.
HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "Unauthorized", url: "http://localhost:3000/user/auth?token=eyJhbGciOiJI…3Njd9.FE3sYhOSFhfhnxkACKSmclcHEWKVhpItuAMqBl-A-5w", ok: false, …}
error
:
{title: "You are not authorized to do that", error: "Please sign out and sign back in"}
headers
:
HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message
I know its probably simple but I just have no idea.
*** Here is the code for getUser
getUser: function getUser(req, res) {
var decoded = jwt.decode(req.query.token);
return User.findOne({
where: {
id: decoded.user.id
}
}).then(function(user){
return res.status(200).json({
title: "User found",
obj: user
});
}).catch(function(error) {
return res.status(400).json({
title: 'There was an error getting user!',
error: error
});
});
},
In your auth, try:
router.use('/auth', function (req,res,next) {
jwt.verify(req.query.token, 'secret', function (err, decoded) {
if (err) {
return next(new Error('You are not authorized to do that'));
}
});
next();
});
This is still an issue
Since your getUser returns a Promise, and you are just returning that from your route. I believe you want to wait on the result of the Promise, before returning from your route.