2022-06-24 23:09:46 +04:00
|
|
|
package handlers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"image/png"
|
|
|
|
"justcaptcha/internal/captcha"
|
|
|
|
"justcaptcha/pkg/server"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
2022-06-26 15:45:42 +04:00
|
|
|
type CaptchaHandlers struct{}
|
2022-06-24 23:09:46 +04:00
|
|
|
|
2022-06-26 15:45:42 +04:00
|
|
|
func New() *CaptchaHandlers {
|
|
|
|
return &CaptchaHandlers{}
|
2022-06-24 23:09:46 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
func (h *CaptchaHandlers) New(w http.ResponseWriter, r *http.Request) {
|
2022-06-26 20:54:15 +04:00
|
|
|
dc := captcha.NewDwellingCaptcha(captcha.GetExpiry())
|
2022-06-24 23:09:46 +04:00
|
|
|
_, id := captcha.New(r.RemoteAddr, dc)
|
|
|
|
|
|
|
|
fmt.Fprint(w, id)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *CaptchaHandlers) Image(w http.ResponseWriter, r *http.Request) {
|
|
|
|
captchaID := captcha.ID(server.GetURLParam(r, "captcha"))
|
|
|
|
|
|
|
|
captchaImage, err := captcha.Image(captchaID)
|
|
|
|
if err != nil {
|
|
|
|
w.WriteHeader(http.StatusNotFound)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if captchaImage == nil {
|
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
w.Header().Add("Content-Disposition", "inline; filename=\""+string(captchaID)+"\"")
|
|
|
|
|
|
|
|
png.Encode(w, *captchaImage)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *CaptchaHandlers) Solve(w http.ResponseWriter, r *http.Request) {
|
|
|
|
r.ParseForm()
|
|
|
|
|
|
|
|
captchaID := captcha.ID(server.GetURLParam(r, "captcha"))
|
|
|
|
answer := captcha.Answer(r.FormValue("answer"))
|
|
|
|
|
|
|
|
ok, err := captcha.Solve(captcha.ID(captchaID), answer)
|
|
|
|
if err != nil {
|
|
|
|
w.WriteHeader(http.StatusNotFound)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if !ok {
|
|
|
|
w.WriteHeader(http.StatusForbidden)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *CaptchaHandlers) IsSolved(w http.ResponseWriter, r *http.Request) {
|
|
|
|
captchaID := captcha.ID(server.GetURLParam(r, "captcha"))
|
|
|
|
|
|
|
|
solved, err := captcha.IsSolved(captchaID)
|
|
|
|
if err != nil {
|
|
|
|
w.WriteHeader(http.StatusNotFound)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if !solved {
|
|
|
|
w.WriteHeader(http.StatusForbidden)
|
|
|
|
}
|
|
|
|
}
|