Last active
October 22, 2016 21:01
-
-
Save aravindbaskaran/4c63f17259937702857686451f32b90c to your computer and use it in GitHub Desktop.
Middleware to secure API groups to set of whitelist IPs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns sw.ring-ip-whitelist | |
"Just for reference, to show the :require for this to work" | |
(:require [clojure.string :as str])) | |
(defn- header-value | |
[request k] | |
(-> request :headers (get k))) | |
(defn- get-host-addr [request] | |
(or (header-value request "x-forwarded-for") | |
(:remote-addr request) | |
"")) | |
(def ^:const dev (symbol "dev")) | |
(defn wrap-ip-whitelist | |
"Middleware to secure API groups to set of whitelist IPs. Eg: (wrap-ip-whitelist handler \"192.168.0.1,192.168.0.2\" nil) | |
allowed-ips - comma separated list of IP addresses, support for IPv4 | |
allowed-ips and environment can be passed through from a config/edn file. | |
if environment = dev, assumes IP is whitelisted to aid in dev environment testing" | |
[handler allowed-ips environment] | |
(fn [request] | |
(let [addresses (str/split (get-host-addr request) #",")] | |
(if (or | |
(= environment dev) | |
(some #(.contains allowed-ips (str/trim (first (str/split % #":")))) addresses)) | |
(handler request) | |
{:status 401 :headers {"Content-Type" "text/plain"} :body (str "Not allowed" addresses)})))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns sw.route-whitelist | |
"Just for reference, to show the :require for this to work" | |
(:require [sw.ring-ip-whitelist :as middleware] | |
[ring.util.http-response :refer [ok]] | |
[luminus.http-server :as http] ;; Using luminus server, you can use any ring-based servers | |
[compojure.core :refer [defroutes GET]])) | |
(defroutes internal-safe-routes | |
"Internal secure routes" | |
(context "/ip-safe" request | |
(GET "/authenticated" [] (ok "Secured!")))) | |
;; Define other routes as needed | |
(defn start-app [] | |
(http/start {:handler (wrap-routes #'internal-safe-routes middleware/wrap-ip-whitelist) | |
:port 8080})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment