How do I add routes before jsonwebtoken? - json

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.

Related

Node.js - CRUD API multi delete ID's from SQL

I have small project with ReactJS + NodeJS + mySQL.
I can't create-receive correct request for multi delete by IDs.
This how I sent request from React to Node ==>
const deleteProductsByIds = () => {
let ids = [];
stateProducts.forEach((d) => {
if (d.select) {
ids.push(d.id);
}
});
axios
.delete(`http://localhost:5000/products/${ids}`)
.then((data) => {
console.log(data);
getProducts();
})
.catch((err) => alert(err));
};
this how I receive request in Node(sequelize)
router.delete('/:ids', deleteProducts);
export const deleteProducts = async (req, res) => {
try {
await Product.destroy({
where: {
id: []
}
});
res.json({
"message": "ProductS Deleted"
});
} catch (error) {
res.json({ message: error.message });
}
in logs I have this data and by message everything fine, but products(301,302,303,304) not deleted.
config: {url: 'http://localhost:5000/products/301,302,303,304',
method: 'delete', headers: {…},
transformRequest: Array(1), transformResponse: Array(1), …}
data: {message: 'ProductS Deleted'}
I try
where: {
id: req.params.ids
}
but ids value undefind
also I try:
const ids = req.params
try {
await Product.destroy({
where: {
id: ids
}
});
message: "Invalid value { ids: '301,302,303,304' }"}
but receive error message.
usual delete request by ID working without any problem.
For example:
export const deleteProduct = async (req, res) => {
try {
await Product.destroy({
where: {
id: req.params.id
}
});
res.json({
"message": "Product Deleted"
});
} catch (error) {
res.json({ message: error.message });
}
}
Please help me, because I can't find so much information about multi delete request with React-Node-mySQL.

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

Cannot read properties of undefined in Nodejs

I'm trying to do a sample register without JWT using MVC in nodejs, express and mysql so when I run my code and I have an error :
TypeError: Cannot read properties of undefined (reading 'firstName') at exports.register
here is my code :
AuthController
const AuthModel = require('../models/Auth')
// Create and Save a new User
exports.register = (req, res) => {
// Validate request
if (!req.body) {
res.status(400).send({
message: "Content can not be empty!"
});
}
// Create user
const user = new AuthModel({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: req.body.password
});
// Save user in the database
AuthModel.createUser(user, (err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Some error occurred while registring."
});
else res.send(data);
});
};
AuthModel
const AuthModel = function(table){
this.firstName = table.firstName;
this.lastName = table.lastName;
this.email = table.email;
this.password = table.password;
}
AuthModel.createUser = ( newUser, result ) =>{
db.query("INSERT INTO users SET ?", newUser, (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
console.log("User are registed: ", { id: res.insertId, ...newUser });
result(null, { id: res.insertId, ...newUser });
});
};
It seems to me as if the req.body is undefined. I think you might need something like body-parser, which has been added into the core of Express starting with version 4.
Try adding this middleware to your entrypoint: app.use(express.json());
See more here: http://expressjs.com/en/api.html#express.json
In your exports.register, you .send() if the body is undefined. That doesn't mean the rest of the code won't be executed.
Replace:
res.status(400).send({
message: "Content can not be empty!"
});
by
return res.status(400).send({
message: "Content can not be empty!"
});

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

Ionic gives error undefined is not an object (evaluating '_co.user.username') when decoding the login user token

This is part of the error message that I am getting:
[Error] ERROR – TypeError: undefined is not an object (evaluating '_co.user.username') TypeError: undefined is not an object (evaluating '_co.user.username')(anonymous function)checkAndUpdateView — core.js:44...
My login process works fine and data of the user is gotten fine, on ionic serve version of my app, but on ios I can see that error message, like json encoding doesn't work fine or something. Why is the JSON working fine on website, but not on the app? Here is content of TokenService :
constructor(private cookieService: CookieService) {}
setToken(token) {
this.cookieService.set("chat_token", token);
}
getToken() {
return this.cookieService.get("chat_token");
}
deleteToken() {
this.cookieService.delete("chat_token");
}
getPayload() {
const token = this.getToken();
let payload;
if (token) {
payload = token.split(".")[1];
payload = JSON.parse(window.atob(payload));
}
return payload.data;
}
and this is the loginUser function in LoginComponent , that is triggered on logging in:
loginUser() {
this.showSpinner = true;
this.authService.loginUser(this.loginForm.value).subscribe(
data => {
this.tokenService.setToken(data.token);
localStorage.setItem("currentUser", JSON.stringify(data));
this.loginForm.reset();
setTimeout(() => {
this.router.navigate(["/streams"]);
}, 200);
},
err => {
this.showSpinner = false;
if (err.error.message) {
this.errorMessage = err.error.message;
}
}
);
}
Now, the server side, I have this rout in routes/ directory, in node express in file authRoutes.js:
router.post('/login', AuthCtrl.LoginUser);
And then I have this in routes/ directory, in file userRoutes.js:
const express = require('express');
const router = express.Router();
const UserCtrl = require('../controllers/users');
const AuthHelper = require('../Helpers/AuthHelper');
router.get('/users', AuthHelper.VerifyToken, UserCtrl.GetAllUsers);
router.get('/user/:id', AuthHelper.VerifyToken, UserCtrl.GetUser);
router.get(
'/username/:username',
AuthHelper.VerifyToken,
UserCtrl.GetUserByName
);
router.post('/user/view-profile', AuthHelper.VerifyToken, UserCtrl.ProfileView);
router.post(
'/change-password',
AuthHelper.VerifyToken,
UserCtrl.ChangePassword
);
module.exports = router;
This is the part of controller auth.js on node server side:
async LoginUser(req, res) {
if (!req.body.username || !req.body.password) {
return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ message: "No empty fields allowed" });
}
await User.findOne({ username: Helpers.firstUpper(req.body.username) })
.then(user => {
if (!user) {
return res.status(HttpStatus.NOT_FOUND).json({ message: "Username not found" });
}
return bcrypt.compare(req.body.password, user.password).then(result => {
if (!result) {
return res
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.json({ message: "Password is incorrect" });
}
const token = jwt.sign({ data: user }, dbConfig.secret, {
expiresIn: "5h"
});
res.cookie("auth", token);
return res.status(HttpStatus.OK).json({ message: "Login successful", user, token });
});
})
.catch(err => {
console.log("Error is:");
console.log(err);
return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ message: "Error occured" });
});
}
I resolved the issue by transferring all the stored data from CookieService, which is the main culprit of the error, to a localStorage. Just instead of storing payload and that cookie in CookieService, just transferred it to localStorage, and I didn't have any more problems. Seems like, the simpler - the better.