fixed #1
This commit is contained in:
@@ -10,9 +10,18 @@ type contextKey string
|
||||
|
||||
const UserContextKey contextKey = contextKey("user")
|
||||
|
||||
// middleware.go
|
||||
func AuthMiddleware(secret []byte) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// WICHTIG: Wenn der User auf einer öffentlichen Seite ist,
|
||||
// darf die Middleware KEINEN Auth-Zwang ausüben und nicht redirecten!
|
||||
if r.URL.Path == "/login" || r.URL.Path == "/register" || r.URL.Path == "/" {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
tokenStr := ""
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
|
||||
@@ -37,22 +46,25 @@ func AuthMiddleware(secret []byte) func(http.Handler) http.Handler {
|
||||
}
|
||||
|
||||
claims, err := ValidateJWT(tokenStr, secret)
|
||||
|
||||
if err != nil {
|
||||
if strings.HasPrefix(r.URL.Path, "/api/") {
|
||||
http.Error(w, "Invalid token", http.StatusUnauthorized)
|
||||
} else {
|
||||
// Falls das Cookie korrupt oder abgelaufen ist, löschen wir es direkt,
|
||||
// damit das Frontend sauber merkt, dass es weg ist.
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "access_token",
|
||||
Value: "",
|
||||
Path: "/",
|
||||
MaxAge: -1,
|
||||
HttpOnly: false, // Erlaubt JS das Auslesen
|
||||
})
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(
|
||||
r.Context(),
|
||||
UserContextKey,
|
||||
claims,
|
||||
)
|
||||
|
||||
ctx := context.WithValue(r.Context(), UserContextKey, claims)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user