aboutsummaryrefslogtreecommitdiff
path: root/routes/user.go
blob: 95d571762e92dbaefbcc4949b9365283aa435e8e (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package routes

import (
	"log"
	"net/http"

	"github.com/gorilla/sessions"
	"github.com/labstack/echo-contrib/session"
	"github.com/labstack/echo/v4"
	"gitrepo.ru/neonxp/gorum/utils"
	"gitrepo.ru/neonxp/gorum/views"
)

func (r *Router) Login(c echo.Context) error {
	req := new(loginRequest)
	if err := c.Bind(req); err != nil {
		return err
	}
	if c.Request().Method == http.MethodPost {
		u, err := r.userRepo.Login(c.Request().Context(), req.Email, req.Password)
		if err != nil {
			return err
		}
		sess, err := session.Get("session", c)
		if err != nil {
			return err
		}
		maxAge := 0
		if req.Remember == "on" {
			maxAge = 86400 * 14
		}
		sess.Options = &sessions.Options{
			Path:     "/",
			MaxAge:   maxAge,
			HttpOnly: true,
		}
		sess.Values["user"] = *u
		if err := sess.Save(c.Request(), c.Response()); err != nil {
			return err
		}

		return c.Redirect(302, "/")
	}

	return utils.Render(c, views.Login(req.Email))
}

func (r *Router) Logout(c echo.Context) error {
	sess, err := session.Get("session", c)
	if err != nil {
		return err
	}
	sess.Options = &sessions.Options{
		Path:     "/",
		MaxAge:   -1,
		HttpOnly: true,
	}
	sess.Values["user"] = nil
	if err := sess.Save(c.Request(), c.Response()); err != nil {
		return err
	}
	if err := sess.Save(c.Request(), c.Response()); err != nil {
		return err
	}

	return c.Redirect(302, "/")
}

func (r *Router) Register(c echo.Context) error {
	req := new(registerRequest)
	if err := c.Bind(req); err != nil {
		return err
	}
	if c.Request().Method == http.MethodPost {
		uid, err := r.userRepo.Create(c.Request().Context(), req.Email, req.Password, req.Username)
		if err != nil {
			return err
		}
		log.Println(uid)

		return c.Redirect(302, "/login")
	}

	return utils.Render(c, views.Register(req.Username, req.Email))
}