66 lines
1.9 KiB
TypeScript
66 lines
1.9 KiB
TypeScript
import { PrismaService } from '@/src/core/prisma/prisma.service'
|
|
import { VerificationInput } from '@/src/module/auth/verification/inputs/verification.input'
|
|
import { MailService } from '@/src/module/libs/mail/mail.service'
|
|
import { generateToken } from '@/src/shared/util/generate-token.util'
|
|
import { getSessionMetadata } from '@/src/shared/util/session-metadata.util'
|
|
import { saveSession } from '@/src/shared/util/session.util'
|
|
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'
|
|
import { TokenType, User } from '@prisma/generated'
|
|
import { Request } from 'express'
|
|
|
|
@Injectable()
|
|
export class VerificationService {
|
|
constructor(
|
|
private readonly prismaService: PrismaService,
|
|
private readonly mailService: MailService,
|
|
) {
|
|
}
|
|
|
|
public async verify(req: Request, input: VerificationInput, userAgent: string) {
|
|
const { token } = input
|
|
const existingToken = await this.prismaService.token.findUnique({
|
|
where: { token, type: TokenType.EMAIL_VERIFY },
|
|
})
|
|
|
|
if (!existingToken) {
|
|
throw new NotFoundException('Токен не найден')
|
|
}
|
|
|
|
const hasExpired = new Date(existingToken.expiresIn) < new Date()
|
|
|
|
if (hasExpired) {
|
|
throw new BadRequestException('Токен истек')
|
|
}
|
|
|
|
const user = await this.prismaService.user.update({
|
|
where: {
|
|
id: existingToken.userId!, // todo fixme
|
|
},
|
|
data: {
|
|
isEmailVerified: true,
|
|
},
|
|
})
|
|
|
|
await this.prismaService.token.delete({
|
|
where: {
|
|
id: existingToken.id,
|
|
type: TokenType.EMAIL_VERIFY,
|
|
},
|
|
})
|
|
|
|
return saveSession(req, user, getSessionMetadata(req, userAgent))
|
|
}
|
|
|
|
public async sendVerificationToken(user: User) {
|
|
const verificationToken = await generateToken(
|
|
this.prismaService,
|
|
user,
|
|
TokenType.EMAIL_VERIFY,
|
|
)
|
|
|
|
await this.mailService.sendVerificationToken(user.email, verificationToken.token);
|
|
|
|
return true
|
|
}
|
|
}
|