Skip to content

Instantly share code, notes, and snippets.

@jcf
Created June 5, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcf/9380355e8ebbdb6a193a to your computer and use it in GitHub Desktop.
Save jcf/9380355e8ebbdb6a193a to your computer and use it in GitHub Desktop.
CORS interceptors (use `:io.pedestal.http/allowed-origins` instead)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; CORS
(def ^:const ^:private allowed-cors-headers
(str/join ", " #{"Authorization"
"Content-Type"
"If-Match"
"If-Modified-Since"
"If-None-Match"
"If-Unmodified-Since"
"X-Requested-With"}))
(s/defn ^:private add-cors-headers :- types/Response
[origin :- s/Str response :- types/Response]
(update-in
response [:headers] assoc
"Access-Control-Allow-Credentials" "true"
"Access-Control-Allow-Headers" allowed-cors-headers
"Access-Control-Allow-Methods" "DELETE, GET, PATCH, POST, PUT"
"Access-Control-Allow-Origin" origin
"Access-Control-Expose-Headers" "Etag, Link, X-Total"))
(def cross-origin-resource-sharing
(interceptor/around
::cors
(fn [{:keys [request] :as context}]
(let [origin (ring.response/get-header request "origin")]
(if (and origin (= (:request-method request) :options))
(impl.interceptor/terminate
(assoc context :response
(add-cors-headers origin {:status 200
:headers {"Content-Type" "text/plain"}
:body "Preflight complete.\n"})))
context)))
(fn [{:keys [request response] :as context}]
(if-let [origin (ring.response/get-header request "origin")]
(update-in context [:response] (partial add-cors-headers origin))
context))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment