package api import ( "context" "net/http" "os" log "github.com/sirupsen/logrus" "reichard.io/imagini/graph/model" ) type Middleware func(http.Handler) http.HandlerFunc func multipleMiddleware(h http.HandlerFunc, m ...Middleware) http.HandlerFunc { if len(m) < 1 { return h } wrapped := h for i := len(m) - 1; i >= 0; i-- { wrapped = m[i](wrapped) } return wrapped } /** * This is used for the graphQL endpoints that may require access to the * Request and ResponseWriter variables. These are used to get / set cookies. **/ func (api *API) injectContextMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { authContext := &model.AuthContext{ AuthResponse: &w, AuthRequest: r, } // Add context ctx := context.WithValue(r.Context(), "auth", authContext) r = r.WithContext(ctx) next.ServeHTTP(w, r) }) } /** * This is used for non graphQL endpoints that require authentication. **/ func (api *API) authMiddleware(next http.Handler) http.HandlerFunc { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { accessToken, err := api.validateTokens(&w, r) if err != nil { errorJSON(w, "Invalid token.", http.StatusUnauthorized) return } // Create Context authContext := &model.AuthContext{ AccessToken: &accessToken, } ctx := context.WithValue(r.Context(), "auth", authContext) r = r.WithContext(ctx) next.ServeHTTP(w, r) }) } func (api *API) logMiddleware(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.SetOutput(os.Stdout) log.Println(r.Method, r.URL) h.ServeHTTP(w, r) }) }