Add Turnstile captcha to login
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 2m57s
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 2m57s
This commit is contained in:
@@ -1,12 +1,49 @@
|
||||
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';
|
||||
|
||||
router.post('/login', async (req, res, next) => {
|
||||
const { email, password } = req.body;
|
||||
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) {
|
||||
|
||||
Reference in New Issue
Block a user