From 8ef42823936fea59f5a47bcd8d1dce0bfd323cdd Mon Sep 17 00:00:00 2001 From: vinchent Date: Tue, 20 Aug 2024 13:21:40 +0200 Subject: [PATCH] Implementing middleware to protect specific routes --- cmd/api/middleware.go | 14 ++++++++++++++ cmd/api/routes-api.go | 7 +++++++ 2 files changed, 21 insertions(+) create mode 100644 cmd/api/middleware.go diff --git a/cmd/api/middleware.go b/cmd/api/middleware.go new file mode 100644 index 0000000..4fda236 --- /dev/null +++ b/cmd/api/middleware.go @@ -0,0 +1,14 @@ +package main + +import "net/http" + +func (app *application) Auth(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, err := app.authenticateToken(r) + if err != nil { + app.invalidCredentials(w) + return + } + next.ServeHTTP(w, r) + }) +} diff --git a/cmd/api/routes-api.go b/cmd/api/routes-api.go index 9e3e079..05744b6 100644 --- a/cmd/api/routes-api.go +++ b/cmd/api/routes-api.go @@ -24,6 +24,13 @@ func (app *application) routes() http.Handler { mux.Post("/api/authenticate", app.CreateAuthToken) mux.Post("/api/is-authenticated", app.CheckAuthentication) + mux.Route("/api/admin", func(mux chi.Router) { + mux.Use(app.Auth) + + mux.Get("/test", func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte("got in")) + }) + }) return mux }