2026-02-06 17:35:29 +01:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
|
|
"github.com/gorilla/sessions"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func RequireAuth(store *sessions.CookieStore) func(http.Handler) http.Handler {
|
|
|
|
|
return func(next http.Handler) http.Handler {
|
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
session, _ := store.Get(r, "erp-session")
|
|
|
|
|
userID, ok := session.Values["user_id"]
|
|
|
|
|
if !ok || userID == nil {
|
|
|
|
|
// Check if this is an HTMX request
|
|
|
|
|
if r.Header.Get("HX-Request") == "true" {
|
|
|
|
|
w.Header().Set("HX-Redirect", "/login")
|
|
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-02-08 14:20:18 +01:00
|
|
|
|
|
|
|
|
func RequireAdmin(store *sessions.CookieStore) func(http.Handler) http.Handler {
|
|
|
|
|
return func(next http.Handler) http.Handler {
|
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
session, _ := store.Get(r, "erp-session")
|
|
|
|
|
role, ok := session.Values["role"].(string)
|
|
|
|
|
if !ok || role != "admin" {
|
|
|
|
|
http.Error(w, "Forbidden", http.StatusForbidden)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|