Last active
August 29, 2015 14:01
-
-
Save debetimi/24c4f26612b881982f0d to your computer and use it in GitHub Desktop.
This is an example of getting Friend to work with an AJAX request, and redirect set to null. When the request is not JSON/EDN works as normal and redirects.
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 foo.auth.core | |
(:require [cemerick.friend :as friend] | |
[cemerick.friend.util :refer [gets]] | |
[cemerick.friend.workflows :as workflow] | |
[cemerick.friend.credentials :as creds] | |
[tickets.routes.user :refer [login-friend]] | |
[ring.util.request :as req] | |
[noir.response])) | |
(defn- form-ajax-response | |
"Creates an Ajax Request. | |
Authenticates User by merging authentication | |
into response along with status and body allowing | |
for ajax response." | |
[status body resp auth content-type] | |
(let [auth-resp (friend/merge-authentication (dissoc resp :body-params) auth) | |
formatter (case content-type | |
"application/edn" noir.response/edn | |
noir.response/json)] | |
(merge auth-resp {:status status} (formatter {:body body})))) | |
(def not-nil? (complement nil?)) | |
(defn form-or-ajax-login | |
"Friend Workflow for Handling forms or ajax requests posted to | |
'/login'. When a form is posted, the request will initiate a redirect | |
on login When the post is performed via ajax. A response will be sent | |
with success and redirect information" | |
[& {:keys [login-uri credential-fn login-failure-handler redirect-on-auth?] :as ajax-config | |
:or {redirect-on-auth? true}}] | |
(fn [{:keys [uri request-method content-type params] :as request}] | |
(when (and (= :post request-method) | |
(= uri (gets :login-uri ajax-config (::friend/auth-config request)))) | |
(let [creds {:username (:username params) | |
:password (:password params)} | |
{:keys [username password]} creds | |
ajax? (not-nil? (ajax-request-type content-type)) | |
cred-fn (gets :credential-fn ajax-config (::friend/auth-config request))] | |
(when-let [user-record (and username password (cred-fn creds))] | |
(let [user-auth (workflow/make-auth user-record {::friend/workflow :form-or-ajax | |
::friend/redirect-on-auth? (not ajax?)})] | |
(case ajax? | |
true (form-ajax-response 202 {:message "success"} request user-auth content-type) | |
user-auth))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment