gpt4 book ai didi

typescript - 如何使用 typescript 和 bcrypt 在 sequelize 模型中添加方法?

转载 作者:行者123 更新时间:2023-12-03 22:30:13 25 4
gpt4 key购买 nike

我正在用 typescript 创建一个项目,但在使用 bcrypt 和 sequelize 时遇到了麻烦。
为了加密密码,我输入了以下代码:

import Sequelize from "sequelize";
import { sequelize } from "../dbpostgredatabase";
import bcrypt from "bcrypt";

export const User = sequelize.define(
"User",
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
name: {
type: Sequelize.STRING,
allowNull: false,
},

password: {
type: Sequelize.STRING,
allowNull: false,
set(value: string) {
const hash = bcrypt.hashSync(value, 8);
this.setDataValue("password", hash);
},
},

lastname: {
type: Sequelize.STRING,
allowNull: false,
},
email: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
},
date: {
type: Sequelize.DATE,
allowNull: false,
},
admin: {
type: Sequelize.BOOLEAN,
defaultValue: false,
},
},

{
timestamps: false,
createdAt: false,
updatedAt: false,
}
);

export default User;
我需要那个哈希值,但我现在不知道如何获取它,我只需要一种方法来比较密码

最佳答案

import Sequelize from "sequelize";
import { sequelize } from "../dbpostgredatabase";
import bcrypt from "bcrypt";

export const User = sequelize.define(
"User",
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
name: {
type: Sequelize.STRING,
allowNull: false,
},

password: {
type: Sequelize.STRING,
allowNull: false,
set(value: string) {
const hash = bcrypt.hashSync(value, 8);
this.setDataValue("password", hash);
},
},

lastname: {
type: Sequelize.STRING,
allowNull: false,
},
email: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
},
date: {
type: Sequelize.DATE,
allowNull: false,
},
admin: {
type: Sequelize.BOOLEAN,
defaultValue: false,
},
},

{
timestamps: false,
createdAt: false,
updatedAt: false,
}
);

// add static method here
User.hashPassword = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
}

User.isValidPassword = function(password, hash) {
return bcrypt.compareSync(hash, password);
}

export default User;

关于typescript - 如何使用 typescript 和 bcrypt 在 sequelize 模型中添加方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67694882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com