2023-02-16 10:40:03 +08:00
|
|
|
import { Injectable, BadRequestException } from '@nestjs/common'
|
|
|
|
import { PasswordService } from 'src/users/password.service'
|
2023-02-16 15:43:38 +08:00
|
|
|
import { Token } from './dto/token.dto'
|
2023-02-16 01:18:55 +08:00
|
|
|
import { JwtService } from '@nestjs/jwt'
|
|
|
|
import { ConfigService } from '@nestjs/config'
|
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,
|
|
|
|
private configService: ConfigService,
|
2023-02-16 10:40:03 +08:00
|
|
|
private userService: UsersService,
|
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
|
|
|
}
|
|
|
|
|
|
|
|
private generateTokens(payload: { userId: string }): Token {
|
|
|
|
const accessToken = this.jwtService.sign(payload, {
|
|
|
|
secret: this.configService.get<string>(
|
|
|
|
'JWT_ACCESS_SECRET',
|
|
|
|
'JWT_ACCESS_SECRET',
|
|
|
|
),
|
|
|
|
expiresIn: '30min',
|
|
|
|
})
|
|
|
|
const refreshToken = this.jwtService.sign(payload, {
|
|
|
|
secret: this.configService.get<string>(
|
|
|
|
'JWT_REFRESH_SECRET',
|
|
|
|
'JWT_REFRESH_SECRET',
|
|
|
|
),
|
|
|
|
expiresIn: '7d',
|
|
|
|
})
|
|
|
|
|
|
|
|
return { accessToken, refreshToken }
|
|
|
|
}
|
|
|
|
}
|