nest-project/src/auth/auth.service.ts

68 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-02-17 15:56:35 +08:00
import {
2023-02-21 11:13:21 +08:00
Inject,
2023-02-17 15:56:35 +08:00
Injectable,
BadRequestException,
UnauthorizedException,
} from '@nestjs/common'
2023-02-16 10:40:03 +08:00
import { PasswordService } from 'src/users/password.service'
import { Token, TokenPayload } from './dto/token.dto'
2023-02-16 01:18:55 +08:00
import { JwtService } from '@nestjs/jwt'
2023-02-21 11:13:21 +08:00
import { securityConfig, SecurityConfig } from 'src/common/configs'
2023-02-16 10:40:03 +08:00
import { UsersService } from 'src/users/users.service'
import { CreateUserDto } from 'src/users/dto/create-user.dto'
2023-02-16 01:18:55 +08:00
@Injectable()
export class AuthService {
constructor(
private passwordService: PasswordService,
private jwtService: JwtService,
2023-02-16 10:40:03 +08:00
private userService: UsersService,
2023-02-21 11:13:21 +08:00
@Inject(securityConfig.KEY)
private secureConfig: SecurityConfig,
2023-02-16 01:18:55 +08:00
) {}
2023-02-16 10:40:03 +08:00
async register(payload: CreateUserDto) {
const user = await this.userService.createUser(payload)
return this.generateTokens({ userId: user.id })
2023-02-16 01:18:55 +08:00
}
2023-02-16 10:40:03 +08:00
async login(email: string, password: string) {
const user = await this.userService.findUser({ email })
2023-02-16 01:18:55 +08:00
const passwordValid = await this.passwordService.validatePassword(
password,
user.password,
)
if (!passwordValid) {
throw new BadRequestException('Invalid password')
}
2023-02-16 10:40:03 +08:00
return this.generateTokens({ userId: user.id })
2023-02-16 01:18:55 +08:00
}
2023-02-17 15:56:35 +08:00
async refreshToken(token: string) {
try {
const { userId } = this.jwtService.verify(token, {
2023-02-21 11:13:21 +08:00
secret: this.secureConfig.jwt_refresh_secret,
2023-02-17 15:56:35 +08:00
})
return this.generateTokens({ userId })
} catch (e) {
console.error(e)
throw new UnauthorizedException(e.message)
}
}
private generateTokens(payload: TokenPayload): Token {
2023-02-16 01:18:55 +08:00
const accessToken = this.jwtService.sign(payload, {
2023-02-21 11:13:21 +08:00
secret: this.secureConfig.jwt_access_secret,
expiresIn: this.secureConfig.expiresIn,
2023-02-16 01:18:55 +08:00
})
const refreshToken = this.jwtService.sign(payload, {
2023-02-21 11:13:21 +08:00
secret: this.secureConfig.jwt_refresh_secret,
expiresIn: this.secureConfig.refreshIn,
2023-02-16 01:18:55 +08:00
})
return { accessToken, refreshToken }
}
}