github.com/Tyktechnologies/tyk@v2.9.5+incompatible/gateway/mw_granular_access.go (about) 1 package gateway 2 3 import ( 4 "errors" 5 "net/http" 6 7 "github.com/TykTechnologies/tyk/regexp" 8 ) 9 10 // GranularAccessMiddleware will check if a URL is specifically enabled for the key 11 type GranularAccessMiddleware struct { 12 BaseMiddleware 13 } 14 15 func (m *GranularAccessMiddleware) Name() string { 16 return "GranularAccessMiddleware" 17 } 18 19 // ProcessRequest will run any checks on the request on the way through the system, return an error to have the chain fail 20 func (m *GranularAccessMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int) { 21 if ctxGetRequestStatus(r) == StatusOkAndIgnore { 22 return nil, http.StatusOK 23 } 24 25 logger := m.Logger() 26 session := ctxGetSession(r) 27 28 sessionVersionData, foundAPI := session.GetAccessRightByAPIID(m.Spec.APIID) 29 if !foundAPI { 30 return nil, http.StatusOK 31 } 32 33 if len(sessionVersionData.AllowedURLs) == 0 { 34 return nil, http.StatusOK 35 } 36 37 for _, accessSpec := range sessionVersionData.AllowedURLs { 38 logger.Debug("Checking: ", r.URL.Path, " Against:", accessSpec.URL) 39 asRegex, err := regexp.Compile(accessSpec.URL) 40 if err != nil { 41 logger.WithError(err).Error("Regex error") 42 return nil, http.StatusOK 43 } 44 45 match := asRegex.MatchString(r.URL.Path) 46 if match { 47 logger.Debug("Match!") 48 for _, method := range accessSpec.Methods { 49 if method == r.Method { 50 return nil, http.StatusOK 51 } 52 } 53 } 54 } 55 56 logger.Info("Attempted access to unauthorised endpoint (Granular).") 57 58 return errors.New("Access to this resource has been disallowed"), http.StatusForbidden 59 60 }