merge password service into auth service

This commit is contained in:
秦秋旭 2023-02-22 09:43:13 +08:00
parent dfa91f8e7a
commit c4f6e168e5
3 changed files with 5 additions and 42 deletions

View File

@ -1,19 +1,12 @@
import { Module } from '@nestjs/common'
import { AuthService } from './auth.service'
import { AuthController } from './auth.controller'
import { PasswordService } from './password.service'
import { JwtService } from '@nestjs/jwt'
import { JwtStrategy } from './strategies/jwt.strategy'
import { EmailService } from 'src/email/email.service'
@Module({
controllers: [AuthController],
providers: [
AuthService,
JwtService,
JwtStrategy,
PasswordService,
EmailService,
],
providers: [AuthService, JwtService, JwtStrategy, EmailService],
})
export class AuthModule {}

View File

@ -4,7 +4,7 @@ import {
ForbiddenException,
UnauthorizedException,
} from '@nestjs/common'
import { PasswordService } from './password.service'
import * as bcrypt from 'bcrypt'
import { PrismaService } from 'nestjs-prisma'
import { Token, TokenPayload } from './dto/token.dto'
import { JwtService } from '@nestjs/jwt'
@ -16,7 +16,6 @@ import { EmailService } from 'src/email/email.service'
@Injectable()
export class AuthService {
constructor(
private passwordService: PasswordService,
private jwtService: JwtService,
private prismaService: PrismaService,
private emailService: EmailService,
@ -41,8 +40,9 @@ export class AuthService {
throw new ForbiddenException('请输入正确的邮箱')
}
const hashedPassword = await this.passwordService.hashPassword(
const hashedPassword = await bcrypt.hash(
userToCreate.password,
this.secureConfig.bcryptSaltOrRound,
)
const user = await this.prismaService.user.create({
data: {
@ -59,10 +59,7 @@ export class AuthService {
where: { email },
})
const passwordValid = await this.passwordService.validatePassword(
password,
user.password,
)
const passwordValid = await bcrypt.compare(password, user.password)
if (!passwordValid) {
throw new ForbiddenException('Invalid password')

View File

@ -1,27 +0,0 @@
import { Inject, Injectable } from '@nestjs/common'
import { securityConfig, SecurityConfig } from 'src/common/configs'
import { hash, compare } from 'bcrypt'
@Injectable()
export class PasswordService {
constructor(
@Inject(securityConfig.KEY)
private secureConfig: SecurityConfig,
) {}
get bcryptSaltRounds(): string | number {
const saltOrRounds = this.secureConfig.bcryptSaltOrRound
return Number.isInteger(Number(saltOrRounds))
? Number(saltOrRounds)
: saltOrRounds
}
validatePassword(password: string, hashedPassword: string) {
return compare(password, hashedPassword)
}
hashPassword(password: string) {
return hash(password, this.bcryptSaltRounds)
}
}