Skip to content

Commit

Permalink
Add :ssl-port option to wrap-ssl-redirect
Browse files Browse the repository at this point in the history
  • Loading branch information
weavejester committed May 31, 2014
1 parent 595fa47 commit d564b54
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
15 changes: 12 additions & 3 deletions src/ring/middleware/ssl.clj
Expand Up @@ -28,13 +28,22 @@
(or (= method :head)
(= method :get)))

(defn- https-url [url-string port]
(let [url (java.net.URL. url-string)]
(str (java.net.URL. "https" (.getHost url) (or port -1) (.getFile url)))))

(defn wrap-ssl-redirect
"Middleware that redirects any HTTP request to the equivalent HTTPS URL."
[handler]
"Middleware that redirects any HTTP request to the equivalent HTTPS URL.
Accepts the following options:
:ssl-port - the SSL port to use for redirects, defaults to 443."
{:arglists '([handler] [handler options])}
[handler & [{:keys [ssl-port]}]]
(fn [request]
(if (= (:scheme request) :https)
(handler request)
(-> (resp/redirect (req/request-url (assoc request :scheme :https)))
(-> (resp/redirect (https-url (req/request-url request) ssl-port))
(resp/status (if (get-request? request) 301 307))))))

(defn- build-hsts-header
Expand Down
13 changes: 12 additions & 1 deletion test/ring/middleware/ssl_test.clj
Expand Up @@ -42,7 +42,18 @@
(testing "HTTPS request"
(let [response (handler (request :get "https://localhost/"))]
(is (= (:status response) 200))
(is (nil? (get-header response "location")))))))
(is (nil? (get-header response "location"))))))

(let [handler (wrap-ssl-redirect (constantly (response "")) {:ssl-port 8443})]
(testing "HTTP GET request with custom SSL port"
(let [response (handler (request :get "/"))]
(is (= (:status response) 301))
(is (= (get-header response "location") "https://localhost:8443/"))))

(testing "HTTP POST request with custom SSL port"
(let [response (handler (request :post "/"))]
(is (= (:status response) 307))
(is (= (get-header response "location") "https://localhost:8443/"))))))

(deftest test-wrap-hsts
(testing "defaults"
Expand Down

0 comments on commit d564b54

Please sign in to comment.