我在服务器上进行授权和用户注册。在搜索中,我找到了一个小指南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);
}
我在哪里可以出错,现在为什么密码以明文形式存储?在写数据库之前,我几乎做了文档和完成的功能,但是我知道它不起作用。
答案 0 :(得分:1)
BeforeInsert是一个实例级方法,您需要一个实际的User实例才能调用它(如果没有它,则不能引用this.password)
您可以尝试执行类似的操作(如果您不想在db中存储纯密码):
async create(user: UserEntity): Promise<UserEntity> {
user.password = await hash(user.password, 10);
return await this.userRepository.save(user);
}