diff options
Diffstat (limited to 'pkg/handler/admin/admin.go')
-rw-r--r-- | pkg/handler/admin/admin.go | 101 |
1 files changed, 101 insertions, 0 deletions
diff --git a/pkg/handler/admin/admin.go b/pkg/handler/admin/admin.go new file mode 100644 index 0000000..494da05 --- /dev/null +++ b/pkg/handler/admin/admin.go @@ -0,0 +1,101 @@ +package admin + +import ( + "net/http" + + "github.com/labstack/echo/v4" + "github.com/labstack/echo/v4/middleware" + "github.com/uptrace/bun" + "sh.org.ru/pkg/config" + "sh.org.ru/pkg/model" + "sh.org.ru/pkg/tpl" +) + +type Handler struct { + db *bun.DB + cfg *config.Config +} + +// NewHandler returns new Handler. +func NewHandler(db *bun.DB, cfg *config.Config) *Handler { + return &Handler{ + db: db, + cfg: cfg, + } +} + +func (h *Handler) Register(g *echo.Group) { + g.Use(middleware.BasicAuth(func(u, p string, ctx echo.Context) (bool, error) { + return h.cfg.Admins[u] == p, nil + })) + + g.GET("/", h.Admin) + g.POST("/action", h.AdminAction) + g.GET("/export", h.AdminExport) +} + +func (h *Handler) Admin(c echo.Context) error { + quotes := make([]model.Quote, 0, 20) + count, err := h.db.NewSelect(). + Model((*model.Quote)(nil)). + Order("id ASC"). + Where("approved = ?", false). + ScanAndCount(c.Request().Context(), "es) + if err != nil { + return err + } + + return tpl.Admin(quotes, count).Render(c.Request().Context(), c.Response()) +} + +func (h *Handler) AdminAction(c echo.Context) error { + form := new(tpl.AdminForm) + if err := c.Bind(form); err != nil { + return err + } + + switch form.Action { + case "approve": + _, err := h.db.NewUpdate(). + Model(&model.Quote{ + ID: int64(form.ID), + Approved: true, + }). + Column("approved"). + WherePK("id"). + Exec(c.Request().Context()) + if err != nil { + return err + } + case "decline": + _, err := h.db.NewDelete(). + Model(&model.Quote{ + ID: int64(form.ID), + }). + WherePK("id"). + Exec(c.Request().Context()) + if err != nil { + return err + } + } + + return c.Redirect(http.StatusFound, "/admin/") +} + +func (h *Handler) AdminExport(c echo.Context) error { + quotes := []model.Quote{} + err := h.db.NewSelect(). + Model((*model.Quote)(nil)). + Order("id ASC"). + Scan(c.Request().Context(), "es) + if err != nil { + return err + } + + quotesString := make([]string, 0, len(quotes)) + for _, q := range quotes { + quotesString = append(quotesString, q.Quote) + } + + return c.JSON(http.StatusOK, quotesString) +} |