This commit is contained in:
2026-02-11 17:46:22 +03:00
commit eacfacb13b
266 changed files with 51337 additions and 0 deletions

View File

@@ -0,0 +1,58 @@
package middlewares
import (
"bssapp-backend/auth"
"log"
"net/http"
"strings"
)
var publicPaths = []string{
"/api/auth/login",
"/api/auth/refresh",
"/api/password/forgot",
"/api/password/reset",
}
func GlobalAuthMiddleware(db any, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
// PUBLIC ROUTES
for _, p := range publicPaths {
if strings.HasPrefix(path, p) {
next.ServeHTTP(w, r)
return
}
}
// JWT
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || parts[0] != "Bearer" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
claims, err := auth.ValidateToken(parts[1])
if err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
ctx := auth.WithClaims(r.Context(), claims)
log.Printf("🔐 GLOBAL AUTH user=%d role=%s",
claims.ID,
claims.RoleCode,
)
next.ServeHTTP(w, r.WithContext(ctx))
})
}