74 lines
1.6 KiB
Go
74 lines
1.6 KiB
Go
package ui
|
|
|
|
import (
|
|
"net/http"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"git.lohmar.co.uk/lexton-it/NextWks/core/auth"
|
|
"git.lohmar.co.uk/lexton-it/NextWks/core/i18n"
|
|
)
|
|
|
|
// PageCtx holds page-level data passed to templates.
|
|
type PageCtx struct {
|
|
UserID string
|
|
Role string
|
|
Locale i18n.T
|
|
}
|
|
|
|
type Handler struct {
|
|
appDir string
|
|
defaultLang string
|
|
}
|
|
|
|
func NewHandler(appDir string, defaultLang string) *Handler {
|
|
return &Handler{appDir: appDir, defaultLang: defaultLang}
|
|
}
|
|
|
|
func (h *Handler) RegisterRoutes(mux *http.ServeMux, authGate func(http.Handler) http.Handler) {
|
|
staticDir := filepath.Join(h.appDir, "static")
|
|
mux.Handle("GET /static/", http.StripPrefix("/static", http.FileServer(http.Dir(staticDir))))
|
|
mux.Handle("GET /", authGate(http.HandlerFunc(h.launcherPage)))
|
|
}
|
|
|
|
func (h *Handler) launcherPage(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path != "/" {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
|
|
ctx := h.getContext(r)
|
|
apps := DefaultApps(ctx.Role)
|
|
component := LauncherPage(ctx, apps)
|
|
component.Render(r.Context(), w)
|
|
}
|
|
|
|
func (h *Handler) getContext(r *http.Request) PageCtx {
|
|
userID, _ := auth.GetUserID(r)
|
|
role, _ := r.Context().Value(auth.ContextRole).(string)
|
|
if role == "" {
|
|
role = "user"
|
|
}
|
|
|
|
// Detect language: cookie > header > config default
|
|
lang := h.defaultLang
|
|
if lang == "" {
|
|
lang = "en"
|
|
}
|
|
if cookie, err := r.Cookie("lang"); err == nil {
|
|
lang = cookie.Value
|
|
} else if al := r.Header.Get("Accept-Language"); al != "" {
|
|
for _, l := range i18n.Supported() {
|
|
if strings.HasPrefix(al, l) {
|
|
lang = l
|
|
break
|
|
}
|
|
}
|
|
}
|
|
|
|
return PageCtx{
|
|
UserID: userID,
|
|
Role: role,
|
|
Locale: i18n.Get(lang),
|
|
}
|
|
}
|