Add TurnstileCaptcha component and update send API handler
This commit is contained in:
@@ -6,6 +6,20 @@ CORS_ORIGIN=http://localhost:5173
|
|||||||
UPLOAD_DIR=./server/uploads
|
UPLOAD_DIR=./server/uploads
|
||||||
DATA_DIR=./server/data
|
DATA_DIR=./server/data
|
||||||
|
|
||||||
|
# SMTP Mail Service Settings for Contact Us Form
|
||||||
|
SMTP_HOST=smtp.gmail.com
|
||||||
|
SMTP_PORT=465
|
||||||
|
SMTP_SECURE=true
|
||||||
|
SMTP_USER=info@cavinfotech.com
|
||||||
|
SMTP_PASS=your-smtp-password-or-app-password
|
||||||
|
SMTP_FROM="Cavin Infotech Contact Form" <info@cavinfotech.com>
|
||||||
|
SMTP_TO=info@cavinfotech.com
|
||||||
|
# Cloudflare Turnstile Settings (Use Cloudflare testing keys by default)
|
||||||
|
# Sitekey for frontend: 1x00000000000000000000AA (Always Passes - Visible Widget)
|
||||||
|
VITE_TURNSTILE_SITE_KEY=1x00000000000000000000AA
|
||||||
|
# Secret key for backend: 1x000000000000000000000000000000AA
|
||||||
|
TURNSTILE_SECRET_KEY=1x000000000000000000000000000000AA
|
||||||
|
|
||||||
# Production (demo.cavinkare.in/citpl_website):
|
# Production (demo.cavinkare.in/citpl_website):
|
||||||
# 1. Copy dist/ + server/ + package.json + .env to the host
|
# 1. Copy dist/ + server/ + package.json + .env to the host
|
||||||
# 2. npm install --omit=dev && npm run server (or pm2 start server/index.js)
|
# 2. npm install --omit=dev && npm run server (or pm2 start server/index.js)
|
||||||
|
|||||||
+91
-25
@@ -1,5 +1,6 @@
|
|||||||
|
import nodemailer from 'nodemailer';
|
||||||
|
|
||||||
export default async function handler(req, res) {
|
export default async function handler(req, res) {
|
||||||
// Set CORS headers for local development if needed
|
|
||||||
res.setHeader('Access-Control-Allow-Origin', '*');
|
res.setHeader('Access-Control-Allow-Origin', '*');
|
||||||
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
|
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
|
||||||
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
|
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
|
||||||
@@ -12,41 +13,106 @@ export default async function handler(req, res) {
|
|||||||
return res.status(405).json({ error: 'Method Not Allowed' });
|
return res.status(405).json({ error: 'Method Not Allowed' });
|
||||||
}
|
}
|
||||||
|
|
||||||
const { type, name, email, phone, mobile, designation, dateTime, interests, resumeName } = req.body;
|
const { type, name, email, phone, mobile, subject, message, interests, turnstileToken } = req.body;
|
||||||
|
|
||||||
const serviceId = process.env.EMAILJS_SERVICE_ID || 'vishva_cavintest';
|
const contactName = name?.trim();
|
||||||
const publicKey = process.env.EMAILJS_PUBLIC_KEY || 'YOUR_EMAILJS_PUBLIC_KEY';
|
const contactEmail = email?.trim();
|
||||||
|
const contactPhone = (phone || mobile || '').trim();
|
||||||
let templateId = '';
|
const contactSubject = (subject || interests || type || 'General Inquiry').trim();
|
||||||
if (type === 'careers') {
|
const contactMessage = (message || req.body.comments || '').trim();
|
||||||
templateId = process.env.EMAILJS_TEMPLATE_ID_CAREERS || 'YOUR_EMAILJS_TEMPLATE_ID_CAREERS';
|
|
||||||
} else {
|
if (!contactName || !contactEmail) {
|
||||||
templateId = process.env.EMAILJS_TEMPLATE_ID_STRATEGY || 'YOUR_EMAILJS_TEMPLATE_ID_STRATEGY';
|
return res.status(400).json({ error: 'Name and Email are required.' });
|
||||||
}
|
}
|
||||||
|
|
||||||
const templateParams = {
|
// Verify Cloudflare Turnstile Token
|
||||||
type: type,
|
if (turnstileToken) {
|
||||||
name: name,
|
const secretKey = process.env.TURNSTILE_SECRET_KEY || '1x000000000000000000000000000000AA';
|
||||||
email: email,
|
try {
|
||||||
phone: phone || mobile || '',
|
const formData = new URLSearchParams();
|
||||||
mobile: mobile || phone || '',
|
formData.append('secret', secretKey);
|
||||||
designation: designation || 'N/A',
|
formData.append('response', turnstileToken);
|
||||||
dateTime: dateTime || 'N/A',
|
const turnstileRes = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
|
||||||
interests: interests || 'N/A',
|
method: 'POST',
|
||||||
resumeName: resumeName || 'None'
|
body: formData
|
||||||
};
|
});
|
||||||
|
const turnstileOutcome = await turnstileRes.json();
|
||||||
|
if (!turnstileOutcome.success) {
|
||||||
|
return res.status(400).json({ error: 'Cloudflare Turnstile verification failed. Please try again.' });
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Turnstile verification error:', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Try sending via SMTP (nodemailer)
|
||||||
|
const smtpHost = process.env.SMTP_HOST;
|
||||||
|
const smtpUser = process.env.SMTP_USER;
|
||||||
|
const smtpPass = process.env.SMTP_PASS;
|
||||||
|
|
||||||
|
if (smtpHost && smtpUser && smtpPass) {
|
||||||
|
try {
|
||||||
|
const port = parseInt(process.env.SMTP_PORT || '465', 10);
|
||||||
|
const secure = process.env.SMTP_SECURE === 'true' || port === 465;
|
||||||
|
|
||||||
|
const transporter = nodemailer.createTransport({
|
||||||
|
host: smtpHost,
|
||||||
|
port,
|
||||||
|
secure,
|
||||||
|
auth: { user: smtpUser, pass: smtpPass },
|
||||||
|
tls: { rejectUnauthorized: false }
|
||||||
|
});
|
||||||
|
|
||||||
|
const toEmail = process.env.SMTP_TO || smtpUser;
|
||||||
|
const fromEmail = process.env.SMTP_FROM || `"Cavin Infotech Contact" <${smtpUser}>`;
|
||||||
|
|
||||||
|
const info = await transporter.sendMail({
|
||||||
|
from: fromEmail,
|
||||||
|
to: toEmail,
|
||||||
|
replyTo: `"${contactName}" <${contactEmail}>`,
|
||||||
|
subject: `[Contact Form] ${contactSubject}`,
|
||||||
|
text: `Name: ${contactName}\nEmail: ${contactEmail}\nPhone: ${contactPhone}\nSubject: ${contactSubject}\n\nMessage:\n${contactMessage}`,
|
||||||
|
html: `
|
||||||
|
<div style="font-family: Arial, sans-serif; background: #020710; color: #fff; padding: 30px; border-radius: 12px;">
|
||||||
|
<h2 style="color: #ffaa00; margin-top: 0;">Cavin Infotech - Contact Inquiry</h2>
|
||||||
|
<p><strong>Name:</strong> ${contactName}</p>
|
||||||
|
<p><strong>Email:</strong> <a href="mailto:${contactEmail}" style="color: #38bdf8;">${contactEmail}</a></p>
|
||||||
|
<p><strong>Phone:</strong> ${contactPhone || 'Not provided'}</p>
|
||||||
|
<p><strong>Subject:</strong> ${contactSubject}</p>
|
||||||
|
<div style="margin-top: 20px; padding: 15px; background: #0b1528; border-left: 4px solid #ffaa00; border-radius: 6px;">
|
||||||
|
<p style="margin: 0; white-space: pre-line;">${contactMessage}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`
|
||||||
|
});
|
||||||
|
|
||||||
|
return res.status(200).json({ success: true, messageId: info.messageId, message: 'Message sent via SMTP!' });
|
||||||
|
} catch (smtpErr) {
|
||||||
|
console.error('SMTP Send Error:', smtpErr);
|
||||||
|
return res.status(500).json({ error: `SMTP Send Error: ${smtpErr.message}` });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Fallback to EmailJS API if SMTP env vars are not set
|
||||||
|
const serviceId = process.env.EMAILJS_SERVICE_ID || 'vishva_cavintest';
|
||||||
|
const publicKey = process.env.EMAILJS_PUBLIC_KEY || 'YOUR_EMAILJS_PUBLIC_KEY';
|
||||||
|
const templateId = process.env.EMAILJS_TEMPLATE_ID_STRATEGY || 'YOUR_EMAILJS_TEMPLATE_ID_STRATEGY';
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch('https://api.emailjs.com/api/v1.0/email/send', {
|
const response = await fetch('https://api.emailjs.com/api/v1.0/email/send', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: { 'Content-Type': 'application/json' },
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
service_id: serviceId,
|
service_id: serviceId,
|
||||||
template_id: templateId,
|
template_id: templateId,
|
||||||
user_id: publicKey,
|
user_id: publicKey,
|
||||||
template_params: templateParams
|
template_params: {
|
||||||
|
name: contactName,
|
||||||
|
email: contactEmail,
|
||||||
|
phone: contactPhone,
|
||||||
|
interests: contactSubject,
|
||||||
|
message: contactMessage
|
||||||
|
}
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -4,10 +4,31 @@ import { sendContactEmail } from '../services/mailService.js';
|
|||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
|
async function verifyTurnstile(token, remoteip) {
|
||||||
|
const secretKey = process.env.TURNSTILE_SECRET_KEY || '1x000000000000000000000000000000AA';
|
||||||
|
if (!token) return { success: false, 'error-codes': ['missing-input-response'] };
|
||||||
|
|
||||||
|
try {
|
||||||
|
const formData = new URLSearchParams();
|
||||||
|
formData.append('secret', secretKey);
|
||||||
|
formData.append('response', token);
|
||||||
|
if (remoteip) formData.append('remoteip', remoteip);
|
||||||
|
|
||||||
|
const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
|
||||||
|
method: 'POST',
|
||||||
|
body: formData
|
||||||
|
});
|
||||||
|
return await res.json();
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Turnstile verification exception:', err);
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// POST /api/contact - Handle Contact Us Form submission via SMTP
|
// POST /api/contact - Handle Contact Us Form submission via SMTP
|
||||||
router.post('/', async (req, res) => {
|
router.post('/', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { name, email, phone, mobile, subject, message, interests, type } = req.body;
|
const { name, email, phone, mobile, subject, message, interests, type, turnstileToken } = req.body;
|
||||||
|
|
||||||
const contactName = name?.trim();
|
const contactName = name?.trim();
|
||||||
const contactEmail = email?.trim();
|
const contactEmail = email?.trim();
|
||||||
@@ -19,6 +40,14 @@ router.post('/', async (req, res) => {
|
|||||||
return res.status(400).json({ error: 'Name and Email are required.' });
|
return res.status(400).json({ error: 'Name and Email are required.' });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Verify Cloudflare Turnstile Token
|
||||||
|
if (turnstileToken) {
|
||||||
|
const turnstileRes = await verifyTurnstile(turnstileToken, req.ip);
|
||||||
|
if (!turnstileRes.success) {
|
||||||
|
return res.status(400).json({ error: 'Cloudflare Turnstile security verification failed. Please try again.' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Save lead record in database
|
// Save lead record in database
|
||||||
const lead = saveLead({
|
const lead = saveLead({
|
||||||
name: contactName,
|
name: contactName,
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import React, { useState } from 'react';
|
import React, { useState, useCallback } from 'react';
|
||||||
import { motion } from 'framer-motion';
|
import { motion } from 'framer-motion';
|
||||||
import { assetUrl } from '../lib/assetUrl';
|
import { assetUrl } from '../lib/assetUrl';
|
||||||
import { Mail, Phone, Clock, ArrowUpRight, Check } from 'lucide-react';
|
import { Mail, Phone, Clock, ArrowUpRight, Check, ShieldCheck } from 'lucide-react';
|
||||||
|
import TurnstileCaptcha from './TurnstileCaptcha';
|
||||||
|
|
||||||
export default function ContactSection({ isMobile, onOpenStrategy }) {
|
export default function ContactSection({ isMobile, onOpenStrategy }) {
|
||||||
const [formData, setFormData] = useState({
|
const [formData, setFormData] = useState({
|
||||||
@@ -11,10 +12,21 @@ export default function ContactSection({ isMobile, onOpenStrategy }) {
|
|||||||
subject: '',
|
subject: '',
|
||||||
message: ''
|
message: ''
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const [turnstileToken, setTurnstileToken] = useState('');
|
||||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||||
const [submitted, setSubmitted] = useState(false);
|
const [submitted, setSubmitted] = useState(false);
|
||||||
const [errorMsg, setErrorMsg] = useState('');
|
const [errorMsg, setErrorMsg] = useState('');
|
||||||
|
|
||||||
|
const handleTurnstileVerify = useCallback((token) => {
|
||||||
|
setTurnstileToken(token);
|
||||||
|
if (errorMsg) setErrorMsg('');
|
||||||
|
}, [errorMsg]);
|
||||||
|
|
||||||
|
const handleTurnstileExpire = useCallback(() => {
|
||||||
|
setTurnstileToken('');
|
||||||
|
}, []);
|
||||||
|
|
||||||
const handleChange = (e) => {
|
const handleChange = (e) => {
|
||||||
setFormData({ ...formData, [e.target.name]: e.target.value });
|
setFormData({ ...formData, [e.target.name]: e.target.value });
|
||||||
if (errorMsg) setErrorMsg('');
|
if (errorMsg) setErrorMsg('');
|
||||||
@@ -27,6 +39,11 @@ export default function ContactSection({ isMobile, onOpenStrategy }) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!turnstileToken) {
|
||||||
|
setErrorMsg('Please complete the Cloudflare Turnstile security verification.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
setIsSubmitting(true);
|
setIsSubmitting(true);
|
||||||
setErrorMsg('');
|
setErrorMsg('');
|
||||||
|
|
||||||
@@ -40,7 +57,8 @@ export default function ContactSection({ isMobile, onOpenStrategy }) {
|
|||||||
email: formData.email,
|
email: formData.email,
|
||||||
phone: formData.phone,
|
phone: formData.phone,
|
||||||
subject: formData.subject,
|
subject: formData.subject,
|
||||||
message: formData.message
|
message: formData.message,
|
||||||
|
turnstileToken
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -54,7 +72,8 @@ export default function ContactSection({ isMobile, onOpenStrategy }) {
|
|||||||
email: formData.email,
|
email: formData.email,
|
||||||
phone: formData.phone,
|
phone: formData.phone,
|
||||||
subject: formData.subject,
|
subject: formData.subject,
|
||||||
message: formData.message
|
message: formData.message,
|
||||||
|
turnstileToken
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -64,13 +83,15 @@ export default function ContactSection({ isMobile, onOpenStrategy }) {
|
|||||||
if (response.ok && resData.success) {
|
if (response.ok && resData.success) {
|
||||||
setSubmitted(true);
|
setSubmitted(true);
|
||||||
setFormData({ name: '', email: '', phone: '', subject: '', message: '' });
|
setFormData({ name: '', email: '', phone: '', subject: '', message: '' });
|
||||||
|
setTurnstileToken('');
|
||||||
} else {
|
} else {
|
||||||
setErrorMsg(resData.error || resData.smtpError || 'Failed to send message. Please check SMTP configuration.');
|
setErrorMsg(resData.error || resData.smtpError || 'Cloudflare Turnstile verification failed. Please try again.');
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Contact submit error:', err);
|
console.error('Contact submit error:', err);
|
||||||
setSubmitted(true);
|
setSubmitted(true);
|
||||||
setFormData({ name: '', email: '', phone: '', subject: '', message: '' });
|
setFormData({ name: '', email: '', phone: '', subject: '', message: '' });
|
||||||
|
setTurnstileToken('');
|
||||||
} finally {
|
} finally {
|
||||||
setIsSubmitting(false);
|
setIsSubmitting(false);
|
||||||
}
|
}
|
||||||
@@ -543,6 +564,12 @@ export default function ContactSection({ isMobile, onOpenStrategy }) {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Cloudflare Turnstile Security Verification */}
|
||||||
|
<TurnstileCaptcha
|
||||||
|
onVerify={handleTurnstileVerify}
|
||||||
|
onExpire={handleTurnstileExpire}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* Submit Button */}
|
{/* Submit Button */}
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
import React, { useEffect, useRef, useState } from 'react';
|
||||||
|
|
||||||
|
// Cloudflare Turnstile Test Sitekeys:
|
||||||
|
// '1x00000000000000000000AA' -> Always passes (Visible Widget)
|
||||||
|
const DEFAULT_SITE_KEY = '1x00000000000000000000AA';
|
||||||
|
|
||||||
|
export default function TurnstileCaptcha({ onVerify, onError, onExpire }) {
|
||||||
|
const containerRef = useRef(null);
|
||||||
|
const widgetIdRef = useRef(null);
|
||||||
|
const [scriptLoaded, setScriptLoaded] = useState(false);
|
||||||
|
|
||||||
|
const siteKey = import.meta.env.VITE_TURNSTILE_SITE_KEY || process.env.VITE_TURNSTILE_SITE_KEY || DEFAULT_SITE_KEY;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (window.turnstile) {
|
||||||
|
setScriptLoaded(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const scriptId = 'cf-turnstile-script';
|
||||||
|
let existingScript = document.getElementById(scriptId);
|
||||||
|
|
||||||
|
if (!existingScript) {
|
||||||
|
const script = document.createElement('script');
|
||||||
|
script.id = scriptId;
|
||||||
|
script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
|
||||||
|
script.async = true;
|
||||||
|
script.defer = true;
|
||||||
|
script.onload = () => setScriptLoaded(true);
|
||||||
|
document.head.appendChild(script);
|
||||||
|
} else {
|
||||||
|
existingScript.addEventListener('load', () => setScriptLoaded(true));
|
||||||
|
if (window.turnstile) setScriptLoaded(true);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!scriptLoaded || !containerRef.current || !window.turnstile) return;
|
||||||
|
|
||||||
|
if (widgetIdRef.current !== null) {
|
||||||
|
try {
|
||||||
|
window.turnstile.remove(widgetIdRef.current);
|
||||||
|
} catch {
|
||||||
|
// Ignore cleanup error if widget was already removed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
widgetIdRef.current = window.turnstile.render(containerRef.current, {
|
||||||
|
sitekey: siteKey,
|
||||||
|
theme: 'dark',
|
||||||
|
callback: (token) => {
|
||||||
|
if (onVerify) onVerify(token);
|
||||||
|
},
|
||||||
|
'error-callback': (err) => {
|
||||||
|
if (onError) onError(err);
|
||||||
|
},
|
||||||
|
'expired-callback': () => {
|
||||||
|
if (onExpire) onExpire();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[Turnstile] Render error:', e);
|
||||||
|
}
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
if (widgetIdRef.current !== null && window.turnstile) {
|
||||||
|
try {
|
||||||
|
window.turnstile.remove(widgetIdRef.current);
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
widgetIdRef.current = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, [scriptLoaded, siteKey]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{
|
||||||
|
display: 'flex',
|
||||||
|
justifyContent: 'center',
|
||||||
|
alignItems: 'center',
|
||||||
|
margin: '0.75rem 0',
|
||||||
|
minHeight: '65px',
|
||||||
|
width: '100%'
|
||||||
|
}}>
|
||||||
|
<div ref={containerRef} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
+2
-2
@@ -14,13 +14,13 @@ export default defineConfig((configEnv) => {
|
|||||||
server: {
|
server: {
|
||||||
proxy: {
|
proxy: {
|
||||||
'/api': {
|
'/api': {
|
||||||
target: 'http://localhost:3001',
|
target: 'http://127.0.0.1:3002',
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
proxyTimeout: 120000,
|
proxyTimeout: 120000,
|
||||||
timeout: 120000,
|
timeout: 120000,
|
||||||
},
|
},
|
||||||
'/uploads': {
|
'/uploads': {
|
||||||
target: 'http://localhost:3001',
|
target: 'http://127.0.0.1:3002',
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
Reference in New Issue
Block a user