2025-01-27 03:23:54 +00:00
|
|
|
package handlers
|
|
|
|
|
|
|
|
import (
|
2025-01-31 23:56:59 +00:00
|
|
|
"encoding/json"
|
2025-01-31 22:42:32 +00:00
|
|
|
"errors"
|
2025-01-27 03:23:54 +00:00
|
|
|
"github.com/gofiber/fiber/v2"
|
2025-01-27 10:48:40 +00:00
|
|
|
"lmika.dev/lmika/hugo-cms/models"
|
2025-01-31 23:56:59 +00:00
|
|
|
"log"
|
2025-01-27 03:23:54 +00:00
|
|
|
)
|
|
|
|
|
2025-01-31 22:42:32 +00:00
|
|
|
func GetUser(c *fiber.Ctx) models.User {
|
|
|
|
u, ok := c.Locals("user").(models.User)
|
|
|
|
if !ok {
|
|
|
|
panic(errors.New("user not found in context"))
|
|
|
|
}
|
|
|
|
return u
|
|
|
|
}
|
2025-01-27 03:23:54 +00:00
|
|
|
|
|
|
|
func GetSite(c *fiber.Ctx) models.Site {
|
2025-01-31 22:42:32 +00:00
|
|
|
s, ok := c.Locals("site").(models.Site)
|
|
|
|
if !ok {
|
|
|
|
panic(errors.New("no site in context"))
|
|
|
|
}
|
|
|
|
return s
|
2025-01-27 03:23:54 +00:00
|
|
|
}
|
2025-01-31 23:56:59 +00:00
|
|
|
|
|
|
|
func UpdatePrefCookie(c *fiber.Ctx, update func(prefs *models.PrefCookie)) {
|
|
|
|
cookie := GetPrefCookie(c)
|
|
|
|
update(&cookie)
|
|
|
|
setPrefCookie(c, cookie)
|
|
|
|
}
|
|
|
|
|
|
|
|
func GetPrefCookie(c *fiber.Ctx) models.PrefCookie {
|
|
|
|
prefCookieValue := c.Cookies(models.PrefCookieName)
|
|
|
|
if prefCookieValue == "" {
|
|
|
|
return models.PrefCookie{}
|
|
|
|
}
|
|
|
|
|
|
|
|
var prefCookie models.PrefCookie
|
|
|
|
err := json.Unmarshal([]byte(prefCookieValue), &prefCookie)
|
|
|
|
if err != nil {
|
|
|
|
return models.PrefCookie{}
|
|
|
|
}
|
|
|
|
|
|
|
|
return prefCookie
|
|
|
|
}
|
|
|
|
|
|
|
|
func setPrefCookie(c *fiber.Ctx, prefCookie models.PrefCookie) {
|
|
|
|
if prefJson, err := json.Marshal(prefCookie); err == nil {
|
|
|
|
c.Cookie(&fiber.Cookie{
|
|
|
|
Name: models.PrefCookieName,
|
|
|
|
Value: string(prefJson),
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
log.Printf("unable to save pref cookie: %v", err)
|
|
|
|
}
|
|
|
|
}
|