aboutsummaryrefslogtreecommitdiff
path: root/pkg/handler/add
diff options
context:
space:
mode:
Diffstat (limited to 'pkg/handler/add')
-rw-r--r--pkg/handler/add/add.go60
-rw-r--r--pkg/handler/add/handler.go21
2 files changed, 81 insertions, 0 deletions
diff --git a/pkg/handler/add/add.go b/pkg/handler/add/add.go
new file mode 100644
index 0000000..dbcce47
--- /dev/null
+++ b/pkg/handler/add/add.go
@@ -0,0 +1,60 @@
+package add
+
+import (
+ "net/http"
+
+ "github.com/labstack/echo/v4"
+ "github.com/ssoda/captcha"
+ "sh.org.ru/pkg/model"
+ "sh.org.ru/pkg/tpl"
+)
+
+func (h *Handler) AddQuote(c echo.Context) error {
+ cid := captcha.New()
+ form := &tpl.AddQuoteForm{
+ CaptchaID: cid,
+ }
+ return tpl.
+ AddQuotePage(form, "").
+ Render(c.Request().Context(), c.Response())
+}
+
+func (h *Handler) AddQuotePost(c echo.Context) error {
+ form := &tpl.AddQuoteForm{}
+ if err := c.Bind(form); err != nil {
+ return err
+ }
+ if form.CaptchaValue == "" {
+ return formError(form, c, "Неверный код")
+ }
+ if !captcha.VerifyString(form.CaptchaID, form.CaptchaValue) {
+ return formError(form, c, "Неверный код")
+ }
+
+ if len(form.Quote) < 10 {
+ return formError(form, c, "Цитата слишком короткая")
+ }
+
+ q := &model.Quote{
+ Quote: form.Quote,
+ Approved: false,
+ Archive: false,
+ }
+ if _, err := h.db.NewInsert().Model(q).Exec(c.Request().Context()); err != nil {
+ return err
+ }
+
+ return c.Redirect(http.StatusFound, "/add/success")
+}
+
+func (h *Handler) AddQuoteSuccess(c echo.Context) error {
+ return tpl.AddQuoteSuccessPage().Render(c.Request().Context(), c.Response())
+}
+
+func formError(form *tpl.AddQuoteForm, c echo.Context, err string) error {
+ form.CaptchaID = captcha.New()
+ form.CaptchaValue = ""
+ return tpl.
+ AddQuotePage(form, err).
+ Render(c.Request().Context(), c.Response())
+}
diff --git a/pkg/handler/add/handler.go b/pkg/handler/add/handler.go
new file mode 100644
index 0000000..8f744ab
--- /dev/null
+++ b/pkg/handler/add/handler.go
@@ -0,0 +1,21 @@
+package add
+
+import (
+ "github.com/labstack/echo/v4"
+ "github.com/uptrace/bun"
+)
+
+type Handler struct {
+ db *bun.DB
+}
+
+// NewHandler returns new Handler.
+func NewHandler(db *bun.DB) *Handler {
+ return &Handler{db: db}
+}
+
+func (h *Handler) Register(g *echo.Group) {
+ g.GET("", h.AddQuote)
+ g.POST("", h.AddQuotePost)
+ g.GET("/success", h.AddQuoteSuccess)
+}