From 6160b4fdc5f37e4ceaa6b3c5acc855f466049d61 Mon Sep 17 00:00:00 2001 From: Alexander Neonxp Kiryukhin Date: Sun, 6 Oct 2024 17:04:37 +0300 Subject: Первая версия MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkg/handler/add.go | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 pkg/handler/add.go (limited to 'pkg/handler/add.go') diff --git a/pkg/handler/add.go b/pkg/handler/add.go new file mode 100644 index 0000000..a6a5ced --- /dev/null +++ b/pkg/handler/add.go @@ -0,0 +1,60 @@ +package handler + +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()) +} -- cgit v1.2.3