68 lines
1.4 KiB
Go
68 lines
1.4 KiB
Go
package admin
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"net/http"
|
|
)
|
|
|
|
const flashCookieName = "hold_admin_flash"
|
|
|
|
// setFlash sets a flash message cookie
|
|
func setFlash(w http.ResponseWriter, r *http.Request, category, message string) {
|
|
flash := Flash{
|
|
Category: category,
|
|
Message: message,
|
|
}
|
|
|
|
data, err := json.Marshal(flash)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
encoded := base64.URLEncoding.EncodeToString(data)
|
|
secure := r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https"
|
|
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: flashCookieName,
|
|
Value: encoded,
|
|
Path: "/admin",
|
|
MaxAge: 60, // 1 minute - should be consumed on next page load
|
|
HttpOnly: true,
|
|
Secure: secure,
|
|
SameSite: http.SameSiteLaxMode,
|
|
})
|
|
}
|
|
|
|
// getFlash retrieves and clears the flash message
|
|
func getFlash(r *http.Request, ui *AdminUI) *Flash {
|
|
cookie, err := r.Cookie(flashCookieName)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
|
|
data, err := base64.URLEncoding.DecodeString(cookie.Value)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
|
|
var flash Flash
|
|
if err := json.Unmarshal(data, &flash); err != nil {
|
|
return nil
|
|
}
|
|
|
|
return &flash
|
|
}
|
|
|
|
// clearFlash clears the flash cookie (called after displaying)
|
|
func clearFlash(w http.ResponseWriter) {
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: flashCookieName,
|
|
Value: "",
|
|
Path: "/admin",
|
|
MaxAge: -1,
|
|
HttpOnly: true,
|
|
SameSite: http.SameSiteLaxMode,
|
|
})
|
|
}
|