From bc37700d9b5676c4eabd8595a55c2e1422fa4ac4 Mon Sep 17 00:00:00 2001 From: "Alexander \"Arav\" Andreev" Date: Sun, 5 Feb 2023 23:05:11 +0400 Subject: [PATCH] Added CAPTCHA handlers. --- internal/http/handlers.go | 48 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/internal/http/handlers.go b/internal/http/handlers.go index abf8c97..f6c2280 100644 --- a/internal/http/handlers.go +++ b/internal/http/handlers.go @@ -1,6 +1,8 @@ package http import ( + "fmt" + "image/jpeg" "math" "net/http" "strconv" @@ -11,6 +13,9 @@ import ( "git.arav.top/Arav/dwelling-home/pkg/servicestat" "git.arav.top/Arav/dwelling-home/pkg/util" "git.arav.top/Arav/dwelling-home/web" + "git.arav.top/Arav/justcaptcha/pkg/captcha" + "git.arav.top/Arav/justcaptcha/pkg/captcha/inmemdb" + "git.arav.top/Arav/justcaptcha/pkg/dwcaptcha" gbsqlite "git.arav.top/Arav/justguestbook/database/sqlite" "git.arav.top/Arav/justguestbook/guestbook" ) @@ -28,6 +33,8 @@ func NewHandlers(captchaExpire time.Duration, dbPath, gbOwner string, gbPageSize panic(err) } + inmemdb.SetExpiry(captchaExpire) + return &Handlers{ guestbookDB: gbdb, captchaExpire: captchaExpire, @@ -160,3 +167,44 @@ func (h *Handlers) Robots(w http.ResponseWriter, r *http.Request) { func (h *Handlers) NotFound(w http.ResponseWriter, r *http.Request) { web.NotFound("Not Found", w) } + +/**** CAPTCHA *****************************************************************/ + +func (h *Handlers) CaptchaNew(w http.ResponseWriter, r *http.Request) { + dwc := dwcaptcha.NewDwellingCaptcha(h.captchaExpire) + _, id := inmemdb.New(r.RemoteAddr, dwc) + w.WriteHeader(http.StatusCreated) + fmt.Fprint(w, id) +} + +func (h *Handlers) CaptchaImage(w http.ResponseWriter, r *http.Request) { + id := captcha.ID(GetURLParam(r, "id")) + + image := inmemdb.Image(id, r.URL.Query().Get("style")) + if image == nil { + http.Error(w, "image not found", http.StatusNotFound) + return + } + + w.Header().Add("Content-Disposition", "inline; filename=\""+string(id)+"\"") + + jpeg.Encode(w, *image, &jpeg.Options{Quality: 20}) +} + +func (h *Handlers) CaptchaSolve(w http.ResponseWriter, r *http.Request) { + captchaID := captcha.ID(GetURLParam(r, "id")) + isJustRemove := r.URL.Query().Has("remove") + + if isJustRemove { + inmemdb.Remove(captchaID) + w.WriteHeader(http.StatusNoContent) + return + } + + if solved := inmemdb.IsSolved(captchaID); !solved { + http.Error(w, "wrong answer", http.StatusForbidden) + return + } + + w.WriteHeader(http.StatusNoContent) +}