hatecomputers.club/api/hcaptcha/hcaptcha.go

76 lines
1.9 KiB
Go
Raw Permalink Normal View History

2024-04-03 19:53:50 -04:00
package hcaptcha
2024-04-03 17:58:44 -04:00
import (
"encoding/json"
"fmt"
"net/http"
"strings"
2024-04-03 19:53:50 -04:00
"git.hatecomputers.club/hatecomputers/hatecomputers.club/api/types"
2024-04-03 17:58:44 -04:00
)
2024-04-03 19:53:50 -04:00
type HcaptchaArgs struct {
SiteKey string
}
2024-04-03 17:58:44 -04:00
func verifyCaptcha(secret, response string) error {
verifyURL := "https://hcaptcha.com/siteverify"
body := strings.NewReader("secret=" + secret + "&response=" + response)
req, err := http.NewRequest("POST", verifyURL, body)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
jsonResponse := struct {
Success bool `json:"success"`
}{}
err = json.NewDecoder(resp.Body).Decode(&jsonResponse)
if err != nil {
return err
}
if !jsonResponse.Success {
return fmt.Errorf("hcaptcha verification failed")
}
defer resp.Body.Close()
return nil
}
2024-04-03 19:53:50 -04:00
func CaptchaArgsContinuation(context *types.RequestContext, req *http.Request, resp http.ResponseWriter) types.ContinuationChain {
return func(success types.Continuation, failure types.Continuation) types.ContinuationChain {
2024-04-03 17:58:44 -04:00
(*context.TemplateData)["HcaptchaArgs"] = HcaptchaArgs{
SiteKey: context.Args.HcaptchaSiteKey,
}
return success(context, req, resp)
}
}
2024-04-03 19:53:50 -04:00
func CaptchaVerificationContinuation(context *types.RequestContext, req *http.Request, resp http.ResponseWriter) types.ContinuationChain {
return func(success types.Continuation, failure types.Continuation) types.ContinuationChain {
2024-04-03 17:58:44 -04:00
hCaptchaResponse := req.FormValue("h-captcha-response")
secretKey := context.Args.HcaptchaSecret
err := verifyCaptcha(secretKey, hCaptchaResponse)
if err != nil {
(*context.TemplateData)["Error"] = types.BannerMessages{
Messages: []string{"hCaptcha verification failed"},
2024-04-03 17:58:44 -04:00
}
resp.WriteHeader(http.StatusBadRequest)
return failure(context, req, resp)
}
return success(context, req, resp)
}
}