28 lines
691 B
Go
28 lines
691 B
Go
|
|
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)
|
||
|
|
})
|
||
|
|
}
|
||
|
|
}
|