feat: refactor for using app config

This commit is contained in:
2025-05-25 16:22:28 +02:00
parent b95dcc6230
commit 07b9b94143
10 changed files with 120 additions and 153 deletions

View File

@ -7,34 +7,37 @@ import (
"strings"
"gitea.local/admin/hspguard/internal/auth"
"gitea.local/admin/hspguard/internal/config"
"gitea.local/admin/hspguard/internal/types"
"gitea.local/admin/hspguard/internal/web"
)
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
web.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
func AuthMiddleware(cfg *config.AppConfig) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
web.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
parts := strings.Split(authHeader, "Bearer ")
if len(parts) != 2 {
web.Error(w, "invalid auth header format", http.StatusUnauthorized)
return
}
parts := strings.Split(authHeader, "Bearer ")
if len(parts) != 2 {
web.Error(w, "invalid auth header format", http.StatusUnauthorized)
return
}
tokenStr := parts[1]
token, userClaims, err := auth.VerifyToken(tokenStr)
if err != nil || !token.Valid {
http.Error(w, fmt.Sprintf("invalid token: %v", err), http.StatusUnauthorized)
return
}
tokenStr := parts[1]
token, userClaims, err := auth.VerifyToken(tokenStr, cfg.Jwt.PublicKey)
if err != nil || !token.Valid {
http.Error(w, fmt.Sprintf("invalid token: %v", err), http.StatusUnauthorized)
return
}
ctx := context.WithValue(r.Context(), types.UserIdKey, userClaims.Subject)
next.ServeHTTP(w, r.WithContext(ctx))
})
ctx := context.WithValue(r.Context(), types.UserIdKey, userClaims.Subject)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
func WithSkipper(mw func(http.Handler) http.Handler, excludedPaths ...string) func(http.Handler) http.Handler {