First commit

This commit is contained in:
corrado.mulas
2024-11-20 03:03:09 +01:00
parent 0ceca43b23
commit 1e9dbb2b82
2 changed files with 27 additions and 57 deletions

View File

@@ -1,7 +1,6 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
@@ -10,37 +9,36 @@ import (
)
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)
log.Printf("Validating CAPTCHA token: %s", token)
resp, err := http.Post(url, "application/json", bytes.NewBuffer(payloadBytes))
url := "https://challenges.cloudflare.com/turnstile/v0/siteverify"
data := map[string][]string{
"secret": {secret},
"response": {token},
}
resp, err := http.PostForm(url, data)
if err != nil {
return false, fmt.Errorf("Turnstile API request failed: %v", err)
return false, fmt.Errorf("failed to verify CAPTCHA: %v", err)
}
defer resp.Body.Close()
var result map[string]interface{}
if resp.StatusCode != http.StatusOK {
return false, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
var result struct {
Success bool `json:"success"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return false, fmt.Errorf("Failed to parse Turnstile API response: %v", err)
return false, fmt.Errorf("failed to decode CAPTCHA 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
log.Printf("CAPTCHA validation result: %v", result.Success)
return result.Success, nil
}