aboutsummaryrefslogtreecommitdiff
path: root/pkg/handler/user/login.go
blob: b3fbdbf2547d8a439c47b9d70d34f61599f1d488 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package user

import (
	"net/http"

	"github.com/labstack/echo/v4"

	"go.neonxp.ru/framework/pkg/tpl"
	"go.neonxp.ru/framework/pkg/utils"
)

const oneyear = 86400 * 365

func (h *Handler) LoginForm(c echo.Context) error {
	form := &tpl.LoginForm{}
	if err := c.Bind(form); err != nil {
		return err
	}

	if c.Request().Method == http.MethodPost {
		err := h.doLogin(c, form)
		if err == nil {
			if utils.IsHTMX(c) {
				utils.HTMXRedirect(c, "/")
				return c.NoContent(http.StatusNoContent)
			}

			return c.Redirect(http.StatusFound, "/")
		}

		form.Message = UserErrors.Get(err)
		if form.Message == "" {
			return err
		}
	}

	return tpl.Login(form).
		Render(c.Request().Context(), c.Response())
}

func (h *Handler) doLogin(c echo.Context, form *tpl.LoginForm) error {
	u, err := h.user.Login(c.Request().Context(), form)
	if err != nil {
		return err
	}

	maxage := 0
	if form.Remember == "on" {
		maxage = oneyear
	}

	return utils.SetUser(c, u, maxage)
}