arlindosilvaneto
3/8/2017 - 1:15 PM

Filter architecture for Luminus Webframework

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))))))