const express = require('express'); const { login } = require('../auth'); const { TURNSTILE_SECRET_KEY } = require('../config'); const router = express.Router(); const TURNSTILE_VERIFY_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify'; const verifyCaptcha = async (captchaToken, remoteIp) => { if (!TURNSTILE_SECRET_KEY) return true; if (!captchaToken || typeof captchaToken !== 'string') return false; try { const formData = new URLSearchParams({ secret: TURNSTILE_SECRET_KEY, response: captchaToken }); if (remoteIp) { formData.set('remoteip', remoteIp); } const response = await fetch(TURNSTILE_VERIFY_URL, { method: 'POST', body: formData }); if (!response.ok) return false; const result = await response.json(); return result.success === true; } catch (error) { console.error('Captcha verification failed', error); return false; } }; router.post('/login', async (req, res, next) => { const { email, password, captchaToken } = req.body; try { const captchaValid = await verifyCaptcha(captchaToken, req.ip); if (!captchaValid) { res.status(403).json({ error: 'Captcha verification failed' }); return; } const authResult = await login(email, password); if (!authResult) { res.status(401).json({ error: 'Invalid credentials' }); return; } res.json(authResult); } catch (error) { next(error); } }); module.exports = router;