package handlers import ( "fmt" "net/http" "ytdlp-site/database" "ytdlp-site/users" "github.com/labstack/echo/v4" "golang.org/x/crypto/bcrypt" ) func LoginPost(c echo.Context) error { username := c.FormValue("username") password := c.FormValue("password") db := database.Get() var user users.User if err := db.Where("username = ?", username).First(&user).Error; err != nil { return c.String(http.StatusUnauthorized, "Invalid credentials") } if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil { return c.String(http.StatusUnauthorized, "Invalid credentials") } session, err := store.Get(c.Request(), "session") if err != nil { return c.String(http.StatusInternalServerError, "Unable to retrieve session") } session.Values["user_id"] = user.ID err = session.Save(c.Request(), c.Response().Writer) if err != nil { return c.String(http.StatusInternalServerError, "Unable to save session") } session, _ = store.Get(c.Request(), "session") _, ok := session.Values["user_id"] if !ok { return c.String(http.StatusInternalServerError, "user_id was not saved as expected") } fmt.Println("loginPostHandler: redirect to /download") return c.Redirect(http.StatusSeeOther, "/download") } func LoginGet(c echo.Context) error { return c.Render(http.StatusOK, "login.html", nil) } func LogoutGet(c echo.Context) error { session, _ := store.Get(c.Request(), "session") delete(session.Values, "user_id") session.Save(c.Request(), c.Response().Writer) return c.Redirect(http.StatusSeeOther, "/login") }