How to make session data in http-kit - clojure

For my login system, I need to implement session data for different functionality when users are logged in or not.
I've only ever done sessions in flask, and google searches don't reveal a lot (or, more likely, I'm searching the wrong things). I have two questions:
Is there a canonical way to do session data in Clojure and can this specifically done in http-kit?
Is an atom enough, or would this be bad practice?

sessions will have to be managed via ring. http-kit is a server & will only use the ring spec for requests and responses.
To fetch the session
(get-in req [:session :auth-token])
To add a session to your ring response
(assoc res
:session {:auth-token auth-token
:userid (:id json-data)
:username (:username json-data)})

Related

Weird session management bug when mixing ring's `wrap-defaults`' and lib-noir's `wrap-noir-session`

I have a ring webapp that uses noir.session as follows:
(def app (-> app-routes
(session/wrap-noir-session)
(wrap-defaults site-defaults))) ; both from ring.middleware.defaults
However, it seems like session variables are lost between the requests. The server keeps sending a Set-Cookie header even though the client provides the Cookie header.
Using trial and error, I found out that when I disable ring's anti-forgery wrapper as follows, the same session lives across requests:
(def app (-> app-routes
(session/wrap-noir-session)
(wrap-defaults (assoc-in site-defaults [:security :anti-forgery] false))))
but of course I don't want that. Why is this, and how can I fix my problem without risking CSRF attacks?
Browsing the source code of all involved middleware, I found out that lib-noir's wrap-noir-session re-implements parts of ring's wrap-session. That lead me to the following experiment:
(def app (-> app-routes
(session/wrap-noir-session {:store (memory-store)})
(wrap-defaults (assoc site-defaults :session false))))
Here as well, sessions live across requests.
Here's the culprit: wrap-defaults already applies wrap-session, so when the wrap-noir-session handler is listed as well, wrap-session is actually invoked twice.
The final solution couldn't be simpler: Use wrap-noir-session* instead. According to the docs, it "expects that wrap-session has already been used." It seems that the contrary is true for wrap-noir-session.
(def app (-> app-routes
(session/wrap-noir-session*)
(wrap-defaults site-defaults)))
Hopefully, this will save you some time.

How to disable CSRF token for specific endpoints(URLs) with Ring in Clojure?

I have a web app which has CSRF protection but I need to disable this protection for some endpoints(public APIs) so I can send Rest calls without having problem.
Here is my code:
(def handler (-> route.all/routes
log-middleware
(wrap-defaults site-defaults);;which provides CSRF protection
wrap-exceptions
wrap-reload
wrap-gzip))
(defn start
[port]
(jetty/run-jetty handler {:port port}))
P.S: I use Liberator along with Ring
Thanks to James Reeves, he has answered this question over here

In ClojureScript, why can't I navigate to a URL entered by hand, but if I click a link it works?

(Note, I'm using Reagent, Secretary, and Compojure (among others))
I want to create a route /sectest/:id, and if I point my browser to that route, I get the following error:
Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:3449/sectest/css/site.css".
asdf:1
Refused to execute script from 'http://localhost:3449/sectest/js/app.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
But if I click on a link in the browser that navigates to that route, it works fine...
Here's the pertinent code:
Client Side:
(secretary/defroute "/sectest/:id" [id]
(do
(js/console.log (str "Hi " id))
(session/put! :current-page #'my-page)))
Server Side:
(defroutes routes
(GET "*" [] loading-page) ;this anticipates client-side routing only
(GET "/cards" [] cards-page)
(resources "/")
(not-found "Not Found"))
(def app (wrap-middleware #'routes))
So the following link takes me to my-page, and the console prints "Hi asdf" just fine:
[:div [:a {:href "/sectest/asdf"} "SECTEST"]]
But if I type in http://localhost:3449/sectest/asdf, I get an error, and I can't seem to trace it. I suspect it might have something to do with the code trying to find resources located at /sectest, (which it shouldn't), but I can't confirm this or figure out how to work with it... I am new to clojure, so forgive if I'm massively ignorant on some point, any thoughts?
Take a look at your server side routing, effectively you only have one route:
(GET "*" [] loading-page)
As it handles everything all following routes will never trigger. Order matters:
(defroutes routes
(GET "/cards" [] cards-page)
(resources "/")
(GET "*" [] loading-page) ;this anticipates client-side routing only
)
The above should do the trick, I removed the 404 route, as this should be handled by the frontend routing.
The reason it currently works when clicking on a page link in your SPA is that it will get handled by secretary. If you enter the url manually you are doing a page reload and the request is handled by compojure initially.
Edit:
After taking a closer look, relative links to your css/js files in your html template are most likely the culprit here:
/sectest/js/app.js
The compojure resources route won't match and the default catch all route loading-page is served as css/js file to your browser. Hence the error.
For my dev env I also had to correct the :asset-path of my boot cljs task as the source mapping files suffered from the problem. Should be similiar with lein-figwheel.

Is there some sort of canonical edn response we can use for ring?

I've been reading the edn spec and want to integrate it into my application. However, I don't know how to transfer edn requests between clojure and client. Do we put a content-type application/edn in the response header and just send the prn output string?
Although it has not yet been accepted by IANA (June 14, 2013), the correct content-type is application/edn. To provide a valid string output of your clojure object, use (pr-str obj). For a web service, the method of encoding and decoding depends on your web framework and your needs.
Pedestal supports parsing of edn into an :edn-params key on its request map through the use of its body-params interceptor. Sending clojure objects as edn is handled automatically if your response bodies are not strings. For content-negotiation, see pedestal-content-negotiation.
For ring middleware, ring-edn parses edn into an :edn-params key, but does not do any outbound modification. ring-middleware-format provides parsing of a handful of different formats into the :body-params key, and has a collection of middlewares that can be helpful for responses as well. There are a handful of other ring middleware projects like this out there.

Put Clojure Ring middlewares in correct order

I'm having trouble with my Clojure server middlewares. My app has the following requirements:
Some routes should be accessible with no problems. Others require basic authentication, so I'd like to have an authentication function that sits in front of all the handler functions and makes sure the request is verified. I've been using the ring-basic-authentication handler for this, especially the instructions on how to separate your public and private routes.
However, I'd also like the params sent in the Authorization: header to be available in the route controller. For this I've been using Compojure's site function in compojure.handler, which puts variables in the :params dictionary of the request (see for example Missing form parameters in Compojure POST request)
However I can't seem to get both 401 authorization and the parameters to work at the same time. If I try this:
; this is a stripped down sample case:
(defn authenticated?
"authenticate the request"
[service-name token]
(:valid (model/valid-service-and-token service-name token)))
(defroutes token-routes
(POST "/api/:service-name/phone" request (add-phone request)))
(defroutes public-routes
controller/routes
; match anything in the static dir at resources/public
(route/resources "/"))
(defroutes authviasms-handler
public-routes
(auth/wrap-basic-authentication
controller/token-routes authenticated?))
;handler is compojure.handler
(def application (handler/site authviasms-handler))
(defn start [port]
(ring/run-jetty (var application) {:port (or port 8000) :join? false}))
the authorization variables are accessible in the authenticated? function, but not in the routes.
Obviously, this isn't a very general example, but I feel like I'm really spinning my wheels and just making changes at random to the middleware order and hoping things work. I'd appreciate some help both for my specific example, and learning more about how to wrap middlewares to make things execute correctly.
Thanks,
Kevin
AFAIK, ring.middleware.basic-authentication doesn't read anything from the :params in request and ring.core.request/site doesn't put anything authentication-related there either.
But in any ring handler, you can still access the headers. Something like:
(GET "/hello"
{params :params headers :headers}
(str "your authentication is " (headers "authentication")
" and you provided " params))
Similarly, you can use that to write your own middleware to put authentication-related stuff in params, if you really want to.