0
votes

am trying to do login with graphql, i want to first of all check if the email exist in the database, then if the email exist, then i will compare the password with the bcrypt hash in the password, if it returns true, then i will update the token in the users table in the database, but when i tested it with this

mutation {
  loginUser(user: {email: "[email protected]", password: "1345968"}) {
    password
  }
}

it returned this instead of te token in the database

mutation {
  loginUser(user: {email: "[email protected]", password: "1345968"}) {
    token
  }
}

here is my code

import models from '../../../models/index.js';
import User from '../../types/user.js';
import UserInput from '../../inputs/user.js';
const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')
require('dotenv').config()
const fs = require('fs');
const path = require('path');

var privateKey = fs.readFileSync(path.join(__dirname, '../../key/private.key'), 'utf8');
export default {
    type: User,
    args: {
        user: {
            type: UserInput
        }
    },
    resolve (_,args) {
        return models.user.findOne({
            where: {email: args.user.email}  
        }).then((fUser)=> {
            bcrypt.compare(args.user.password, fUser.password, function (err, res) {
                if (res) {
                    return models.user.findById(fUser.id).then((user) => {
                        return user.update({ token: jwt.sign({id:fUser.id, role:fUser.role, email:fUser.email}, privateKey, { expiresIn: '1h' }) });
                    });
                } else {
                  console.log(err+" error")
                }
            })
        });
    }
};

pls ow can i make it return the token

1

1 Answers

0
votes

Try using findByIdAndUpdate with {new: true} for updated document. So your code will be something like this

return models.user.findOne({
        where: {email: args.user.email}  
    }).then((fUser)=> {
        bcrypt.compare(args.user.password, fUser.password, function (err, res) {
            if (res) {
                return models.user.findByIdAndUpdate(fUser.id, {
                  $set: {
                    token: jwt.sign(
                      { id:fUser.id, role:fUser.role, email:fUser.email },
                      privateKey,
                      { expiresIn: '1h' }
                   )}}, { new: true })

            } else {
              console.log(err+" error")
            }
        })
    });