I am trying to set up an user level authentication using node.js, so I go and do npm install -g jsonwebtoken --save
. However, I run into problems when I use require('jsonwebtoken');
and try to compile my code, it gives me the error described above in the title. Now, for some reason, when I uninstall the JWT and try to run my code without it, it compiles, but obviously it doesn't work. I tried re-installing it, still no success.
My npm --version
:
6.3.0
node --version
:
v11.1.0
npm install -g jsonwebtoken --save
code:
'use strict';
require('jsonwebtoken');
exports.generateToken = async (data) => {
return jwt.sign(data, global.SALT_KEY, { expiresIn: '1d' });
}
exports.decodeToken = async (token) => {
var data = await jwt.verify(token, global.SALT_KEY);
return data;
}
exports.authorize = function (req, res, next) {
var token = req.body.token || req.query.token || req.headers['x-access-token'];
if (!token) {
res.status(401).json({
message: 'Acesso Restrito'
});
} else {
jwt.verify(token, global.SALT_KEY, function (error, decoded) {
if (error) {
res.status(401).json({
message: 'Token Inválido'
});
} else {
next();
}
});
}
};
exports.isAdmin = function (req, res, next) {
var token = req.body.token || req.query.token || req.headers['x-access-token'];
if (!token) {
res.status(401).json({
message: 'Token Inválido'
});
} else {
jwt.verify(token, global.SALT_KEY, function (error, decoded) {
if (error) {
res.status(401).json({
message: 'Token Inválido'
});
} else {
if (decoded.roles.includes('admin')) {
next();
} else {
res.status(403).json({
message: 'Esta funcionalidade é restrita para administradores'
});
}
}
});
}
};
Instead of installing it globally with the -g
tag, just install it locally in your current working directory. Just do:
npm install jsonwebtoken
This is because you can not directly require
a globally installed package in your code.