The people in this group forgive me if the explanation is a little long and meaningless, it's because I'm taking an online course from udemy and the teacher takes a lot to answer so I'll take a step by step from what I'm doing. At first I can save with administrator authentication, however when I am authenticated as an ordinary user I can not make the changes.
This is my source code
See my route in my express project;
api.post('/salvarEvento', md_auth.ensureAuth, EventoController.saveEvento);
When I run in postman the save method I can get success as you can see below.
ButthenImakethefollowingchanges;
Igetencryptedpasswordfromjoaquimaccountandsavedinadminpasswordasyoucanseebelow
Beforethis,
Nowit'slikethis;
AfterthatIcreateafilecalledis_admininthesamefolderthatwasimplementedwithJWTuserauthentication.
'usestrict'exports.isAdmin=function(req,res,next){if(req.user.role!='ROLE_ADMIN'){returnres.status(200).send({mensagem:'Vocênãotemacessoazona',});}next();};
ThenIchangedtheroute.
Beforeitwaslikethis
api.post('/salvarEvento',md_auth.ensureAuth,EventoController.saveEvento);
Thenitwaslikethis;
api.post('/salvarEvento',[md_auth.ensureAuth,md_admin.isAdmin],EventoController.saveEvento);
ThencreatedanewTokenintheloginmethod.
Beforethis,
IranthemethodaccordingtothecourseI'mdoinganditwaslikethis;
ItooktheTokenandputitintheauthorizationofthepostmanandexecutedthesavemethodandseethemessagethatitgave.
1part
Runningthemethod.
It'sfallinghere;
'usestrict'exports.isAdmin=function(req,res,next){if(req.user.role!='ROLE_ADMIN'){returnres.status(200).send({mensagem:'Vocênãotemacessoazona',});}next();};
ItwastobeabletoauthenticatemyselfandIwasabletomakethechangewiththemethod,butIdonotknowwhatishappeningandIneedhelp.
=======================================================================
POSTUPDATE
Whatisthevalueofreq.user?
'usestrict'varjwt=require('jwt-simple');varmoment=require('moment');varsecreto='123';exports.ensureAuth=function(req,res,next){if(!req.headers.authorization){returnres.status(403).send({mensagem:'suasolicitaçãonãofoiatendida,precisaseautenticar'});}vartoken=req.headers.authorization.replace(/['"]+/g, ' ');
try {
var payload = jwt.decode(token, secreto);
if(payload.exp <= moment().unix()) {
return res.status(401).send({
mensagem: 'O token inspirou'
});
}
} catch (ex) {
return res.status(404).send({
mensagem: 'O token não é valido'
});
}
req.user = payload;
next();
}
According to the above code if I was to find the value of req.user I will find this value
req.user = payload;
return res.status(200).send({
mensagem: req.user
});
This value
{
"mensagem": {
"sub": "5afc1283b29c7e9abd8c1e47",
"name": "admin",
"surname": "admin",
"email": "[email protected]",
"iat": 1526993154
}
}
But in the is_admin file it is coming empty;
exports.isAdmin = function(req, res, next){
if (req.user.role != 'ROLE_ADMIN') {
return res.status(200).send({
mensagem: req.user.role
});
}
next();
};
{}
How do I resolve this?