首页 > 解决方案 > 密码以纯文本形式存储在数据库中

问题描述

我在服务器上进行授权和用户注册。在搜索中,我找到了一个小指南https://www.techiediaries.com/nestjs-tutorial-jwt-authentication。跟随他进行了注册和用户授权。我的问题是,在注册过程中,密码以明文形式存储在数据库中。

注册后,密码以明文形式存储。

在此处输入图像描述

控制器和型号与我上面引用的手册中的没有区别。

@Post('login')
async login(@Body() user: UserEntity): Promise<Object> {
    return await this.authService.login(user);
}

@Post('register')
async register(@Body() user: UserEntity): Promise<Object> {
    return await this.authService.register(user);
}
imports: [TypeOrmModule.forFeature([UserEntity])],
providers: [UserService, AuthService],
controllers: [AuthController],

我为自己重写了用户对象。

import { Entity, PrimaryGeneratedColumn, Column, BeforeInsert } from 'typeorm';
import { hash, compare } from 'bcryptjs';

@Entity('users')
export class UserEntity {
    @PrimaryGeneratedColumn() id: number;

    @Column({ type: 'varchar', nullable: false }) firstName: string;

    @Column({ type: 'varchar', nullable: false }) lastName: string;

    @Column({ type: 'varchar', nullable: false }) email: string;

    @Column({ type: 'varchar', nullable: false }) password: string;

    @BeforeInsert()
    async hashPassword(): Promise<void> {
        this.password = await hash(this.password, 10);
    }

    async comparePassword(attempt: string): Promise<boolean> {
        return await compare(attempt, this.password);
    }
}

我还为自己重写了授权服务。

public async login(user: UserEntity) {
    const userData = await this.userService.findByEmail(user.email);
    const result = user.comparePassword(user.password);
    if (!result) {
        return {
            message: 'Password or email is incorrect',
            status: 404,
        };
    }
    return this.getInfo(userData);
}

public async register(user: UserEntity): Promise<Object> {
    const userData = await this.userService.findByEmail(user.email);
    if (userData) {
       return {
            message: 'A user with this email already exists.',
            status: 404,
        };
    }
    const newUser = await this.userService.create(user);
    return this.getInfo(newUser);
}

private async getInfo(userData: UserEntity) {
    const accessToken = this.getAccessToken(userData);
    return {
        accessToken,
        userId: userData.id,
        status: 200,
    };
}

private getAccessToken(userData: UserEntity) {
    return this.jwtService.sign({
        userId: userData.id,
        firstName: userData.firstName,
        lastName: userData.lastName,
        email: userData.email,
    });
}

用户服务也保持不变。

async findByEmail(email: string): Promise<UserEntity> {
    return await this.userRepository.findOne({ where: { email } });
}

async findById(id: number): Promise<UserEntity> {
    return await this.userRepository.findOne({ where: { id } });
}

async create(user: UserEntity): Promise<UserEntity> {
    return await this.userRepository.save(user);
}

我在哪里会出错,现在为什么密码以明文形式存储?我几乎完成了在写入数据库之前完成的文档和功能,但我知道它不起作用。

标签: nestjstypeormpassword-hash

解决方案


根据github问题

BeforeInsert 是一个实例级方法,您需要一个实际的 User 实例才能调用它(如果没有 this,则不能引用 this.password)

您可以尝试执行以下操作(如果您不想将纯密码存储在数据库中):

async create(user: UserEntity): Promise<UserEntity> {
    user.password = await hash(user.password, 10);

    return await this.userRepository.save(user);
}

推荐阅读