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

75 lines
2.0 KiB
TypeScript
Raw Normal View History

2023-02-17 15:56:35 +08:00
import {
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'
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
}
2023-02-17 15:56:35 +08:00
async refreshToken(token: string) {
try {
const { userId } = this.jwtService.verify(token, {
secret: this.configService.get<string>(
'JWT_REFRESH_SECRET',
'JWT_REFRESH_SECRET',
),
})
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, {
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 }
}
}