Integrate dotenv for environment variable management and enhance form error handling

- Added dotenv to load environment variables from a .env file in server.js for better configuration management.
- Improved the Form component by refining error handling during form submission, including specific messages for different error scenarios.
- Updated the CSRF token handling and ensured proper validation of response types from the contact API.
- Enhanced user feedback by providing clearer messages for success and error states in the form submission process.
This commit is contained in:
2025-11-02 02:06:29 +01:00
parent 8773788335
commit 3b28d1c52d
4 changed files with 129 additions and 32 deletions

View File

@@ -84,12 +84,12 @@ const { inputs, textarea, disclaimer, button = 'Contact us', description = '', s
{
disclaimer && (
<div class="mt-3 flex items-start mb-6">
<div class="flex mt-0.5">
<div class="flex items-center h-5">
<input
id="disclaimer"
name="disclaimer"
type="checkbox"
class="cursor-pointer mt-1 py-3 px-4 block w-full text-md rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-slate-900"
class="w-4 h-4 cursor-pointer rounded border-gray-300 dark:border-gray-600 text-blue-600 focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400 dark:bg-slate-700 dark:checked:bg-blue-600"
required
aria-describedby="invalid-feedback-disclaimer"
/>
@@ -163,13 +163,10 @@ const { inputs, textarea, disclaimer, button = 'Contact us', description = '', s
<div id="manual-review-result" class="mt-4 text-center text-green-700 dark:text-green-400 font-medium"></div>
</div>
<script>
// TypeScript: declare the property on window
declare global {
interface Window {
__originalEmail?: string;
}
}
<script define:vars={{ spamReviewConfig: spamReview }}>
// Make spamReview accessible in client script
const spamReview = spamReviewConfig || {};
async function setCsrfToken() {
try {
const res = await fetch('/api/contact?csrf=true');
@@ -177,7 +174,7 @@ const { inputs, textarea, disclaimer, button = 'Contact us', description = '', s
const data = await res.json();
const csrfInput = document.getElementById('csrf_token');
if (csrfInput && data.csrfToken) {
(csrfInput as HTMLInputElement).value = data.csrfToken;
csrfInput.value = data.csrfToken;
}
}
} catch (e) {
@@ -187,7 +184,7 @@ const { inputs, textarea, disclaimer, button = 'Contact us', description = '', s
document.addEventListener('DOMContentLoaded', setCsrfToken);
const form = document.getElementById('contact-form') as HTMLFormElement | null;
const form = document.getElementById('contact-form');
if (form) {
form.addEventListener('submit', async (event) => {
@@ -198,14 +195,29 @@ const { inputs, textarea, disclaimer, button = 'Contact us', description = '', s
response = await fetch('/api/contact', {
method: 'POST',
body: formData,
headers: {
'Accept': 'application/json',
},
});
result = await response.json();
// Check if response is JSON before parsing
const contentType = response.headers.get('content-type');
if (contentType && contentType.includes('application/json')) {
result = await response.json();
} else {
const text = await response.text();
throw new Error(`Unexpected response type: ${contentType || 'unknown'}. Response: ${text.substring(0, 100)}`);
}
console.log('Contact API response:', result);
} catch (_err) {
} catch (err) {
const errorElement = document.getElementById('form-error');
if (errorElement) errorElement.classList.remove('hidden');
const successElement = document.getElementById('form-success');
if (successElement) successElement.classList.add('hidden');
if (errorElement) {
errorElement.textContent = 'Network error. Please check your connection and try again.';
errorElement.classList.remove('hidden');
}
console.error('Form submission error:', err);
return;
}
@@ -214,8 +226,8 @@ const { inputs, textarea, disclaimer, button = 'Contact us', description = '', s
console.log('Spam detected, showing manual review UI.');
form.style.display = 'none';
const spamWarning = document.getElementById('spam-warning');
const manualEmail = document.getElementById('manual-email') as HTMLInputElement | null;
const manualToken = document.getElementById('manual-token') as HTMLInputElement | null;
const manualEmail = document.getElementById('manual-email');
const manualToken = document.getElementById('manual-token');
// Store the original email in a variable (not in the input)
window.__originalEmail = String(formData.get('email'));
if (spamWarning && manualEmail && manualToken) {
@@ -228,17 +240,64 @@ const { inputs, textarea, disclaimer, button = 'Contact us', description = '', s
if (!response.ok) {
const errorElement = document.getElementById('form-error');
if (errorElement) errorElement.classList.remove('hidden');
const successElement = document.getElementById('form-success');
if (successElement) successElement.classList.add('hidden');
// Handle specific error cases
if (result.message && result.message.includes('Please use POST')) {
if (errorElement) {
errorElement.textContent = 'There was an error with the form submission. Please refresh the page and try again.';
errorElement.classList.remove('hidden');
}
} else if (result.errors) {
// Handle field-specific validation errors
if (errorElement) {
errorElement.textContent = 'Please check all fields and try again.';
errorElement.classList.remove('hidden');
}
// Show field-specific errors
Object.keys(result.errors).forEach((fieldName) => {
const field = form.querySelector(`[name="${fieldName}"]`);
const feedback = document.getElementById(`invalid-feedback-${fieldName}`);
if (field && feedback) {
field.classList.add('border-red-500');
feedback.textContent = result.errors[fieldName];
feedback.classList.remove('hidden');
}
});
} else if (result.error) {
if (errorElement) {
errorElement.textContent = result.error;
errorElement.classList.remove('hidden');
}
} else {
if (errorElement) {
errorElement.textContent = 'There was an error sending your message. Please try again.';
errorElement.classList.remove('hidden');
}
}
return;
}
// Success
const successElement = document.getElementById('form-success');
if (successElement) successElement.classList.remove('hidden');
if (successElement) {
successElement.textContent = result.message || 'Your message has been sent successfully. We will get back to you soon!';
successElement.classList.remove('hidden');
}
const errorElement = document.getElementById('form-error');
if (errorElement) errorElement.classList.add('hidden');
// Clear any field error states
form.querySelectorAll('.border-red-500').forEach((el) => {
el.classList.remove('border-red-500');
});
form.querySelectorAll('.invalid-feedback').forEach((el) => {
el.classList.add('hidden');
});
form.reset();
setCsrfToken();
});
@@ -249,11 +308,11 @@ const { inputs, textarea, disclaimer, button = 'Contact us', description = '', s
if (manualReviewForm) {
manualReviewForm.onsubmit = async function (e) {
e.preventDefault();
const manualEmail = document.getElementById('manual-email') as HTMLInputElement | null;
const manualJustification = document.getElementById('manual-justification') as HTMLTextAreaElement | null;
const manualToken = document.getElementById('manual-token') as HTMLInputElement | null;
const manualEmail = document.getElementById('manual-email');
const manualJustification = document.getElementById('manual-justification');
const manualToken = document.getElementById('manual-token');
const resultDiv = document.getElementById('manual-review-result');
const form = document.getElementById('contact-form') as HTMLFormElement | null;
const form = document.getElementById('contact-form');
const spamWarning = document.getElementById('spam-warning');
if (!manualEmail || !manualJustification || !manualToken || !resultDiv) return;
const email = manualEmail.value;

View File

@@ -18,27 +18,61 @@ const {
// Email configuration
const isProduction = process.env.NODE_ENV === 'production';
// Debug: Log environment variables on load (only in development or if SMTP_HOST is set)
if (!isProduction || SMTP_HOST) {
console.log('[EMAIL CONFIG] SMTP_HOST:', SMTP_HOST || '(not set)');
console.log('[EMAIL CONFIG] SMTP_PORT:', SMTP_PORT || '(using default: 587)');
console.log('[EMAIL CONFIG] SMTP_USER:', SMTP_USER ? '***' : '(not set - no auth)');
console.log('[EMAIL CONFIG] ADMIN_EMAIL:', ADMIN_EMAIL || '(not set)');
}
// Create a transporter for sending emails
let transporter: nodemailer.Transporter;
// Initialize the transporter based on environment
function initializeTransporter() {
if (isProduction && SMTP_HOST) {
// Use local Postfix mail relay (no authentication)
transporter = nodemailer.createTransport({
const port = parseInt(SMTP_PORT, 10) || 587;
// Determine if secure connection (port 465 typically uses SSL)
const secure = port === 465;
// Build transporter config
const transporterConfig: {
host: string;
port: number;
secure: boolean;
tls: { rejectUnauthorized: boolean };
auth?: { user: string; pass: string };
} = {
host: SMTP_HOST,
port: parseInt(SMTP_PORT, 10) || 25, // default to port 25 if not set
secure: false, // No SSL for local relay
port: port,
secure: secure,
tls: {
rejectUnauthorized: false, // Accept self-signed certificates if present
rejectUnauthorized: false, // Accept self-signed certificates (useful for Mailcow)
},
});
};
transporter.verify((error, success) => {
// Add authentication if credentials are provided
if (SMTP_USER && SMTP_PASS) {
transporterConfig.auth = {
user: SMTP_USER,
pass: SMTP_PASS,
};
}
transporter = nodemailer.createTransport(transporterConfig);
transporter.verify((error, _success) => {
if (error) {
console.error('❌ SMTP connection error:', error);
console.error('❌ SMTP connection error:', error.message);
console.error(' Host:', SMTP_HOST);
console.error(' Port:', port);
console.error(' Auth:', SMTP_USER ? 'Yes' : 'No');
} else {
console.log('✅ SMTP server is ready to take messages.');
console.log(' Host:', SMTP_HOST);
console.log(' Port:', port);
console.log(' Auth:', SMTP_USER ? 'Yes' : 'No');
}
});
} else {
@@ -140,7 +174,7 @@ export function logEmailAttempt(success: boolean, recipient: string, subject: st
}
// Send an email
export async function sendEmail(to: string, subject: string, html: string, text: string, domain?: string): Promise<boolean> {
export async function sendEmail(to: string, subject: string, html: string, text: string, _domain?: string): Promise<boolean> {
// Initialize transporter if not already done
if (!transporter) {
initializeTransporter();

View File

@@ -10,7 +10,7 @@ export async function isSpamWithGemini(message: string): Promise<boolean> {
console.warn('[Gemini] API key not set; skipping spam check.');
return false;
}
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const model = genAI.getGenerativeModel({ model: "gemini-2.5-flash" });
const prompt = `Is the following message spam? Reply with only 'yes' or 'no'.\n\nMessage:\n${message}`;
const result = await model.generateContent(prompt);
const response = result.response.text().trim().toLowerCase();