sonarqube-badges/router/middlewares/checkAuth.go

33 lines
716 B
Go
Raw Normal View History

2025-03-13 08:25:39 +01:00
package middlewares
import (
"net/http"
2025-03-15 01:49:52 +01:00
"sonarqube-badge/security/jwt"
2025-03-13 08:25:39 +01:00
)
func CheckJwtToken(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tokenCookie, err := r.Cookie("jwt-token")
if err != nil || tokenCookie == nil {
2025-03-15 01:49:52 +01:00
if r.Method == "GET" {
http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
} else {
w.WriteHeader(http.StatusUnauthorized)
}
2025-03-13 08:25:39 +01:00
return
}
2025-03-15 01:49:52 +01:00
_, err = jwt.VerifyToken(tokenCookie.Value, r.Context())
2025-03-13 08:25:39 +01:00
if err != nil {
2025-03-15 01:49:52 +01:00
if r.Method == "GET" {
http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
} else {
w.WriteHeader(http.StatusUnauthorized)
}
2025-03-13 08:25:39 +01:00
return
}
h.ServeHTTP(w, r)
})
}