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

57 lines
1.9 KiB
TypeScript
Raw Normal View History

import { ConflictException, Inject, Injectable } from '@nestjs/common'
import { securityConfig, SecurityConfig } from 'src/common/configs'
2023-02-21 16:31:45 +08:00
import { MailerService } from '@nestjs-modules/mailer'
import { JwtService } from '@nestjs/jwt'
import { EmailScene } from './dto/email.dto'
import { PrismaService } from 'nestjs-prisma'
2023-02-21 16:31:45 +08:00
@Injectable()
export class EmailService {
constructor(
private prismaService: PrismaService,
private mailerService: MailerService,
private jwtService: JwtService,
@Inject(securityConfig.KEY)
private secureConfig: SecurityConfig,
) {}
2023-02-21 16:31:45 +08:00
async sendEmailTo(email: string) {
return this.mailerService.sendMail({
to: email, // list of receivers
subject: 'Testing Nest Mailermodule with template ✔',
template: 'index', // The `.pug` or `.hbs` extension is appended automatically.
context: {
// Data to be sent to template engine.
code: 'cf1a3f828287',
username: 'john doe',
},
})
}
async getRegisterToken(email: string, scene: EmailScene) {
const user = await this.prismaService.user.findUnique({ where: { email } })
if (user) {
throw new ConflictException(`邮箱${email}已注册`)
}
const verificationCode = this.generateVerificationCode()
const registerToken = this.jwtService.sign(
{ email, scene },
2023-02-22 01:09:26 +08:00
{ secret: this.getEmailJwtSecret(verificationCode, scene) },
)
await this.mailerService.sendMail({
to: email,
subject: '注册qiuxu.site',
html: `您正在注册qiuxu.site验证码为 <strong>${verificationCode}</strong>30分钟内有效`,
})
2023-02-22 01:09:26 +08:00
return registerToken
}
getEmailJwtSecret(verificationCode: string, scene: EmailScene) {
return this.secureConfig.jwt_access_secret + verificationCode + scene
}
private generateVerificationCode() {
2023-02-22 01:09:26 +08:00
return Math.floor(Math.random() * 899999 + 100000).toString()
}
2023-02-21 16:31:45 +08:00
}