1
0
dwelling-home/internal/http/api_captcha_handlers.go

60 lines
1.4 KiB
Go

package http
import (
"fmt"
"image/jpeg"
"net/http"
"time"
"git.arav.su/Arav/justcaptcha/pkg/captcha"
"git.arav.su/Arav/justcaptcha/pkg/captcha/inmemdb"
"git.arav.su/Arav/justcaptcha/pkg/dwcaptcha"
)
type CaptchaApiHandlers struct {
Expiry time.Duration
}
func NewCaptchaApiHandlers(expiry time.Duration) *CaptchaApiHandlers {
inmemdb.SetExpiry(expiry)
return &CaptchaApiHandlers{Expiry: expiry}
}
func (h *CaptchaApiHandlers) New(w http.ResponseWriter, r *http.Request) {
dwc := dwcaptcha.NewDwellingCaptcha(h.Expiry)
_, id := inmemdb.New(r.RemoteAddr, dwc)
w.WriteHeader(http.StatusCreated)
fmt.Fprint(w, id)
}
func (h *CaptchaApiHandlers) Solve(w http.ResponseWriter, r *http.Request) {
captchaID := captcha.ID(GetURLParam(r, "id"))
if r.URL.Query().Has("remove") {
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)
}
func (h *CaptchaApiHandlers) Image(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})
}