First commit

This commit is contained in:
corrado.mulas
2024-11-20 01:39:04 +01:00
parent 1f140e9681
commit 81a5c8bd7d

View File

@@ -3,39 +3,42 @@ package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
)
func validateRecaptcha(token string) (bool, error) {
func validateRecaptcha(captchaToken string) (bool, error) {
secret := os.Getenv("CAPTCHA_SERVER_KEY")
if secret == "" {
return false, errors.New("missing CAPTCHA_SERVER_KEY")
return false, fmt.Errorf("CAPTCHA_SERVER_KEY is not set")
}
url := "https://www.google.com/recaptcha/api/siteverify"
payload := map[string]string{
"secret": secret,
"response": token,
"response": captchaToken,
}
jsonPayload, _ := json.Marshal(payload)
payloadBytes, _ := json.Marshal(payload)
resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonPayload))
resp, err := http.Post(url, "application/json", bytes.NewBuffer(payloadBytes))
if err != nil {
return false, err
return false, fmt.Errorf("reCAPTCHA 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, err
return false, fmt.Errorf("failed to parse reCAPTCHA API response: %v", err)
}
success, ok := result["success"].(bool)
if !ok {
return false, errors.New("invalid reCAPTCHA response format")
if !ok || !success {
if errors, exists := result["error-codes"]; exists {
fmt.Printf("reCAPTCHA error codes: %+v\n", errors)
}
return false, fmt.Errorf("reCAPTCHA validation failed")
}
return success, nil
return true, nil
}