我的nodejs bcrypt比较无法正常工作

时间:2019-02-17 06:12:42

标签: node.js graphql bcrypt

我正在使用apollo使用节点qraphQl构建一个应用程序,试图创建一个登录页面,但是在注册后又尝试登录,我的bcrypt总是返回false,

在我的用户模型中

import bcrypt from 'bcryptjs';

const user = (sequelize, DataTypes) => {
  const User = sequelize.define('user', {    
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      unique: true,
      primaryKey: true,
      field: 'id'
    },
    fullname: DataTypes.STRING,
    username: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notEmpty: true,
      },
    },
    email: {
      type: DataTypes.STRING,
      allowedNull: false,
      validate: {
        notEmpty: true,
        isEmail: true, 
      }
    },
    password: {
      type: DataTypes.STRING,
      allowedNull: false,
      validate: {
        notEmpty: true,
        len: [7, 42],
      },
    },
    role: { 
      type: DataTypes.ENUM,
      values: ['ADMIN', 'INSTRUCTOR', 'STUDENT'],
      defaultValue: 'STUDENT'
    }
  });

  User.beforeCreate(async user => {
    user.password = await user.generatePasswordHash()
  });
  User.beforeSave(async user => {
    user.password = await user.generatePasswordHash()
  });

  User.prototype.generatePasswordHash = async function() {
    const saltRounds = 10;
    return await bcrypt.hash(this.password, saltRounds)
  };

  User.prototype.validatePassword = async function(password) {
    return await bcrypt.compare(password, this.password);
  };

  User.associate = models => {
    User.hasMany(models.Message, { onDelete: 'CASCADE' });
  };

  User.findByLogin = async login => {
    let user = await User.findOne({
      where: { username: login },
    });

    if (!user) {
      user = await User.findOne({
        where: { email: login },
      });
    }

    return user;
  };

  return User;
};

export default user;

在我的用户解析器中,下面是代码

import { combineResolvers } from 'graphql-resolvers';
import Joi from 'joi'
import { isAuthenticated, isAdmin } from './authorization';
import {SignUp, SignIn} from '../functions/joi'
import {createToken} from '../functions/jwt'

export default {

  Mutation: {
    signUp: async (parent, { username, fullname, email, password, Rpassword}, { models, secret }) => {
      if(password !== Rpassword){
        return new Error('Password did not match')
      }
      var thejoi = { username, fullname, email, password }
      const checkUserEm = await models.User.find({ where: { email: email }})
      if (checkUserEm) {
          return new Error('Email address already Exist')
      }
      const checkUserUs = await models.User.find({ where: { username: username }})
      if (checkUserUs) {
          return new Error('Username already Exist')
      }

      await Joi.validate(thejoi, SignUp, {abortEarly:false})
      const user = await models.User.create({
        username, 
        fullname, 
        email,
        password,
        role:'STUDENT'
      });
      return { token: createToken(user) };
    },
    signIn: async (parent, { login, password }, { models, secret }, ) => {
      var varrh = { password }
      await Joi.validate(varrh, SignIn, {abortEarly:false})
      const user = await models.User.findByLogin(login);

      if (!user) {
        return new Error('No user found with this login credentials.');
      }

      const isValid = await user.validatePassword(password);
      if (!isValid) { 
        return new Error('Invalid password .');
      }

      return { token: createToken(user) };
    }
  },
  User: {
    messages: async (user, args, { models }) => {
      return await models.Message.findAll({
        where: {
          userId: user.id
        }
      });
    },
  },
}

请问我真的很困惑,因为它可以正常工作,我已经搜索过谷歌,但并没有帮助我,请问我该如何解决这个问题

1 个答案:

答案 0 :(得分:1)

generatePasswordHash内,您引用​​的是this,但是您还对beforeCreatebeforeSave钩使用了箭头功能。

两个选项:

  1. 请勿对beforeCreatebeforeSave挂钩使用箭头功能。
User.beforeCreate(async function (user) {
  user.password = await user.generatePasswordHash()
});

User.beforeSave(async function (user) {
  user.password = await user.generatePasswordHash()
});
  1. user提供generatePasswordHash对象,并将this替换为user
User.beforeCreate(async user => {
  user.password = await user.generatePasswordHash(user)
});

User.beforeSave(async user => {
  user.password = await user.generatePasswordHash(user)
});

User.prototype.generatePasswordHash = async function(user) {
    const saltRounds = 10;
    return await bcrypt.hash(user.password, saltRounds)
};