29. 使用 bcryptjs 加密

2024-11-07  本文已影响0人  求墨者
$ npm install --save bcryptjs
'use strict';
const {
  Model
} = require('sequelize');
const bcryptjs = require('bcryptjs');
module.exports = (sequelize, DataTypes) => {
  class User extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
  }
  User.init({
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notNull: { msg: "必须填写" },
        notEmpty: { msg: "不能为空字符串" },
        isEmail: { msg: "格式不正确" },
        async isUnique(value) {
          const user = await User.findOne({ where: { email: value } })
          if (user) {
            throw new Error("邮箱已存在");
          }
        }
      }
    },
    username: DataTypes.STRING,
    password: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notNull: { msg: '密码必须填写' },
        notEmpty: { msg: '密码不能为空字符串' }
      },
      set(value) {
        if (value.length >= 6 && value <= 45) {
          this.setDataValue('password', bcryptjs.hashSync(value, 10))
        } else {
          throw new Error("密码长度为6~45");
        }
      }
    },
    nickname: DataTypes.STRING,
    sex: DataTypes.TINYINT,
    company: DataTypes.STRING,
    introduce: DataTypes.TEXT,
    role: DataTypes.TINYINT,
    avatar: DataTypes.STRING
  }, {
    sequelize,
    modelName: 'User',
  });
  return User;
};
上一篇 下一篇

猜你喜欢

热点阅读