From 1379e8262c235238bf98050818d70f56ba8dd5ed Mon Sep 17 00:00:00 2001 From: Nguyen Marc Date: Wed, 24 Jan 2024 01:29:05 +0100 Subject: [PATCH] refactor(jwr): better middlewares --- jwt/jwt.go | 15 ++++++++++++++- main.go | 1 + 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/jwt/jwt.go b/jwt/jwt.go index 66325f1..3008b43 100644 --- a/jwt/jwt.go +++ b/jwt/jwt.go @@ -116,7 +116,7 @@ func (s Secret) VerifyToken(tokenString string) (*Claims, error) { return nil, fmt.Errorf("invalid token") } -// Middleware is an authentication guard for HTTP servers. +// Middleware is a middleware that inject the JWT in the context for HTTP servers. func (jwt Secret) Middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Get the JWT token from the request header @@ -139,6 +139,19 @@ func (jwt Secret) Middleware(next http.Handler) http.Handler { }) } +// Deny is an authentication guard for HTTP servers. +func Deny(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, ok := GetClaimsFromRequest(r) + if !ok { + http.Error(w, "Unauthorized", http.StatusUnauthorized) + return + } + + next.ServeHTTP(w, r) + }) +} + // GetClaimsFromRequest is a helper function to fetch the JWT session token from an HTTP request. func GetClaimsFromRequest(r *http.Request) (claims Claims, ok bool) { claims, ok = r.Context().Value(claimsContextKey{}).(Claims) diff --git a/main.go b/main.go index 603186d..4693274 100644 --- a/main.go +++ b/main.go @@ -242,6 +242,7 @@ var app = &cli.App{ http.Error(w, err.Error(), http.StatusInternalServerError) } } + r.With(jwt.Deny).Get("/counter", renderFn) r.Get("/*", renderFn) r.Handle("/static/*", http.FileServer(http.FS(static)))