github.com/dbernstein1/tyk@v2.9.0-beta9-dl-apic+incompatible/gateway/mw_version_check.go (about)

     1  package gateway
     2  
     3  import (
     4  	"errors"
     5  	"net/http"
     6  	"time"
     7  
     8  	"github.com/TykTechnologies/tyk/apidef"
     9  	"github.com/TykTechnologies/tyk/request"
    10  )
    11  
    12  // VersionCheck will check whether the version of the requested API the request is accessing has any restrictions on URL endpoints
    13  type VersionCheck struct {
    14  	BaseMiddleware
    15  	sh SuccessHandler
    16  }
    17  
    18  func (v *VersionCheck) Init() {
    19  	v.sh = SuccessHandler{v.BaseMiddleware}
    20  }
    21  
    22  func (v *VersionCheck) Name() string {
    23  	return "VersionCheck"
    24  }
    25  
    26  func (v *VersionCheck) DoMockReply(w http.ResponseWriter, meta interface{}) {
    27  	// Reply with some alternate data
    28  	emeta := meta.(*apidef.EndpointMethodMeta)
    29  	responseMessage := []byte(emeta.Data)
    30  	for header, value := range emeta.Headers {
    31  		w.Header().Add(header, value)
    32  	}
    33  
    34  	w.WriteHeader(emeta.Code)
    35  	w.Write(responseMessage)
    36  }
    37  
    38  // ProcessRequest will run any checks on the request on the way through the system, return an error to have the chain fail
    39  func (v *VersionCheck) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int) {
    40  	// Check versioning, blacklist, whitelist and ignored status
    41  	requestValid, stat, meta := v.Spec.RequestValid(r)
    42  	if !requestValid {
    43  		// Fire a versioning failure event
    44  		v.FireEvent(EventVersionFailure, EventVersionFailureMeta{
    45  			EventMetaDefault: EventMetaDefault{
    46  				Message:            "Attempted access to disallowed version / path.",
    47  				OriginatingRequest: EncodeRequestToEvent(r),
    48  			},
    49  			Path:   r.URL.Path,
    50  			Origin: request.RealIP(r),
    51  			Reason: string(stat),
    52  		})
    53  		return errors.New(string(stat)), http.StatusForbidden
    54  	}
    55  
    56  	// We handle redirects before ignores in case we aren't using a whitelist
    57  	if stat == StatusRedirectFlowByReply {
    58  		v.DoMockReply(w, meta)
    59  		return nil, mwStatusRespond
    60  	}
    61  
    62  	if expTime, _ := meta.(*time.Time); expTime != nil {
    63  		w.Header().Set("x-tyk-api-expires", expTime.Format(time.RFC1123))
    64  	}
    65  
    66  	if stat == StatusOkAndIgnore {
    67  		v.sh.ServeHTTP(w, r)
    68  		return nil, mwStatusRespond
    69  	}
    70  
    71  	return nil, http.StatusOK
    72  }