Created
November 2, 2015 00:31
-
-
Save Frozenlock/c53b388cab3f639e0ff4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns cea.buddy-token | |
"The token based authentication and authorization backends." | |
(:require [buddy.auth.protocols :as proto] | |
[buddy.auth.http :as http] | |
[buddy.auth :refer [authenticated?]] | |
[buddy.sign.jws :as jws] | |
[buddy.sign.jwe :as jwe] | |
[clojure.string :as s])) | |
(defn- handle-unauthorized-default | |
"A default response constructor for an unathorized request." | |
[request] | |
(if (authenticated? request) | |
{:status 403 :headers {} :body "Permission denied"} | |
{:status 401 :headers {} :body "Unauthorized"})) | |
(defn- parse-cookie-token-header | |
[request token-name] | |
(let [cookie (or (http/-get-header request "cookie") "")] | |
(some-> | |
(or (re-find (re-pattern (str token-name "=(.+); ")) cookie) | |
(re-find (re-pattern (str token-name "=(.+)$")) cookie)) | |
(second) | |
(s/replace #"; " "")))) | |
(defn jws-in-cookies-backend | |
"Create an instance of the jws (json web signature) | |
based authentication backend. | |
This backends also implements authorization workflow | |
with some defaults. This means that you can provide | |
own unauthorized-handler hook if the default not | |
satisfies you." | |
[{:keys [secret unauthorized-handler options token-name on-error] | |
:or {token-name "token"}}] | |
(reify | |
proto/IAuthentication | |
(-parse [_ request] | |
(let [token (parse-cookie-token-header request token-name)] | |
token)) | |
(-authenticate [_ request data] | |
(try | |
(jws/unsign data secret options) | |
(catch clojure.lang.ExceptionInfo e | |
(let [data (ex-data e)] | |
(when (fn? on-error) | |
(on-error request e)) | |
nil)))) | |
proto/IAuthorization | |
(-handle-unauthorized [_ request metadata] | |
(if unauthorized-handler | |
(unauthorized-handler request metadata) | |
(handle-unauthorized-default request))))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment