代码之家  ›  专栏  ›  技术社区  ›  merko

NestJS哈希密码

  •  0
  • merko  · 技术社区  · 5 年前

    我正在尝试散列用户实体文件中的密码,我从另一个项目中复制了代码,该代码在该项目上有效,但在这个项目上无效。

    在实体中:

     @Column()
     password: string;
    
      @BeforeInsert()
      async hashPassword() {
        this.password = 'hashed password';
      }
    

    async create(user: DeepPartial<User>) {
        const newUser = this.userRepository.create(user);
        return this.userRepository.save(newUser);
      }
    

    它创建一个用户,但密码不是散列的。

    0 回复  |  直到 5 年前
        1
  •  0
  •   slyDog    5 年前

    如果您使用的是Sequelize ORM,那么我这样做的方式是在初始化Sequelize模型之后返回到数据库提供者并添加它。

        export const databaseProviders = [
        {
            provide: ioc.sequelizeProvider,
            useFactory: async () => {
                const sequelize = new Sequelize({
                    dialect: 'mysql',
                    host: databaseConstants.host,
                    port: databaseConstants.port,
                    username: databaseConstants.username,
                    password: databaseConstants.password,
                    database: databaseConstants.database,
                });
                sequelize.addModels([Profile]);
                await sequelize.sync();
    
                Profile.beforeSave((profile, options) => {
                    const hashPassword = crypto.createHmac('sha256', profile.password).digest('hex');
                    profile.password = hashPassword;
                });
    
                return sequelize;
            },
        },
    ];