Add email verification system for user registration
All checks were successful
Build And Push Image / docker (push) Successful in 3m1s
All checks were successful
Build And Push Image / docker (push) Successful in 3m1s
- Add SMTP configuration UI in admin panel with test functionality - Implement email verification workflow with tokens and templates - Add verification success/expired pages for user feedback - Include nodemailer, handlebars, and JWT dependencies - Create API endpoints for email config, testing, and verification
This commit is contained in:
@@ -2,7 +2,7 @@ import { readFile, writeFile, mkdir, access, constants } from 'fs/promises';
|
||||
import { existsSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { createCipheriv, createDecipheriv, randomBytes, pbkdf2Sync } from 'crypto';
|
||||
import type { NocoDBSettings } from '~/utils/types';
|
||||
import type { NocoDBSettings, SMTPConfig } from '~/utils/types';
|
||||
|
||||
interface AdminConfiguration {
|
||||
nocodb: NocoDBSettings;
|
||||
@@ -15,6 +15,15 @@ interface AdminConfiguration {
|
||||
iban: string;
|
||||
accountHolder: string;
|
||||
};
|
||||
smtp?: {
|
||||
host: string;
|
||||
port: number;
|
||||
secure: boolean;
|
||||
username: string;
|
||||
password: string; // Will be encrypted
|
||||
fromAddress: string;
|
||||
fromName: string;
|
||||
};
|
||||
lastUpdated: string;
|
||||
updatedBy: string;
|
||||
}
|
||||
@@ -189,6 +198,9 @@ export async function loadAdminConfig(): Promise<AdminConfiguration | null> {
|
||||
if (config.recaptcha?.secretKey) {
|
||||
config.recaptcha.secretKey = decryptSensitiveData(config.recaptcha.secretKey);
|
||||
}
|
||||
if (config.smtp?.password) {
|
||||
config.smtp.password = decryptSensitiveData(config.smtp.password);
|
||||
}
|
||||
|
||||
console.log('[admin-config] Configuration loaded from file');
|
||||
configCache = config;
|
||||
@@ -409,6 +421,65 @@ export function getRegistrationConfig(): { membershipFee: number; iban: string;
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save SMTP configuration
|
||||
*/
|
||||
export async function saveSMTPConfig(config: SMTPConfig, updatedBy: string): Promise<void> {
|
||||
try {
|
||||
await ensureConfigDir();
|
||||
await createBackup();
|
||||
|
||||
const currentConfig = configCache || await loadAdminConfig() || {
|
||||
nocodb: { url: '', apiKey: '', baseId: '', tables: {} },
|
||||
lastUpdated: new Date().toISOString(),
|
||||
updatedBy: 'system'
|
||||
};
|
||||
|
||||
const updatedConfig: AdminConfiguration = {
|
||||
...currentConfig,
|
||||
smtp: {
|
||||
...config,
|
||||
password: encryptSensitiveData(config.password)
|
||||
},
|
||||
lastUpdated: new Date().toISOString(),
|
||||
updatedBy
|
||||
};
|
||||
|
||||
const configJson = JSON.stringify(updatedConfig, null, 2);
|
||||
await writeFile(CONFIG_FILE, configJson, 'utf-8');
|
||||
|
||||
// Update cache with unencrypted data
|
||||
configCache = {
|
||||
...updatedConfig,
|
||||
smtp: { ...config } // Keep original unencrypted data in cache
|
||||
};
|
||||
|
||||
console.log('[admin-config] SMTP configuration saved');
|
||||
await logConfigChange('SMTP_CONFIG_SAVED', updatedBy, { host: config.host, fromAddress: config.fromAddress });
|
||||
|
||||
} catch (error) {
|
||||
console.error('[admin-config] Failed to save SMTP configuration:', error);
|
||||
await logConfigChange('SMTP_CONFIG_SAVE_FAILED', updatedBy, { error: error instanceof Error ? error.message : String(error) });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get SMTP configuration
|
||||
*/
|
||||
export function getSMTPConfig(): SMTPConfig {
|
||||
const config = configCache?.smtp || {
|
||||
host: '',
|
||||
port: 587,
|
||||
secure: false,
|
||||
username: '',
|
||||
password: '',
|
||||
fromAddress: '',
|
||||
fromName: 'MonacoUSA Portal'
|
||||
};
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize configuration system on server startup
|
||||
*/
|
||||
|
||||
168
server/utils/email-tokens.ts
Normal file
168
server/utils/email-tokens.ts
Normal file
@@ -0,0 +1,168 @@
|
||||
import { sign, verify } from 'jsonwebtoken';
|
||||
|
||||
export interface EmailVerificationTokenPayload {
|
||||
userId: string;
|
||||
email: string;
|
||||
purpose: 'email-verification';
|
||||
iat: number;
|
||||
}
|
||||
|
||||
// In-memory token storage for validation (in production, consider Redis)
|
||||
const activeTokens = new Map<string, EmailVerificationTokenPayload>();
|
||||
|
||||
/**
|
||||
* Generate a secure JWT token for email verification
|
||||
*/
|
||||
export async function generateEmailVerificationToken(userId: string, email: string): Promise<string> {
|
||||
const runtimeConfig = useRuntimeConfig();
|
||||
|
||||
if (!runtimeConfig.jwtSecret) {
|
||||
throw new Error('JWT secret not configured');
|
||||
}
|
||||
|
||||
const payload: EmailVerificationTokenPayload = {
|
||||
userId,
|
||||
email: email.toLowerCase().trim(),
|
||||
purpose: 'email-verification',
|
||||
iat: Date.now()
|
||||
};
|
||||
|
||||
const token = sign(payload, runtimeConfig.jwtSecret, {
|
||||
expiresIn: '24h',
|
||||
issuer: 'monacousa-portal',
|
||||
audience: 'email-verification'
|
||||
});
|
||||
|
||||
// Store token metadata for additional validation
|
||||
activeTokens.set(token, payload);
|
||||
|
||||
// Clean up expired tokens periodically
|
||||
setTimeout(() => {
|
||||
activeTokens.delete(token);
|
||||
}, 24 * 60 * 60 * 1000); // 24 hours
|
||||
|
||||
console.log('[email-tokens] Generated verification token for user:', userId, 'email:', email);
|
||||
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify and decode an email verification token
|
||||
*/
|
||||
export async function verifyEmailToken(token: string): Promise<{ userId: string; email: string }> {
|
||||
const runtimeConfig = useRuntimeConfig();
|
||||
|
||||
if (!runtimeConfig.jwtSecret) {
|
||||
throw new Error('JWT secret not configured');
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
throw new Error('Token is required');
|
||||
}
|
||||
|
||||
try {
|
||||
// Verify JWT signature and expiration
|
||||
const decoded = verify(token, runtimeConfig.jwtSecret, {
|
||||
issuer: 'monacousa-portal',
|
||||
audience: 'email-verification'
|
||||
}) as EmailVerificationTokenPayload;
|
||||
|
||||
// Validate token purpose
|
||||
if (decoded.purpose !== 'email-verification') {
|
||||
throw new Error('Invalid token purpose');
|
||||
}
|
||||
|
||||
// Check if token exists in our active tokens (prevents replay attacks)
|
||||
const storedPayload = activeTokens.get(token);
|
||||
if (!storedPayload) {
|
||||
throw new Error('Token not found or already used');
|
||||
}
|
||||
|
||||
// Validate payload consistency
|
||||
if (storedPayload.userId !== decoded.userId || storedPayload.email !== decoded.email) {
|
||||
throw new Error('Token payload mismatch');
|
||||
}
|
||||
|
||||
// Remove token after successful verification (single use)
|
||||
activeTokens.delete(token);
|
||||
|
||||
console.log('[email-tokens] Successfully verified token for user:', decoded.userId, 'email:', decoded.email);
|
||||
|
||||
return {
|
||||
userId: decoded.userId,
|
||||
email: decoded.email
|
||||
};
|
||||
|
||||
} catch (error: any) {
|
||||
console.error('[email-tokens] Token verification failed:', error.message);
|
||||
|
||||
// Provide user-friendly error messages
|
||||
if (error.name === 'TokenExpiredError') {
|
||||
throw new Error('Verification link has expired. Please request a new one.');
|
||||
} else if (error.name === 'JsonWebTokenError') {
|
||||
throw new Error('Invalid verification link.');
|
||||
} else {
|
||||
throw new Error(error.message || 'Token verification failed');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a token is still valid without consuming it
|
||||
*/
|
||||
export async function isTokenValid(token: string): Promise<boolean> {
|
||||
try {
|
||||
const runtimeConfig = useRuntimeConfig();
|
||||
|
||||
if (!runtimeConfig.jwtSecret || !token) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const decoded = verify(token, runtimeConfig.jwtSecret, {
|
||||
issuer: 'monacousa-portal',
|
||||
audience: 'email-verification'
|
||||
}) as EmailVerificationTokenPayload;
|
||||
|
||||
return decoded.purpose === 'email-verification' && activeTokens.has(token);
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up expired tokens from memory
|
||||
*/
|
||||
export function cleanupExpiredTokens(): void {
|
||||
const now = Date.now();
|
||||
const expirationTime = 24 * 60 * 60 * 1000; // 24 hours
|
||||
|
||||
for (const [token, payload] of activeTokens.entries()) {
|
||||
if (now - payload.iat > expirationTime) {
|
||||
activeTokens.delete(token);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('[email-tokens] Cleaned up expired tokens. Active tokens:', activeTokens.size);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get statistics about active tokens
|
||||
*/
|
||||
export function getTokenStats(): { activeTokens: number; oldestToken: number | null } {
|
||||
const now = Date.now();
|
||||
let oldestToken: number | null = null;
|
||||
|
||||
for (const payload of activeTokens.values()) {
|
||||
if (oldestToken === null || payload.iat < oldestToken) {
|
||||
oldestToken = payload.iat;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
activeTokens: activeTokens.size,
|
||||
oldestToken: oldestToken ? Math.floor((now - oldestToken) / 1000 / 60) : null // minutes ago
|
||||
};
|
||||
}
|
||||
|
||||
// Periodic cleanup of expired tokens (every hour)
|
||||
setInterval(cleanupExpiredTokens, 60 * 60 * 1000);
|
||||
356
server/utils/email.ts
Normal file
356
server/utils/email.ts
Normal file
@@ -0,0 +1,356 @@
|
||||
import nodemailer from 'nodemailer';
|
||||
import handlebars from 'handlebars';
|
||||
import { readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import type { SMTPConfig } from '~/utils/types';
|
||||
|
||||
export interface EmailData {
|
||||
to: string;
|
||||
subject: string;
|
||||
html: string;
|
||||
text?: string;
|
||||
}
|
||||
|
||||
export interface WelcomeEmailData {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
verificationLink: string;
|
||||
memberId: string;
|
||||
logoUrl?: string;
|
||||
}
|
||||
|
||||
export interface VerificationEmailData {
|
||||
firstName: string;
|
||||
verificationLink: string;
|
||||
logoUrl?: string;
|
||||
}
|
||||
|
||||
export interface PasswordResetEmailData {
|
||||
firstName: string;
|
||||
resetLink: string;
|
||||
logoUrl?: string;
|
||||
}
|
||||
|
||||
export interface DuesReminderEmailData {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
amount: number;
|
||||
dueDate: string;
|
||||
iban?: string;
|
||||
accountHolder?: string;
|
||||
logoUrl?: string;
|
||||
}
|
||||
|
||||
export class EmailService {
|
||||
private transporter: nodemailer.Transporter | null = null;
|
||||
private templates: Map<string, handlebars.TemplateDelegate> = new Map();
|
||||
|
||||
constructor(private config: SMTPConfig) {
|
||||
this.initializeTransporter();
|
||||
this.preloadTemplates();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the nodemailer transporter
|
||||
*/
|
||||
private initializeTransporter(): void {
|
||||
if (!this.config.host || !this.config.port) {
|
||||
console.warn('[EmailService] SMTP configuration incomplete, emails will not be sent');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
this.transporter = nodemailer.createTransport({
|
||||
host: this.config.host,
|
||||
port: this.config.port,
|
||||
secure: this.config.secure, // true for 465, false for other ports
|
||||
auth: this.config.username && this.config.password ? {
|
||||
user: this.config.username,
|
||||
pass: this.config.password
|
||||
} : undefined,
|
||||
tls: {
|
||||
rejectUnauthorized: false // Accept self-signed certificates in development
|
||||
}
|
||||
});
|
||||
|
||||
console.log('[EmailService] ✅ SMTP transporter initialized');
|
||||
} catch (error) {
|
||||
console.error('[EmailService] ❌ Failed to initialize SMTP transporter:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Preload and compile email templates
|
||||
*/
|
||||
private preloadTemplates(): void {
|
||||
const templateNames = ['welcome', 'verification', 'password-reset', 'dues-reminder', 'test'];
|
||||
|
||||
templateNames.forEach(templateName => {
|
||||
try {
|
||||
const templatePath = join(process.cwd(), 'server/templates', `${templateName}.hbs`);
|
||||
const templateContent = readFileSync(templatePath, 'utf-8');
|
||||
const compiledTemplate = handlebars.compile(templateContent);
|
||||
this.templates.set(templateName, compiledTemplate);
|
||||
console.log(`[EmailService] ✅ Template '${templateName}' loaded`);
|
||||
} catch (error) {
|
||||
console.warn(`[EmailService] ⚠️ Template '${templateName}' not found or failed to load:`, error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a compiled template by name
|
||||
*/
|
||||
private getTemplate(templateName: string): handlebars.TemplateDelegate | null {
|
||||
return this.templates.get(templateName) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a generic email
|
||||
*/
|
||||
private async sendEmail(emailData: EmailData): Promise<void> {
|
||||
if (!this.transporter) {
|
||||
throw new Error('SMTP transporter not initialized');
|
||||
}
|
||||
|
||||
const mailOptions = {
|
||||
from: `${this.config.fromName} <${this.config.fromAddress}>`,
|
||||
to: emailData.to,
|
||||
subject: emailData.subject,
|
||||
html: emailData.html,
|
||||
text: emailData.text || undefined
|
||||
};
|
||||
|
||||
try {
|
||||
const info = await this.transporter.sendMail(mailOptions);
|
||||
console.log(`[EmailService] ✅ Email sent successfully to ${emailData.to}:`, info.messageId);
|
||||
} catch (error) {
|
||||
console.error(`[EmailService] ❌ Failed to send email to ${emailData.to}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send welcome/verification email to new members
|
||||
*/
|
||||
async sendWelcomeEmail(to: string, data: WelcomeEmailData): Promise<void> {
|
||||
const template = this.getTemplate('welcome');
|
||||
if (!template) {
|
||||
throw new Error('Welcome email template not found');
|
||||
}
|
||||
|
||||
const templateData = {
|
||||
...data,
|
||||
logoUrl: data.logoUrl || `${useRuntimeConfig().public.domain}/MONACOUSA-Flags_376x376.png`
|
||||
};
|
||||
|
||||
const html = template(templateData);
|
||||
|
||||
await this.sendEmail({
|
||||
to,
|
||||
subject: 'Welcome to MonacoUSA - Please Verify Your Email',
|
||||
html
|
||||
});
|
||||
|
||||
console.log(`[EmailService] ✅ Welcome email sent to ${to}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send email verification email
|
||||
*/
|
||||
async sendVerificationEmail(to: string, data: VerificationEmailData): Promise<void> {
|
||||
const template = this.getTemplate('verification');
|
||||
if (!template) {
|
||||
throw new Error('Verification email template not found');
|
||||
}
|
||||
|
||||
const templateData = {
|
||||
...data,
|
||||
logoUrl: data.logoUrl || `${useRuntimeConfig().public.domain}/MONACOUSA-Flags_376x376.png`
|
||||
};
|
||||
|
||||
const html = template(templateData);
|
||||
|
||||
await this.sendEmail({
|
||||
to,
|
||||
subject: 'Verify Your Email - MonacoUSA Portal',
|
||||
html
|
||||
});
|
||||
|
||||
console.log(`[EmailService] ✅ Verification email sent to ${to}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send password reset email
|
||||
*/
|
||||
async sendPasswordResetEmail(to: string, data: PasswordResetEmailData): Promise<void> {
|
||||
const template = this.getTemplate('password-reset');
|
||||
if (!template) {
|
||||
throw new Error('Password reset email template not found');
|
||||
}
|
||||
|
||||
const templateData = {
|
||||
...data,
|
||||
logoUrl: data.logoUrl || `${useRuntimeConfig().public.domain}/MONACOUSA-Flags_376x376.png`
|
||||
};
|
||||
|
||||
const html = template(templateData);
|
||||
|
||||
await this.sendEmail({
|
||||
to,
|
||||
subject: 'Reset Your Password - MonacoUSA Portal',
|
||||
html
|
||||
});
|
||||
|
||||
console.log(`[EmailService] ✅ Password reset email sent to ${to}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send membership dues reminder email
|
||||
*/
|
||||
async sendDuesReminderEmail(to: string, data: DuesReminderEmailData): Promise<void> {
|
||||
const template = this.getTemplate('dues-reminder');
|
||||
if (!template) {
|
||||
throw new Error('Dues reminder email template not found');
|
||||
}
|
||||
|
||||
const templateData = {
|
||||
...data,
|
||||
logoUrl: data.logoUrl || `${useRuntimeConfig().public.domain}/MONACOUSA-Flags_376x376.png`
|
||||
};
|
||||
|
||||
const html = template(templateData);
|
||||
|
||||
await this.sendEmail({
|
||||
to,
|
||||
subject: `MonacoUSA Membership Dues Reminder - €${data.amount} Due`,
|
||||
html
|
||||
});
|
||||
|
||||
console.log(`[EmailService] ✅ Dues reminder email sent to ${to}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send test email to verify SMTP configuration
|
||||
*/
|
||||
async sendTestEmail(to: string): Promise<void> {
|
||||
const template = this.getTemplate('test');
|
||||
|
||||
const templateData = {
|
||||
testTime: new Date().toISOString(),
|
||||
logoUrl: `${useRuntimeConfig().public.domain}/MONACOUSA-Flags_376x376.png`,
|
||||
smtpHost: this.config.host,
|
||||
fromAddress: this.config.fromAddress
|
||||
};
|
||||
|
||||
let html: string;
|
||||
if (template) {
|
||||
html = template(templateData);
|
||||
} else {
|
||||
// Fallback HTML if template is not available
|
||||
html = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head><title>SMTP Test Email</title></head>
|
||||
<body style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;">
|
||||
<div style="text-align: center; margin-bottom: 30px;">
|
||||
<img src="${templateData.logoUrl}" alt="MonacoUSA" style="width: 100px;">
|
||||
<h1 style="color: #a31515;">SMTP Test Email</h1>
|
||||
</div>
|
||||
|
||||
<p>This is a test email from the MonacoUSA Portal email system.</p>
|
||||
|
||||
<div style="background: #f5f5f5; padding: 15px; border-radius: 8px; margin: 20px 0;">
|
||||
<p><strong>Test Details:</strong></p>
|
||||
<ul>
|
||||
<li>Sent at: ${templateData.testTime}</li>
|
||||
<li>SMTP Host: ${templateData.smtpHost}</li>
|
||||
<li>From Address: ${templateData.fromAddress}</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<p>If you received this email, your SMTP configuration is working correctly!</p>
|
||||
|
||||
<hr style="margin: 30px 0;">
|
||||
<p style="color: #666; font-size: 14px; text-align: center;">
|
||||
MonacoUSA Portal Email System
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
}
|
||||
|
||||
await this.sendEmail({
|
||||
to,
|
||||
subject: 'SMTP Configuration Test - MonacoUSA Portal',
|
||||
html,
|
||||
text: `This is a test email from MonacoUSA Portal. Sent at: ${templateData.testTime}`
|
||||
});
|
||||
|
||||
console.log(`[EmailService] ✅ Test email sent to ${to}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify SMTP connection
|
||||
*/
|
||||
async verifyConnection(): Promise<boolean> {
|
||||
if (!this.transporter) {
|
||||
throw new Error('SMTP transporter not initialized');
|
||||
}
|
||||
|
||||
try {
|
||||
await this.transporter.verify();
|
||||
console.log('[EmailService] ✅ SMTP connection verified');
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('[EmailService] ❌ SMTP connection verification failed:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update SMTP configuration and reinitialize transporter
|
||||
*/
|
||||
updateConfig(newConfig: SMTPConfig): void {
|
||||
this.config = newConfig;
|
||||
this.initializeTransporter();
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the transporter connection
|
||||
*/
|
||||
close(): void {
|
||||
if (this.transporter) {
|
||||
this.transporter.close();
|
||||
this.transporter = null;
|
||||
console.log('[EmailService] SMTP connection closed');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Singleton instance for reuse across the application
|
||||
let emailServiceInstance: EmailService | null = null;
|
||||
|
||||
/**
|
||||
* Get or create EmailService instance with current SMTP config
|
||||
*/
|
||||
export function getEmailService(): EmailService {
|
||||
const { getSMTPConfig } = require('./admin-config');
|
||||
const config = getSMTPConfig();
|
||||
|
||||
if (!emailServiceInstance) {
|
||||
emailServiceInstance = new EmailService(config);
|
||||
} else {
|
||||
// Update config in case it changed
|
||||
emailServiceInstance.updateConfig(config);
|
||||
}
|
||||
|
||||
return emailServiceInstance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new EmailService instance with custom config
|
||||
*/
|
||||
export function createEmailService(config: SMTPConfig): EmailService {
|
||||
return new EmailService(config);
|
||||
}
|
||||
Reference in New Issue
Block a user