Guest User

Untitled

a guest
Jan 19th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. (defn wrap-anti-forgery
  2. "Middleware that prevents CSRF attacks. Any POST request to the handler
  3. returned by this function must contain a valid anti-forgery token, or else an
  4. access-denied response is returned.
  5.  
  6. The anti-forgery token can be placed into a HTML page via the
  7. *anti-forgery-token* var, which is bound to a random key unique to the
  8. current session. By default, the token is expected to be in a form field
  9. named '__anti-forgery-token', or in the 'X-CSRF-Token' or 'X-XSRF-Token'
  10. headers.
  11.  
  12. Accepts the following options:
  13.  
  14. :read-token - a function that takes a request and returns an anti-forgery
  15. token, or nil if the token does not exist
  16.  
  17. :error-response - the response to return if the anti-forgery token is
  18. incorrect or missing
  19.  
  20. :error-handler - a handler function to call if the anti-forgery token is
  21. incorrect or missing.
  22.  
  23. Only one of :error-response, :error-handler may be specified."
  24. ([handler]
  25. (wrap-anti-forgery handler {}))
  26. ([handler options]
  27. {:pre [(not (and (:error-response options) (:error-handler options)))]}
  28. (let [read-token (:read-token options default-request-token)
  29. error-handler (make-error-handler options)]
  30. (fn
  31. ([request]
  32. (go-try
  33. (let [token (find-or-create-token request)]
  34. (binding [*anti-forgery-token* token]
  35. (if (valid-request? request read-token)
  36. (add-session-token (<? (handler request)) request token)
  37. (error-handler request))))))
  38. ([request respond raise]
  39. (go-try
  40. (let [token (find-or-create-token request)]
  41. (binding [*anti-forgery-token* token]
  42. (if (valid-request? request read-token)
  43. (<? (handler request #(respond (add-session-token % request token)) raise))
  44. (error-handler request respond raise))))))))))
Add Comment
Please, Sign In to add comment