|
| 1 | +import { Inject, Injectable } from '@nestjs/common'; |
| 2 | +import { |
| 3 | + IEmailServiceInterface, |
| 4 | + IEmailServiceToken, |
| 5 | +} from '@api/modules/notifications/email/email-service.interface'; |
| 6 | +import { ApiConfigService } from '@api/modules/config/app-config.service'; |
| 7 | + |
| 8 | +export type PasswordRecovery = { |
| 9 | + email: string; |
| 10 | + token: string; |
| 11 | + origin: string; |
| 12 | +}; |
| 13 | + |
| 14 | +@Injectable() |
| 15 | +export class AuthMailer { |
| 16 | + constructor( |
| 17 | + @Inject(IEmailServiceToken) |
| 18 | + private readonly emailService: IEmailServiceInterface, |
| 19 | + private readonly apiConfig: ApiConfigService, |
| 20 | + ) {} |
| 21 | + |
| 22 | + async sendPasswordRecoveryEmail( |
| 23 | + passwordRecovery: PasswordRecovery, |
| 24 | + ): Promise<void> { |
| 25 | + // TODO: Investigate if it's worth using a template engine to generate the email content, the mail service provider allows it |
| 26 | + // TODO: Use a different expiration time, or different secret altogether for password recovery |
| 27 | + |
| 28 | + const { expiresIn } = this.apiConfig.getJWTConfig(); |
| 29 | + |
| 30 | + const resetPasswordUrl = `${passwordRecovery.origin}/auth/forgot-password/${passwordRecovery.token}`; |
| 31 | + |
| 32 | + const htmlContent: string = ` |
| 33 | + <h1>Dear User,</h1> |
| 34 | + <br/> |
| 35 | + <p>We recently received a request to reset your password for your account. If you made this request, please click on the link below to securely change your password:</p> |
| 36 | + <br/> |
| 37 | + <p><a href="${resetPasswordUrl}" target="_blank" rel="noopener noreferrer">Secure Password Reset Link</a></p> |
| 38 | + <br/> |
| 39 | + <p>This link will direct you to our app to create a new password. For security reasons, this link will expire after ${passwordRecoveryTokenExpirationHumanReadable(expiresIn)}.</p> |
| 40 | + <p>If you did not request a password reset, please ignore this email; your password will remain the same.</p> |
| 41 | + <br/> |
| 42 | + <p>Thank you for using the platform. We're committed to ensuring your account's security.</p> |
| 43 | + <p>Best regards.</p>`; |
| 44 | + |
| 45 | + await this.emailService.sendMail({ |
| 46 | + from: 'password-recovery', |
| 47 | + to: passwordRecovery.email, |
| 48 | + subject: 'Recover Password', |
| 49 | + html: htmlContent, |
| 50 | + }); |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +const passwordRecoveryTokenExpirationHumanReadable = ( |
| 55 | + expiration: string, |
| 56 | +): string => { |
| 57 | + const unit = expiration.slice(-1); |
| 58 | + const value = parseInt(expiration.slice(0, -1), 10); |
| 59 | + |
| 60 | + switch (unit) { |
| 61 | + case 'h': |
| 62 | + return `${value} hour${value > 1 ? 's' : ''}`; |
| 63 | + case 'd': |
| 64 | + return `${value} day${value > 1 ? 's' : ''}`; |
| 65 | + default: |
| 66 | + return expiration; |
| 67 | + } |
| 68 | +}; |
0 commit comments