package user import ( "github.com/gorilla/sessions" . "github.com/labstack/echo/v4" "net/http" "os" "todo/crud" . "todo/html_components" ) // GENERATED FILE // DO NOT EDIT const cookieMaxAge = 60 * 60 * 24 type UserLogin struct { e *Echo repo *UserRepository cookieStore *sessions.CookieStore html *GoHtmlHandler } func NewUserLogin(e *Echo, repo *UserRepository, html *GoHtmlHandler) *UserLogin { store := sessions.NewCookieStore([]byte(os.Getenv("SESSION_SECRET"))) isLocal := os.Getenv("IS_LOCAL") == "true" if isLocal { store.Options.Secure = false store.Options.SameSite = http.SameSiteLaxMode } store.Options.HttpOnly = true store.MaxAge(cookieMaxAge) return &UserLogin{e: e, repo: repo, cookieStore: store, html: html} } func (u *UserLogin) AddLoginRoute() { u.e.GET("/login", func(c Context) error { return u.html.RenderPage(c, "login", EmailLogin{}) }) u.e.POST("/login", func(c Context) error { email := c.FormValue("email") password := c.FormValue("password") crud.Debug("login request received for email: ", email) success, userId, err := u.repo.VerifyPassword(email, password) if err != nil { crud.Error("error while verifying password: ", err) return u.returnLoginFailed(c) } crud.Debug("login success: ", success) if !success { return u.returnLoginFailed(c) } err = u.createSession(c, email, userId) if err != nil { crud.Error("error while creating session: ", err) return u.returnLoginFailed(c) } c.Response().Header().Set("HX-Redirect", "/") return nil }) } func (u *UserLogin) createSession(c Context, email string, userId int) error { s, err := u.cookieStore.New(c.Request(), "session") if err != nil { return err } s.Values["email"] = email s.Values["userId"] = userId return s.Save(c.Request(), c.Response()) } func (u *UserLogin) returnLoginFailed(c Context) error { return u.html.RenderComponent(c, "emailLogin", EmailLogin{ ShowError: true, Error: "Could not authenticate the user", }) } func (u *UserLogin) IsSessionAuthenticated(c Context) bool { session, err := u.cookieStore.Get(c.Request(), "session") if err != nil { return false } email, ok := session.Values["email"].(string) if !ok { return false } id, ok := session.Values["userId"].(int) if !ok { return false } c.Set("user", email) c.Set("userId", id) return id > -1 }