faas/gateway/handlers/external_auth.go
Alex Ellis 35508ac70b Add explicit deadline for auth request
An explicit timeout is passed to the handler and a new unit test
proves that the functionality is in place. A additional return
statement was needed in the handler as pointed out by
@stefanprodan.

Signed-off-by: Alex Ellis <alexellis2@gmail.com>
2019-06-05 18:13:49 +01:00

38 lines
832 B
Go

package handlers
import (
"context"
"net/http"
"time"
)
// MakeExternalAuthHandler make an authentication proxy handler
func MakeExternalAuthHandler(next http.HandlerFunc, upstreamTimeout time.Duration, upstreamURL string, passBody bool) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
req, _ := http.NewRequest(http.MethodGet, upstreamURL, nil)
deadlineContext, cancel := context.WithDeadline(
context.Background(),
time.Now().Add(upstreamTimeout))
defer cancel()
res, err := http.DefaultClient.Do(req.WithContext(deadlineContext))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
if res.Body != nil {
defer res.Body.Close()
}
if res.StatusCode == http.StatusOK {
next.ServeHTTP(w, r)
return
}
w.WriteHeader(res.StatusCode)
}
}