Skip to content

Instantly share code, notes, and snippets.

@arlindosilvaneto
Last active March 8, 2017 13:46
Show Gist options
  • Save arlindosilvaneto/6b959adb9ab29d345da24d50baaf3031 to your computer and use it in GitHub Desktop.
Save arlindosilvaneto/6b959adb9ab29d345da24d50baaf3031 to your computer and use it in GitHub Desktop.
Filter architecture for Luminus Webframework
(defn request-auth
"Finds the user by the header token parameter and pass it to the next chain filter/controller as the :user request parameter"
[req & chain]
(let [token (get-in req [:headers "x-auth-token"])]
(if (nil? token)
{:status 401}
(let [user (user/find-by-token (:tx req) token)]
(if (nil? user)
{:status 403}
(let [new-req (assoc req :user (assoc (:user user) :id (:id user)))]
(filters/next! new-req chain)))))))
(defn next!
"Routes to next filter or controller"
[req chain]
(if (= (count chain) 1)
;; next chain element is a controller
((first chain) req)
;; next chain element is another filter
(apply (first chain) (conj (next chain) req))))
(defapi user-routes
(PUT "/" []
:body-params [password :- String]
:header-params [x-auth-token :- String]
:summary "Changes user password"
(fn [req] (tx/request-tx req auth/request-auth user/change-password))))
(defn request-tx
"Creates a new transaction with the database and pass it to the next chain filter/controller as the :tx request parameter"
[req & chain]
(let [conn (db/get-conn)
tx (db/get-tx conn)
new-req (assoc req :tx {:conn conn :tx tx})]
(try
(let [res (filters/next! new-req chain)]
(db/commit conn tx)
res)
(catch Exception ex (do
(db/rollback conn tx)
(throw ex))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment