1
0

Added CAPTCHA handlers.

This commit is contained in:
Alexander Andreev 2023-02-05 23:05:11 +04:00
parent 685735a576
commit bc37700d9b
Signed by: Arav
GPG Key ID: 0388CC8FAA51063F

View File

@ -1,6 +1,8 @@
package http package http
import ( import (
"fmt"
"image/jpeg"
"math" "math"
"net/http" "net/http"
"strconv" "strconv"
@ -11,6 +13,9 @@ import (
"git.arav.top/Arav/dwelling-home/pkg/servicestat" "git.arav.top/Arav/dwelling-home/pkg/servicestat"
"git.arav.top/Arav/dwelling-home/pkg/util" "git.arav.top/Arav/dwelling-home/pkg/util"
"git.arav.top/Arav/dwelling-home/web" "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" gbsqlite "git.arav.top/Arav/justguestbook/database/sqlite"
"git.arav.top/Arav/justguestbook/guestbook" "git.arav.top/Arav/justguestbook/guestbook"
) )
@ -28,6 +33,8 @@ func NewHandlers(captchaExpire time.Duration, dbPath, gbOwner string, gbPageSize
panic(err) panic(err)
} }
inmemdb.SetExpiry(captchaExpire)
return &Handlers{ return &Handlers{
guestbookDB: gbdb, guestbookDB: gbdb,
captchaExpire: captchaExpire, 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) { func (h *Handlers) NotFound(w http.ResponseWriter, r *http.Request) {
web.NotFound("Not Found", w) 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)
}