1
0
Fork 0
forked from 0x2E/fusion
fusion/api/session.go
Michael Lynch 64b071b47a Use a constant for the session key name
We're using a 'magic string' for the echo session key name, which makes it easy for the different instances of the string to go out of sync. Using a named constant makes the intent clear and ensures all copies of the key name in the code stay in sync.
2024-12-27 05:23:43 -05:00

68 lines
1.4 KiB
Go

package api
import (
"net/http"
"github.com/0x2e/fusion/conf"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
)
type Session struct{}
const sessionKeyName = "fusion-client-session"
func (s Session) Create(c echo.Context) error {
var req struct {
Password string `json:"password" validate:"required"`
}
if err := bindAndValidate(&req, c); err != nil {
return err
}
if req.Password != conf.Conf.Password {
return echo.NewHTTPError(http.StatusUnauthorized, "Wrong password")
}
sess, _ := session.Get(sessionKeyName, c)
if !conf.Conf.SecureCookie {
sess.Options.Secure = false
sess.Options.SameSite = http.SameSiteDefaultMode
}
sess.Values["password"] = conf.Conf.Password
if err := sess.Save(c.Request(), c.Response()); err != nil {
return c.NoContent(http.StatusInternalServerError)
}
return c.NoContent(http.StatusCreated)
}
func (s Session) Check(c echo.Context) (bool, error) {
sess, err := session.Get(sessionKeyName, c)
if err != nil {
return false, err
}
v, ok := sess.Values["password"]
if !ok {
return false, nil
}
return v == conf.Conf.Password, nil
}
func (s Session) Delete(c echo.Context) error {
sess, err := session.Get(sessionKeyName, c)
if err != nil {
return err
}
sess.Values["password"] = ""
sess.Options.MaxAge = -1
if err := sess.Save(c.Request(), c.Response()); err != nil {
return c.NoContent(http.StatusInternalServerError)
}
return c.NoContent(http.StatusNoContent)
}