1

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:

enter image description here

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!

1 Answer 1

1

You can try to return

{ token: { token }, user: { id: user.id, role: user.role } }

EDIT: From the comments, it seems that the object which is resolved from this function is assigned to the "token" property of some other object where the login function is used. You can verify the code from where you're calling the login function.

Sign up to request clarification or add additional context in comments.

5 Comments

It's now returning a token object that holds both the token and the user objects inside: { "token": { "token": { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZ...." }, "user": { "id": 4, "role": "medecin" } } }
Can you test it by returning an empty object? @Kaisama
It indeed returns an empty object: "token": {}
It means there's a problem outside this function. The object which is resolved from here is assigned to the "token" property of the outer object
I'll try to find the issue, thanks man!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.