Captcha Gateway

This commit is contained in:
2025-03-22 19:48:19 +08:00
parent ba1d96b118
commit 62dcbbf424
14 changed files with 474 additions and 5 deletions

View File

@ -0,0 +1,33 @@
package captcha
import (
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
)
type TemplateData struct {
ApiKey string `json:"api_key"`
}
func GetTemplateData() TemplateData {
return TemplateData{
ApiKey: viper.GetString("captcha.api_key"),
}
}
type CaptchaAdapter interface {
Validate(token, ip string) bool
}
var adapters = map[string]CaptchaAdapter{
"turnstile": &TurnstileAdapter{},
}
func Validate(token, ip string) bool {
provider := viper.GetString("captcha.provider")
if adapter, ok := adapters[provider]; ok {
return adapter.Validate(token, ip)
}
log.Error().Msg("Unable to handle captcha validate request due to unsupported provider.")
return false
}

View File

@ -0,0 +1,46 @@
package captcha
import (
"bytes"
"encoding/json"
"net/http"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
)
type TurnstileAdapter struct{}
type turnstileResponse struct {
Success bool `json:"success"`
ErrorCodes []string `json:"error-codes"`
}
func (a *TurnstileAdapter) Validate(token, ip string) bool {
url := "https://challenges.cloudflare.com/turnstile/v0/siteverify"
data := map[string]string{
"secret": viper.GetString("captcha.api_secret"),
"response": token,
"remoteip": ip,
}
jsonData, _ := json.Marshal(data)
resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
if err != nil {
log.Error().Err(err).Msg("Error sending request to Turnstile...")
return false
}
defer resp.Body.Close()
var result turnstileResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
log.Error().Err(err).Msg("Error decoding response from Turnstile...")
return false
}
if !result.Success {
log.Warn().Strs("errors", result.ErrorCodes).Msg("An captcha validation request failed...")
}
return result.Success
}