Skip to content

Commit

Permalink
refactor(jwr): better middlewares
Browse files Browse the repository at this point in the history
  • Loading branch information
Darkness4 committed Jan 24, 2024
1 parent 60c5e59 commit 1379e82
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
15 changes: 14 additions & 1 deletion jwt/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)))

Expand Down

0 comments on commit 1379e82

Please sign in to comment.