feat(auth): Add authentication middleware

This commit is contained in:
Björn Benouarets
2026-02-06 00:08:27 +01:00
parent fb35450880
commit 78da787f43
5 changed files with 672 additions and 121 deletions

View File

@@ -5,6 +5,7 @@ import (
"strings"
"git.secnex.io/secnex/api-gateway/config"
"git.secnex.io/secnex/api-gateway/middlewares"
"git.secnex.io/secnex/masterlog"
"github.com/go-chi/chi/v5"
)
@@ -17,6 +18,7 @@ type Route struct {
ID string
Path string
StripPrefix config.StripPrefix
Security config.Security
Api *Api
}
@@ -27,6 +29,7 @@ func NewRoutes(cfg *config.Configuration, apis Apis) *Routes {
ID: route.ID,
Path: route.Path,
StripPrefix: route.StripPrefix,
Security: route.Security,
Api: apis[route.Api],
})
}
@@ -36,9 +39,13 @@ func NewRoutes(cfg *config.Configuration, apis Apis) *Routes {
func (rs *Routes) Register(r *chi.Mux) {
for _, route := range rs.routes {
masterlog.Info("Registering route", map[string]interface{}{
"id": route.ID,
"path": route.Path,
"api": route.Api.ID,
"id": route.ID,
"path": route.Path,
"api": route.Api.ID,
"auth_enabled": route.Security.Auth.Enabled,
"auth_header": route.Security.Auth.Header,
"auth_include": route.Security.Auth.Path.Include,
"auth_exclude": route.Security.Auth.Path.Exclude,
})
handler := route.createHandler()
@@ -47,9 +54,29 @@ func (rs *Routes) Register(r *chi.Mux) {
}
func (r *Route) createHandler() http.Handler {
// Start with the API (proxy) handler
handler := http.Handler(r.Api)
// Apply middlewares in reverse order (last one wraps first)
// 1. Auth middleware (if enabled)
if r.Security.Auth.Enabled {
masterlog.Debug("Route: Applying Auth middleware", map[string]interface{}{
"path": r.Path,
"header": r.Security.Auth.Header,
})
handler = middlewares.NewAuthMiddleware(
r.Security.Auth.Header,
r.Security.Auth.Path,
handler,
)
}
// 2. Strip prefix middleware (if enabled)
if r.StripPrefix.Enabled {
masterlog.Debug("Route: Applying StripPrefix middleware", map[string]interface{}{
"path": r.Path,
"prefix": r.StripPrefix.Prefix,
})
handler = newStripPrefixMiddleware(r.StripPrefix.Prefix, handler)
}