github.com/hellofresh/janus@v0.0.0-20230925145208-ce8de8183c67/pkg/jwt/middleware.go (about) 1 package jwt 2 3 import ( 4 "net/http" 5 6 "github.com/hellofresh/janus/pkg/render" 7 log "github.com/sirupsen/logrus" 8 ) 9 10 // Payload Represents the context key 11 type Payload struct{} 12 13 // User represents a logged in user 14 type User struct { 15 Username string 16 Email string 17 } 18 19 // Middleware struct contains data and logic required for middleware functionality 20 type Middleware struct { 21 Guard Guard 22 } 23 24 // NewMiddleware builds and returns new JWT middleware instance 25 func NewMiddleware(config Guard) *Middleware { 26 return &Middleware{config} 27 } 28 29 // Handler implementation 30 func (m *Middleware) Handler(handler http.Handler) http.Handler { 31 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 32 parser := Parser{m.Guard.ParserConfig} 33 _, err := parser.ParseFromRequest(r) 34 if err != nil { 35 log.WithError(err).Debug("failed to parse the token") 36 render.JSON(w, http.StatusUnauthorized, "failed to parse the token") 37 return 38 } 39 40 handler.ServeHTTP(w, r) 41 }) 42 }