Breaking down the ring middleware scenario - clojure

Ring is super sleek and has some pretty sensible defaults for middleware(s).
When I made a new app through leiningen (lein) I ended up with something like this in my router/handler
(def app
(wrap-defaults app-routes site-defaults))
https://github.com/ring-clojure/ring-defaults
Now I want to add more middleware (cemerick/friend) so I can do things like authentication for logins.
So, how would I translate the above into something more reminiscent of the ring middleware "stack," like at the bottom of the page https://github.com/ring-clojure/ring-defaults/blob/master/src/ring/middleware/defaults.clj
(def app
(-> handler
(wrap-anti-forgery)
(wrap-flash)
(wrap-session)
(wrap-keyword-params)
(wrap-resource)
(wrap wrap-file)))

because ring just uses function composition for middleware you can simply wrap friend around the call to wrap defaults:
(def app
(my-additional-middleware
(wrap-defaults app-routes site-defaults)
arguments to my additional middleware))
or you can thread it (for instance when you have several middlewares):
(def app
(-> (wrap-defaults app-routes site-defaults)
(friend-stuff arg arg)
(other-middleware arg arg arg))
Getting the order of the middleware right is still up to you :-/

Related

Implementing a login system with re-frame

I am new to re-frame and not quite sure how to build a user authentication/authorization system with it.
From what I gathered I should create an auth interceptor and place my auth logic inside :before section then inject the interceptor into every events reg-event-db and reg-event-fx that I want to protect.
Am I on the right track?
Not sure if my solution is particularly idiomatic, but I used something like the following in one of my projects. Consider it a Works For Me.
Create a map for the ajax request with a special value for error cases (ignore the context-uri function):
(defn xhrio-map [method path format success-event]
{:method method
:uri (context-uri path)
:timeout 5000
:response-format format
:on-success [success-event]
:on-failure [::ajax-failure]})
Then I use an fx handler for the failure (this is a bit more complicated as it also handles a loading indicator):
(rf/reg-event-fx
::ajax-failure
(fn [{:keys [db]} [_ http-result]]
(if (= 403 (:status http-result))
{:db (assoc db :loading-indicator nil)
:dispatch [::logout]}
{:db (assoc db :loading-indicator nil)
:dispatch
[::error-msg (str "Error fetching from " (:uri http-result)
": " (:response http-result))]})))
The ::logout events sets the document location. This also triggers the logout in the backend.
(rf/reg-event-fx
::logout
(fn [coefx [ev]]
{::location "./logout"}))
Finally, the loading of resources works like this:
(defn load-with-indicator [db xhrio-data]
{:db (assoc db :loading-indicator true)
:http-xhrio xhrio-data})
(rf/reg-event-fx
::load-documentation
(fn [{:keys [db]} _]
(load-with-indicator
db
(xhrio-map :get "documentation/"
(ajax/json-response-format {:keywords? true})
::received-documentation))))
The :received-documentation is handled by some code which invokes the correct display functions.
This uses the day8.re-frame/http-fx and ajax.core
On the backend, I use something similar to the demo code I published over at https://github.com/ska2342/ring-routes-demo.
Hope that helps.
License of the code in this post
In addition to the default license of the StackOverflow site, I also publish these lines under the Eclipse Public License either version 1.0 or (at your option) any later version.

Clojure compojure middleware and arrow syntax

I am trying to understand compojure middlewares :
The following code is from the compojure template :
(def app
(wrap-defaults app-routes site-defaults))
Is it equivalent to the following ?
(def app
(-> app-routes
(wrap-defaults api-defaults)))
I am unsure about this since in the following code my-middleware2 is called before my-middleware1
(def app
(-> api-routes
(wrap-defaults api-defaults)
(my-middleware1)
(my-middleware2)))
You are correct:
(def app
(wrap-defaults app-routes site-defaults))
Is equivalent to:
(def app
(-> app-routes
(wrap-defaults api-defaults)))
The arrow is called the Thread-First Macro and allows you to write nested s-expressions in a linear way.
In your second example, it makes sense that my-middleware2 is called before my-middleware1 when an HTTP request comes in. You are creating a Ring Handler, not calling the middleware directly.
(def app
(-> api-routes
(wrap-defaults api-defaults)
my-middleware1
my-middleware2))
Is expanded to:
(def app
(my-middleware2 (my-middleware1 (wrap-defaults app-routes api-defaults))))
When an HTTP request comes in, my-middleware2 handles it first, does something to it (i.e. extracts the session data), and then passes it along to the next middleware until one of them returns an HTTP response.
Note: I took out the parens from (my-middleware1) and (my-middleware2). When used like that it means that my-middlware1 is a function that when called with no arguments, returns a middleware function. This might be what you wanted but is not common practice.

How to apply a ring-middleware to specific group of routes?

I have a ring middleware which does some check on request maps with the header values.
For the check I have to hit the database.
If a defroutes as a set of routes starting with acommon URI pattern.
I don't want a middleware to run for any random URL that matches the pattern before getting handled.
I only want middleware to run for a certain set of URIs that I am suing inside of defroutes only. The reason being there is a database access in the middleware which I want to avoid for 404 responses having the same pattern.
Here is comporoute, a ring handler without any macro magic, aimed at composability and extensibility.
Even though it's in early alpha state it has precise docstrings already. It has a feature called inner middleware to solve the issue you are having. You may (and should) use it only for what you need it for and leave the rest to Compojure.
Given your Compojure handler/app is called compojure:
(defn demo-middleware
"A test midleware associng :bar to :foo of request"
[handler]
(fn [request]
(handler (assoc request :foo :bar))))
(defn demo-handler [request]
(ring.util.response/response
(str "id is " (get-in request [:params :id]) " "
":foo is" (:foo request))))
(def app
(comporoute.core/router
[["/demo-with-middleware"
[demo-middleware ;; all handlers in this vector are
;; wrapped via demo-middleware
["/:id" :demo-with demo-handler]]]
["/demo-without-middleware"
["/:id" :demo-without demo-handler]]]
:page-not-found compojure)
At the shell
curl http://localhost:8080/demo-without-middleware/1234
id is 1234 :foo is
curl http://localhost:8080/demo-with-middleware/1234
id is 1234 :foo is :bar
# Everything else will be handled by compojure.
Dependency vector [comporoute "0.2.0"]

How to write a login function in luminus or use friend?

I am beginning to use luminus framework to develop a web app, and I am trying to use friend for auth, I am stacked here, I don't know how to use that like using gem in rails app.
I don't know where should I put the code in luminus, is there anyone can show me a demo. Or tell me what to do next?
Well, you can also tell me how to write a log in function in luminus.
The login sort of works like it is posted in the Luminus Docs. Not sure if you managed to read that part, but I'll show you a simplified version of the code I use. I want to mention that I removed quite a bit of code to make everything a bit easier to understand, so this may not work as-is since I only deleted code and extra parens. Since it is from actual working code, it will work with a bit of tweeking:
The first part is getting the login form:
(defn login-page []
(html5
[:h3 "Login"]
[:form {:method "POST" :action "login"}
[:div "Username:"
[:input {:type "text" :name "username" :required "required"}]]
[:div "Password:"
[:input {:type "password" :name "password" :required "required"}]]
[:div
[:input {:type "submit" :value "Log In"}]]]]))
Notice that there is a "POST" method? In order to get the routes to work, you have to have a "POST" route, but you will also need a "GET" route. This is the simplified version of the "GET" "POST" loop that I have:
(defroutes app-routes
(GET "/login" []
(log/login-page))
(POST "/login" [username password]
(do-login username password)))
The (do-login) function is where I authenticate the user / password combo, which then sets the session, which is shown downn below.
Notice that the POST route needs arguments. The arguments must match the "name" parameters in the form.
Finally, to get it all to work, you have to hook up some sessions. I personally use lib-noir.sessions:
(ns myapp.handler
(:require [noir.session :as sesh])
Then you have to create a map to hold the session, which I'm wrapping in a function here (note that the :key must match whatever you have in your database:
(defn set-user [username]
(sesh/put! :handle username))
And finally, you have to tell clojure that you want to allow sessions to be handled via middleware:
(def app
(sesh/wrap-noir-session
(handler/site
app-routes)))
Hopefully that gives you a bit of a headstart. I did not include how to connect to a database or how to use a map, but the above should be enough to get you on your way. I also did not touch on authorization and security (please don't skip this!). Using a database, map, or friend isn't a huge quantum leap from here. Just wanted to offer just enough to get you started.
Here's an example from when I did a luminus+friend combination, granted, they've changed the template several times, so this is from an older version, but the concepts the same, I hope it helps.
(def all-routes
[home-routes cljs-routes test-routes app-routes])
(def app
(-> all-routes middleware/app-handler ))
(def secured-app
(handler/site
(friend/authenticate app{
:login-uri "/login"
:unauthorized-redirect-uri "/login"
:credential-fn (partial creds/bcrypt-credential-fn users)
:workflows [(workflows/interactive-form)]})))
(def war-handler
(middleware/war-handler secured-app))

how to debug the ring session store?

I've defined an app and wish to be able to print out all the values contained in session store is there a good way to do this?
(def app
(-> #'handler
(ring.middleware.stacktrace/wrap-stacktrace)
(ring.middleware.session/wrap-session)))
You can specify the session store for wrap-session to use:
(def all-the-sessions (atom {}))
(def app
(-> #'handler
(ring.middleware.stacktrace/wrap-stacktrace)
(ring.middleware.session/wrap-session {:store (ring.middleware.session.memory/memory-store all-the-sessions)))
Now you can inspect the all-the-sessions atom.