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}已注册`)
|
|
|
|
|
}
|
|
|
|
|
const verificationCode = this.generateRandomNum()
|
|
|
|
|
const registerToken = this.jwtService.sign(
|
|
|
|
|
{ email, scene },
|
|
|
|
|
{
|
|
|
|
|
secret: this.secureConfig.jwt_access_secret + verificationCode + scene,
|
|
|
|
|
expiresIn: '30min',
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
await this.mailerService.sendMail({
|
|
|
|
|
to: email,
|
|
|
|
|
subject: '注册qiuxu.site',
|
|
|
|
|
html: `您正在注册qiuxu.site,验证码为 <strong>${verificationCode}</strong>,30分钟内有效`,
|
|
|
|
|
})
|
|
|
|
|
return { registerToken, verificationCode }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private generateRandomNum() {
|
|
|
|
|
return Math.floor(Math.random() * 899999 + 100000)
|
|
|
|
|
}
|
2023-02-21 16:31:45 +08:00
|
|
|
|
}
|