Skip to content

Commit dcb474f

Browse files
authored
Allow custom auth middleware when initializing router (#57)
1 parent 8c0dfcf commit dcb474f

3 files changed

Lines changed: 10 additions & 4 deletions

File tree

cmd/warrant/main.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,6 @@ func main() {
253253
}
254254

255255
log.Debug().Msgf("Listening on port %d", config.Port)
256-
shutdownErr := http.ListenAndServe(fmt.Sprintf(":%d", config.Port), service.NewRouter(&config, "", routes))
256+
shutdownErr := http.ListenAndServe(fmt.Sprintf(":%d", config.Port), service.NewRouter(&config, "", routes, nil))
257257
log.Fatal().Err(shutdownErr).Msg("")
258258
}

pkg/service/auth.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@ type AuthInfo struct {
2828
TenantId string
2929
}
3030

31-
func AuthMiddleware(next http.Handler, config *config.Config, enableSessionAuth bool) http.Handler {
31+
type AuthMiddlewareFunc func(next http.Handler, config *config.Config, enableSessionAuth bool) http.Handler
32+
33+
func DefaultAuthMiddleware(next http.Handler, config *config.Config, enableSessionAuth bool) http.Handler {
3234
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
3335
logger := hlog.FromRequest(r)
3436

pkg/service/router.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ func (rh RouteHandler[T]) ServeHTTP(w http.ResponseWriter, r *http.Request) {
5353
}
5454
}
5555

56-
func NewRouter(config *config.Config, pathPrefix string, routes []Route, additionalMiddlewares ...mux.MiddlewareFunc) *mux.Router {
56+
func NewRouter(config *config.Config, pathPrefix string, routes []Route, authMiddleware AuthMiddlewareFunc, additionalMiddlewares ...mux.MiddlewareFunc) *mux.Router {
5757
router := mux.NewRouter()
5858

5959
// Setup default middleware
@@ -74,6 +74,10 @@ func NewRouter(config *config.Config, pathPrefix string, routes []Route, additio
7474

7575
router.Use(hlog.URLHandler("uri"))
7676

77+
if authMiddleware == nil {
78+
authMiddleware = DefaultAuthMiddleware
79+
}
80+
7781
// Setup supplied middleware
7882
for _, additionalMiddleware := range additionalMiddlewares {
7983
router.Use(additionalMiddleware)
@@ -85,7 +89,7 @@ func NewRouter(config *config.Config, pathPrefix string, routes []Route, additio
8589
if route.DisableAuth || config.ApiKey == "" {
8690
router.Handle(routePattern, route.Handler).Methods(route.Method)
8791
} else {
88-
router.Handle(routePattern, AuthMiddleware(route.Handler, config, route.EnableSessionAuth)).Methods(route.Method)
92+
router.Handle(routePattern, authMiddleware(route.Handler, config, route.EnableSessionAuth)).Methods(route.Method)
8993
}
9094
}
9195

0 commit comments

Comments
 (0)