github.com/pf-qiu/concourse/v6@v6.7.3-0.20201207032516-1f455d73275f/atc/api/policychecker/handler.go (about)

     1  package policychecker
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  
     7  	"code.cloudfoundry.org/lager"
     8  
     9  	"github.com/pf-qiu/concourse/v6/atc/api/accessor"
    10  	"github.com/pf-qiu/concourse/v6/atc/policy"
    11  )
    12  
    13  func NewHandler(
    14  	logger lager.Logger,
    15  	handler http.Handler,
    16  	action string,
    17  	policyChecker PolicyChecker,
    18  ) http.Handler {
    19  	return policyCheckingHandler{
    20  		logger:        logger,
    21  		handler:       handler,
    22  		action:        action,
    23  		policyChecker: policyChecker,
    24  	}
    25  }
    26  
    27  type policyCheckingHandler struct {
    28  	logger        lager.Logger
    29  	handler       http.Handler
    30  	action        string
    31  	policyChecker PolicyChecker
    32  }
    33  
    34  func (h policyCheckingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    35  	acc := accessor.GetAccessor(r)
    36  
    37  	result, err := h.policyChecker.Check(h.action, acc, r)
    38  	if err != nil {
    39  		w.WriteHeader(http.StatusBadRequest)
    40  		fmt.Fprintf(w, fmt.Sprintf("policy check error: %s", err.Error()))
    41  		return
    42  	}
    43  
    44  	if !result.Allowed {
    45  		w.WriteHeader(http.StatusForbidden)
    46  		policyCheckErr := policy.PolicyCheckNotPass{
    47  			Reasons: result.Reasons,
    48  		}
    49  		fmt.Fprintf(w, policyCheckErr.Error())
    50  		return
    51  	}
    52  
    53  	h.handler.ServeHTTP(w, r)
    54  }