-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #9 from anasabbal/develop
Develop
- Loading branch information
Showing
11 changed files
with
268 additions
and
190 deletions.
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'; | ||
import * as dotenv from 'dotenv'; | ||
import { EmailVerificationRepository } from '../repository/email.repository'; | ||
import { EmailUtils } from './utils'; | ||
import { VerificationToken } from '../models/email.confirmation'; | ||
|
||
dotenv.config(); | ||
|
||
@Injectable() | ||
export class EmailService { | ||
private readonly logger = new Logger(EmailService.name); | ||
|
||
constructor( | ||
private readonly emailRepository: EmailVerificationRepository, | ||
private readonly emailUtils: EmailUtils, | ||
) {} | ||
|
||
async createEmailToken(email: string): Promise<boolean> { | ||
try { | ||
const emailVerification = await this.emailRepository.findByEmail(email); | ||
|
||
if (emailVerification && this.isRecentlySent(emailVerification.timestamp)) { | ||
throw new HttpException('LOGIN.EMAIL_SENT_RECENTLY', HttpStatus.INTERNAL_SERVER_ERROR); | ||
} else { | ||
await this.emailRepository.upsertVerificationToken(email, this.generateEmailToken(), new Date()); | ||
this.logger.debug(`Email token created for ${email}`); | ||
return true; | ||
} | ||
} catch (error) { | ||
this.logger.error(`Error creating email token: ${error.message}`); | ||
throw error; | ||
} | ||
} | ||
|
||
async sendEmailVerification(email: string): Promise<boolean> { | ||
try { | ||
const model = await this.emailRepository.findByEmail(email); | ||
if (!model || !model.token) { | ||
throw new HttpException('REGISTER.USER_NOT_REGISTERED', HttpStatus.FORBIDDEN); | ||
} | ||
this.logger.debug(`Email Token: ${model.token}`); | ||
|
||
const sent = await this.emailUtils.sendVerificationEmail(email, model.token); | ||
if (sent) { | ||
this.logger.debug(`Email verification sent to ${email}`); | ||
} else { | ||
this.logger.warn(`Failed to send email verification to ${email}`); | ||
} | ||
return sent; | ||
} catch (error) { | ||
this.logger.error(`Error sending email verification: ${error.message}`); | ||
throw error; | ||
} | ||
} | ||
|
||
private isRecentlySent(timestamp: Date): boolean { | ||
if (!timestamp) { | ||
return false; | ||
} | ||
const minutesElapsed = (new Date().getTime() - new Date(timestamp).getTime()) / 60000; | ||
return minutesElapsed < 15; | ||
} | ||
|
||
private generateEmailToken(): string { | ||
return (Math.floor(Math.random() * 9000000) + 1000000).toString(); | ||
} | ||
|
||
async findEmailConfirmationWithToken(token: string): Promise<VerificationToken | null> { | ||
try { | ||
return await this.emailRepository.findByToken(token); | ||
} catch (error) { | ||
this.logger.error(`Error finding email confirmation: ${error.message}`); | ||
throw error; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
import nodemailer from 'nodemailer'; | ||
import * as dotenv from 'dotenv'; | ||
|
||
dotenv.config(); | ||
|
||
class NodemailerTransporter { | ||
private static instance: nodemailer.Transporter | null = null; | ||
|
||
private constructor() {} // Prevents instantiation | ||
|
||
static getInstance(): nodemailer.Transporter { | ||
if (!NodemailerTransporter.instance) { | ||
NodemailerTransporter.instance = nodemailer.createTransport({ | ||
host: process.env.EMAIL_HOST, | ||
port: parseInt(process.env.EMAIL_PORT || '0', 10), | ||
secure: process.env.EMAIL_SECURE === 'true', | ||
auth: { | ||
user: process.env.EMAIL_USERNAME, | ||
pass: process.env.EMAIL_PASSWORD, | ||
}, | ||
}); | ||
} | ||
return NodemailerTransporter.instance; | ||
} | ||
} | ||
|
||
export default NodemailerTransporter; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
import * as nodemailer from 'nodemailer'; | ||
import * as dotenv from 'dotenv'; | ||
|
||
dotenv.config(); | ||
|
||
|
||
export class EmailUtils { | ||
private transporter = nodemailer.createTransport({ | ||
host: process.env.EMAIL_HOST, | ||
port: parseInt(process.env.EMAIL_PORT || '0', 10), | ||
secure: process.env.EMAIL_SECURE === 'true', | ||
auth: { | ||
user: process.env.EMAIL_USERNAME, | ||
pass: process.env.EMAIL_PASSWORD, | ||
}, | ||
}); | ||
|
||
async sendVerificationEmail(email: string, emailToken: string): Promise<boolean> { | ||
const mailOptions = { | ||
from: `"Company" <${process.env.COMPANY_EMAIL}>`, | ||
to: email, | ||
subject: 'Verify Email', | ||
text: 'Verify Email', | ||
html: `Hi! <br><br> Thanks for your registration<br><br>` + | ||
`<a href="${process.env.EMAIL_URL}:${process.env.PORT}/auth/verify/${emailToken}">Click here to activate your account</a>`, | ||
}; | ||
|
||
try { | ||
const info = await this.transporter.sendMail(mailOptions); | ||
return true; | ||
} catch (error) { | ||
console.error(`Error sending email: ${error.message}`); | ||
return false; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
import { Injectable } from '@nestjs/common'; | ||
import { InjectModel } from '@nestjs/mongoose'; | ||
import { Model } from 'mongoose'; | ||
import { VerificationToken, VerificationTokenDocument } from '../models/email.confirmation'; | ||
|
||
@Injectable() | ||
export class EmailVerificationRepository { | ||
constructor( | ||
@InjectModel(VerificationToken.name) private readonly verificationTokenModel: Model<VerificationTokenDocument>, | ||
) {} | ||
|
||
async findByEmail(email: string): Promise<VerificationToken | null> { | ||
try { | ||
return await this.verificationTokenModel.findOne({ email }).exec(); | ||
} catch (error) { | ||
throw new Error(`Error finding email verification by email ${email}: ${error.message}`); | ||
} | ||
} | ||
|
||
async findByToken(token: string): Promise<VerificationToken | null> { | ||
try { | ||
return await this.verificationTokenModel.findOne({ token }).exec(); | ||
} catch (error) { | ||
throw new Error(`Error finding email verification by token ${token}: ${error.message}`); | ||
} | ||
} | ||
|
||
async upsertVerificationToken(email: string, token: string, timestamp: Date): Promise<void> { | ||
try { | ||
const filter = { email }; | ||
const update = { token, timestamp }; | ||
const options = { upsert: true, new: true, setDefaultsOnInsert: true }; | ||
await this.verificationTokenModel.findOneAndUpdate(filter, update, options).exec(); | ||
} catch (error) { | ||
throw error; | ||
} | ||
} | ||
|
||
async deleteByEmail(email: string): Promise<void> { | ||
try { | ||
await this.verificationTokenModel.deleteOne({ email }).exec(); | ||
} catch (error) { | ||
throw new Error(`Error deleting email verification for ${email}: ${error.message}`); | ||
} | ||
} | ||
} |
Oops, something went wrong.