Implementing middleware to protect specific routes

This commit is contained in:
vinchent 2024-08-20 13:21:40 +02:00
parent 1fce6f6a48
commit 8ef4282393
2 changed files with 21 additions and 0 deletions

14
cmd/api/middleware.go Normal file
View File

@ -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)
})
}

View File

@ -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
}