aboutsummaryrefslogblamecommitdiff
path: root/routes/user.go
blob: 95d571762e92dbaefbcc4949b9365283aa435e8e (plain) (tree)




















































































                                                                                                           
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))
}