diff options
Diffstat (limited to 'routes/user.go')
-rw-r--r-- | routes/user.go | 85 |
1 files changed, 85 insertions, 0 deletions
diff --git a/routes/user.go b/routes/user.go new file mode 100644 index 0000000..95d5717 --- /dev/null +++ b/routes/user.go @@ -0,0 +1,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)) +} |