2023-05-23 04:36:04 +04:00
|
|
|
package http
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"image/jpeg"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
|
2023-05-27 20:56:32 +04:00
|
|
|
"git.arav.su/Arav/httpr"
|
2023-08-12 22:58:54 +04:00
|
|
|
captcha "git.arav.su/Arav/justcaptcha/v2"
|
|
|
|
"git.arav.su/Arav/justcaptcha/v2/dwcaptcha"
|
|
|
|
"git.arav.su/Arav/justcaptcha/v2/inmemdb"
|
2023-05-23 04:36:04 +04:00
|
|
|
)
|
|
|
|
|
|
|
|
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) {
|
2023-05-27 20:56:32 +04:00
|
|
|
captchaID := captcha.ID(httpr.Param(r, "id"))
|
2023-05-23 04:36:04 +04:00
|
|
|
|
|
|
|
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) {
|
2023-05-27 20:56:32 +04:00
|
|
|
id := captcha.ID(httpr.Param(r, "id"))
|
2023-05-23 04:36:04 +04:00
|
|
|
|
|
|
|
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})
|
|
|
|
}
|