【发布时间】:2020-03-16 23:58:10
【问题描述】:
我在服务器上进行授权和用户注册。在搜索中,我找到了一个小指南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);
}
我会在哪里出错,现在为什么密码以明文形式存储?我几乎完成了在写入数据库之前完成的文档和功能,但我知道它不起作用。
【问题讨论】:
-
我猜这是因为你的
@BeforeInsert()函数是异步的。也许您可以尝试使用hashSync使该功能同步。 -
@fyelci 我也尝试这样做,但没有帮助。我遵循了另一条指令,这样的问题并没有发生在我身上。上述说明的作者在某个地方弄错了,但我找不到。
标签: nestjs typeorm password-hash