github.com/hellofresh/janus@v0.0.0-20230925145208-ce8de8183c67/pkg/plugin/oauth2/middleware_access_rules.go (about)

     1  package oauth2
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"github.com/hellofresh/janus/pkg/jwt"
     7  	log "github.com/sirupsen/logrus"
     8  )
     9  
    10  // NewRevokeRulesMiddleware creates a new revoke rules middleware
    11  func NewRevokeRulesMiddleware(parser *jwt.Parser, accessRules []*AccessRule) func(http.Handler) http.Handler {
    12  	return func(handler http.Handler) http.Handler {
    13  		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    14  			log.WithField("rules", len(accessRules)).Debug("Starting revoke rules middleware")
    15  
    16  			// If no rules are set then lets not parse the token to avoid performance issues
    17  			if len(accessRules) < 1 {
    18  				handler.ServeHTTP(w, r)
    19  				return
    20  			}
    21  
    22  			token, err := parser.ParseFromRequest(r)
    23  			if err != nil {
    24  				log.WithError(err).Debug("Could not parse the JWT")
    25  				handler.ServeHTTP(w, r)
    26  				return
    27  			}
    28  
    29  			if claims, ok := parser.GetMapClaims(token); ok && token.Valid {
    30  				for _, rule := range accessRules {
    31  					allowed, err := rule.IsAllowed(claims)
    32  					if err != nil {
    33  						log.WithError(err).Debug("Rule is not allowed")
    34  						continue
    35  					}
    36  
    37  					if allowed {
    38  						handler.ServeHTTP(w, r)
    39  					} else {
    40  						w.WriteHeader(http.StatusUnauthorized)
    41  						return
    42  					}
    43  				}
    44  			}
    45  
    46  			handler.ServeHTTP(w, r)
    47  		})
    48  	}
    49  }