diff options
| author | Elizabeth <elizabeth@simponic.xyz> | 2024-04-03 15:58:44 -0600 |
|---|---|---|
| committer | Elizabeth <elizabeth@simponic.xyz> | 2024-04-03 15:58:44 -0600 |
| commit | 47cc8feefa34f35722719a82456ccd6257903d35 (patch) | |
| tree | 29b2353e15dbc15785ad4c75034c2df32efc9def /api/hcaptcha.go | |
| parent | da6b6011fc8a73af7d0feb32f116e6b10de11b44 (diff) | |
| download | hatecomputers.club-47cc8feefa34f35722719a82456ccd6257903d35.tar.gz hatecomputers.club-47cc8feefa34f35722719a82456ccd6257903d35.zip | |
rename auth redirect login name
Diffstat (limited to 'api/hcaptcha.go')
| -rw-r--r-- | api/hcaptcha.go | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/api/hcaptcha.go b/api/hcaptcha.go new file mode 100644 index 0000000..a310c01 --- /dev/null +++ b/api/hcaptcha.go @@ -0,0 +1,69 @@ +package api + +import ( + "encoding/json" + "fmt" + "net/http" + "strings" +) + +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 +} + +func CaptchaArgsContinuation(context *RequestContext, req *http.Request, resp http.ResponseWriter) ContinuationChain { + return func(success Continuation, failure Continuation) ContinuationChain { + (*context.TemplateData)["HcaptchaArgs"] = HcaptchaArgs{ + SiteKey: context.Args.HcaptchaSiteKey, + } + return success(context, req, resp) + } +} + +func CaptchaVerificationContinuation(context *RequestContext, req *http.Request, resp http.ResponseWriter) ContinuationChain { + return func(success Continuation, failure Continuation) ContinuationChain { + hCaptchaResponse := req.FormValue("h-captcha-response") + secretKey := context.Args.HcaptchaSecret + + err := verifyCaptcha(secretKey, hCaptchaResponse) + if err != nil { + (*context.TemplateData)["FormError"] = FormError{ + Errors: []string{"hCaptcha verification failed"}, + } + resp.WriteHeader(http.StatusBadRequest) + + return failure(context, req, resp) + } + + return success(context, req, resp) + } +} |
