2023-02-21 23:15:40 +08:00
|
|
|
|
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'
|
2023-02-21 23:15:40 +08:00
|
|
|
|
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 {
|
2023-02-21 23:15:40 +08:00
|
|
|
|
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',
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
}
|
2023-02-21 23:15:40 +08:00
|
|
|
|
|
|
|
|
|
async getRegisterToken(email: string, scene: EmailScene) {
|
|
|
|
|
const user = await this.prismaService.user.findUnique({ where: { email } })
|
|
|
|
|
if (user) {
|
|
|
|
|
throw new ConflictException(`邮箱${email}已注册`)
|
|
|
|
|
}
|
2023-02-22 10:41:01 +08:00
|
|
|
|
const verificationCode = this.generateVerificationCode()
|
2023-02-21 23:15:40 +08:00
|
|
|
|
const registerToken = this.jwtService.sign(
|
|
|
|
|
{ email, scene },
|
2023-02-22 01:09:26 +08:00
|
|
|
|
{ secret: this.getEmailJwtSecret(verificationCode, scene) },
|
2023-02-21 23:15:40 +08:00
|
|
|
|
)
|
|
|
|
|
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
|
2023-02-21 23:15:40 +08:00
|
|
|
|
}
|
|
|
|
|
|
2023-02-22 10:41:01 +08:00
|
|
|
|
private generateVerificationCode() {
|
2023-02-22 01:09:26 +08:00
|
|
|
|
return Math.floor(Math.random() * 899999 + 100000).toString()
|
2023-02-21 23:15:40 +08:00
|
|
|
|
}
|
2023-02-21 16:31:45 +08:00
|
|
|
|
}
|