@wikiccu/nest-auth
Version:
A comprehensive authentication package for NestJS applications with Prisma and PostgreSQL
280 lines (262 loc) • 11.8 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.EmailService = void 0;
const common_1 = require("@nestjs/common");
const config_1 = require("@nestjs/config");
const nodemailer = __importStar(require("nodemailer"));
let EmailService = class EmailService {
configService;
transporter;
constructor(configService) {
this.configService = configService;
this.initializeTransporter();
}
initializeTransporter() {
const emailConfig = {
host: this.configService.get('SMTP_HOST'),
port: this.configService.get('SMTP_PORT', 587),
secure: this.configService.get('SMTP_SECURE', false),
auth: {
user: this.configService.get('SMTP_USER'),
pass: this.configService.get('SMTP_PASS'),
},
};
this.transporter = nodemailer.createTransport(emailConfig);
}
async sendEmailVerification(email, token) {
const frontendUrl = this.configService.get('FRONTEND_URL', 'http://localhost:3000');
const verificationUrl = `${frontendUrl}/verify-email?token=${token}`;
const template = this.getEmailVerificationTemplate(verificationUrl);
await this.sendEmail(email, template);
}
async sendPasswordReset(email, token) {
const frontendUrl = this.configService.get('FRONTEND_URL', 'http://localhost:3000');
const resetUrl = `${frontendUrl}/reset-password?token=${token}`;
const template = this.getPasswordResetTemplate(resetUrl);
await this.sendEmail(email, template);
}
async sendWelcomeEmail(email, username) {
const template = this.getWelcomeTemplate(username);
await this.sendEmail(email, template);
}
async sendAccountLockedEmail(email) {
const template = this.getAccountLockedTemplate();
await this.sendEmail(email, template);
}
async sendPasswordChangedEmail(email) {
const template = this.getPasswordChangedTemplate();
await this.sendEmail(email, template);
}
async sendEmail(email, template) {
const fromEmail = this.configService.get('EMAIL_FROM', 'noreply@example.com');
const fromName = this.configService.get('EMAIL_FROM_NAME', 'Authentication Service');
const mailOptions = {
from: `"${fromName}" <${fromEmail}>`,
to: email,
subject: template.subject,
text: template.text,
html: template.html,
};
try {
await this.transporter.sendMail(mailOptions);
}
catch (error) {
console.error('Failed to send email:', error);
throw new Error('Failed to send email');
}
}
getEmailVerificationTemplate(verificationUrl) {
return {
subject: 'Verify Your Email Address',
html: `
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
<h2 style="color: #333;">Welcome to Our Platform!</h2>
<p>Thank you for registering. Please verify your email address by clicking the button below:</p>
<div style="text-align: center; margin: 30px 0;">
<a href="${verificationUrl}"
style="background-color: #007bff; color: white; padding: 12px 24px; text-decoration: none; border-radius: 5px; display: inline-block;">
Verify Email Address
</a>
</div>
<p>If the button doesn't work, you can copy and paste this link into your browser:</p>
<p style="word-break: break-all; color: #666;">${verificationUrl}</p>
<p>This link will expire in 24 hours.</p>
<p>If you didn't create an account, you can safely ignore this email.</p>
</div>
`,
text: `
Welcome to Our Platform!
Thank you for registering. Please verify your email address by visiting this link:
${verificationUrl}
This link will expire in 24 hours.
If you didn't create an account, you can safely ignore this email.
`,
};
}
getPasswordResetTemplate(resetUrl) {
return {
subject: 'Reset Your Password',
html: `
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
<h2 style="color: #333;">Password Reset Request</h2>
<p>You requested to reset your password. Click the button below to create a new password:</p>
<div style="text-align: center; margin: 30px 0;">
<a href="${resetUrl}"
style="background-color: #dc3545; color: white; padding: 12px 24px; text-decoration: none; border-radius: 5px; display: inline-block;">
Reset Password
</a>
</div>
<p>If the button doesn't work, you can copy and paste this link into your browser:</p>
<p style="word-break: break-all; color: #666;">${resetUrl}</p>
<p>This link will expire in 1 hour.</p>
<p>If you didn't request a password reset, you can safely ignore this email.</p>
</div>
`,
text: `
Password Reset Request
You requested to reset your password. Visit this link to create a new password:
${resetUrl}
This link will expire in 1 hour.
If you didn't request a password reset, you can safely ignore this email.
`,
};
}
getWelcomeTemplate(username) {
return {
subject: 'Welcome to Our Platform!',
html: `
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
<h2 style="color: #333;">Welcome, ${username}!</h2>
<p>Thank you for joining our platform. Your account has been successfully created and verified.</p>
<p>You can now:</p>
<ul>
<li>Log in to your account</li>
<li>Update your profile</li>
<li>Explore our features</li>
</ul>
<p>If you have any questions, feel free to contact our support team.</p>
<p>Best regards,<br>The Team</p>
</div>
`,
text: `
Welcome, ${username}!
Thank you for joining our platform. Your account has been successfully created and verified.
You can now:
- Log in to your account
- Update your profile
- Explore our features
If you have any questions, feel free to contact our support team.
Best regards,
The Team
`,
};
}
getAccountLockedTemplate() {
return {
subject: 'Account Locked - Security Alert',
html: `
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
<h2 style="color: #dc3545;">Account Locked</h2>
<p>We detected multiple failed login attempts on your account. For your security, your account has been temporarily locked.</p>
<p>To unlock your account:</p>
<ol>
<li>Wait for the lockout period to expire (usually 15 minutes)</li>
<li>Try logging in again</li>
<li>If you continue to have issues, contact support</li>
</ol>
<p>If this wasn't you, please contact our support team immediately.</p>
<p>Best regards,<br>Security Team</p>
</div>
`,
text: `
Account Locked - Security Alert
We detected multiple failed login attempts on your account. For your security, your account has been temporarily locked.
To unlock your account:
1. Wait for the lockout period to expire (usually 15 minutes)
2. Try logging in again
3. If you continue to have issues, contact support
If this wasn't you, please contact our support team immediately.
Best regards,
Security Team
`,
};
}
getPasswordChangedTemplate() {
return {
subject: 'Password Changed - Security Notification',
html: `
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
<h2 style="color: #28a745;">Password Changed Successfully</h2>
<p>Your password has been successfully changed.</p>
<p>If you didn't make this change, please contact our support team immediately as your account may be compromised.</p>
<p>For your security, we recommend:</p>
<ul>
<li>Using a strong, unique password</li>
<li>Enabling two-factor authentication if available</li>
<li>Regularly reviewing your account activity</li>
</ul>
<p>Best regards,<br>Security Team</p>
</div>
`,
text: `
Password Changed - Security Notification
Your password has been successfully changed.
If you didn't make this change, please contact our support team immediately as your account may be compromised.
For your security, we recommend:
- Using a strong, unique password
- Enabling two-factor authentication if available
- Regularly reviewing your account activity
Best regards,
Security Team
`,
};
}
};
exports.EmailService = EmailService;
exports.EmailService = EmailService = __decorate([
(0, common_1.Injectable)(),
__metadata("design:paramtypes", [config_1.ConfigService])
], EmailService);
//# sourceMappingURL=email.service.js.map