68 lines
1.9 KiB
TypeScript
68 lines
1.9 KiB
TypeScript
import {
|
|
Inject,
|
|
Injectable,
|
|
BadRequestException,
|
|
UnauthorizedException,
|
|
} from '@nestjs/common'
|
|
import { PasswordService } from 'src/users/password.service'
|
|
import { Token, TokenPayload } from './dto/token.dto'
|
|
import { JwtService } from '@nestjs/jwt'
|
|
import { securityConfig, SecurityConfig } from 'src/common/configs'
|
|
import { UsersService } from 'src/users/users.service'
|
|
import { CreateUserDto } from 'src/users/dto/create-user.dto'
|
|
@Injectable()
|
|
export class AuthService {
|
|
constructor(
|
|
private passwordService: PasswordService,
|
|
private jwtService: JwtService,
|
|
private userService: UsersService,
|
|
@Inject(securityConfig.KEY)
|
|
private secureConfig: SecurityConfig,
|
|
) {}
|
|
|
|
async register(payload: CreateUserDto) {
|
|
const user = await this.userService.createUser(payload)
|
|
return this.generateTokens({ userId: user.id })
|
|
}
|
|
|
|
async login(email: string, password: string) {
|
|
const user = await this.userService.findUser({ email })
|
|
|
|
const passwordValid = await this.passwordService.validatePassword(
|
|
password,
|
|
user.password,
|
|
)
|
|
|
|
if (!passwordValid) {
|
|
throw new BadRequestException('Invalid password')
|
|
}
|
|
|
|
return this.generateTokens({ userId: user.id })
|
|
}
|
|
|
|
async refreshToken(token: string) {
|
|
try {
|
|
const { userId } = this.jwtService.verify(token, {
|
|
secret: this.secureConfig.jwt_refresh_secret,
|
|
})
|
|
return this.generateTokens({ userId })
|
|
} catch (e) {
|
|
console.error(e)
|
|
throw new UnauthorizedException(e.message)
|
|
}
|
|
}
|
|
|
|
private generateTokens(payload: TokenPayload): Token {
|
|
const accessToken = this.jwtService.sign(payload, {
|
|
secret: this.secureConfig.jwt_access_secret,
|
|
expiresIn: this.secureConfig.expiresIn,
|
|
})
|
|
const refreshToken = this.jwtService.sign(payload, {
|
|
secret: this.secureConfig.jwt_refresh_secret,
|
|
expiresIn: this.secureConfig.refreshIn,
|
|
})
|
|
|
|
return { accessToken, refreshToken }
|
|
}
|
|
}
|