'Cannot destructure property '_id' of 'req.user' as it is undefined
Doesn't work the request (below) as needed, drops out into an error:
app.get('/protected', auth.isAuthenticated(User), function(req, res) {
res.send('Hoooora! Authentificated!');
});
The isAuthenticated function is called from the auth.js file:
auth.js:
const SECRET = 'secret-message';
const jwt = require('jsonwebtoken');
const { expressjwt: expressJwt } = require('express-jwt');
const compose = require('composable-middleware');
function sign(user) {
return jwt.sign({
_id: user._id,
}, SECRET, {
expiresIn: 60 * 60
});
}
function sendUnauthorized(req, res) {
console.log(req.headers.authorization);
console.log(req.user);
res.status(401).json ({ message: 'Unathorized' });
};
const validateJwt = expressJwt({
secret: SECRET,
algorithms: ['HS256'],
fail: sendUnauthorized,
getToken(req){
if(req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
return req.headers.authorization.split(' ')[1];
} else if (req.query && req.query.access_token) {
return req.query.access_token;
}
return null;
}
});
function isAuthenticated(User) {
console.log('isAuthenticated is called');
return compose()
.use(validateJwt)
.use((req, res, next) => {
// Attach user to request
const { _id } = req.user;
console.log(_id + req.user);
User.findById(_id, function(err, user) {
if (err) return next(err);
if (!user) return sendUnauthorized(req, res);
req.user = user;
console.log('Successfuly verified user by token: ');
next();
});
});
};
module.exports = {
sign,
sendUnauthorized,
isAuthenticated,
};
I get an error when the isAuthenticated function runs. And I don't figure out how to fix it:
"error":{"message":"Cannot destructure property '_id' of 'req.user' as it is undefined."
There is a suspicion that the body-parser or express is not working. Although I did yarn add body-parser and yarn add express. In the index.js file code I also added the following:
const express = require('express');
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
