I'm new to node.js and I'm trying to sign in users using an API that I've created. The login API should return the token corresponding to the logged-in user alongside his role. I'm getting a token object as a map of the token itself alongside the role. The following screenshot shows the response:
But it should return:
{
"token": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NCwidXNlcm5hbWUiOiJiYmIiLCJyb2xlIjoibWVkZWNpbiIsImlhdCI6MTY0OTg0NDY0NiwiZXhwIjoxNjQ5OTMxMDQ2fQ.nSwawXpig72t0ySxQNUUFdXT03eC6jmtgQs9jtsbFbk",
},
"user": {
"id": 4,
"role": "medecin"
}
}
Here is my code in which the resolve methods returns both token obj and user obj separately:
const privateKey = "this is a private key dsfdsgfqdsmlkfsdmqlf,kqdmsjdsmjfm"
exports.login=(email, password)=>{
return new Promise((resolve, reject)=>{
db.User.findOne({where: {email:email}}).then(user=>{
if (!user){
reject('Invalid email and password')
}
{
bcrypt.compare(password, user.password).then(same=>{
if(same){
let token = jwt.sign({id: user.id, username: user.username, role:user.role}, privateKey,
{expiresIn:"24h"})
resolve({ token, user: { id: user.id, role: user.role } })
}
else{
reject('Invalid email and password')
}
})
}
})
})
}
Can anyone help me out with this? thanks in advance!
