Files
overleaf-registration-be/recaptcha.go
corrado.mulas 3a9065d37e First commit
2024-11-20 02:37:15 +01:00

47 lines
1.1 KiB
Go

package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
)
func validateRecaptcha(token string) (bool, error) {
log.Printf("Validating Turnstile token: %s", token)
secret := os.Getenv("TURNSTILE_SECRET_KEY")
if secret == "" {
return false, fmt.Errorf("TURNSTILE_SECRET_KEY is not set")
}
url := "https://challenges.cloudflare.com/turnstile/v0/siteverify"
payload := map[string]string{
"secret": secret,
"response": token,
}
payloadBytes, _ := json.Marshal(payload)
resp, err := http.Post(url, "application/json", bytes.NewBuffer(payloadBytes))
if err != nil {
return false, fmt.Errorf("Turnstile API request failed: %v", err)
}
defer resp.Body.Close()
var result map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return false, fmt.Errorf("Failed to parse Turnstile API response: %v", err)
}
success, ok := result["success"].(bool)
if !ok || !success {
if errors, exists := result["error-codes"]; exists {
return false, fmt.Errorf("Turnstile validation failed: %v", errors)
}
return false, fmt.Errorf("Turnstile validation failed")
}
return true, nil
}