Skip to content
This repository was archived by the owner on Mar 8, 2021. It is now read-only.
This repository was archived by the owner on Mar 8, 2021. It is now read-only.

new workflow for single page applications (non-redirecting API) #120

Description

@GetContented

Hi,

I have a use-case for a new type of workflow which is for single page applications. These require user/pass combo through a http post, but there's no form or redirection involved (kind of a hybrid of http-basic and interactive-form in a way).

So, I wrote the following code. It's not a pull request because I don't have it in a separate repo or anything, and it's lifted straight from my source. Maybe it could be adjusted and added to the main repo as workflows/api?

I hope I haven't done anything crap by submitting this. I just found this incredibly useful and it may be to others, too.

(ns myapp.middleware.auth
  (:use [cemerick.friend.util :only (gets)])
  (:require [ring.util.request :as req]
            [cemerick.friend :as friend]
            (cemerick.friend [workflows :as workflows]
                             [credentials :as creds])))

; the following two methods are private helper functions for the api-workflow function, taken from cemerick.freind.credentials
(defn- username
  [form-params params]
  (or (get form-params "username") (:username params "")))

(defn- password
  [form-params params]
  (or (get form-params "password") (:password params "")))

; this is a custom workflow for Single Page Application login
(defn api-workflow
  [& {:keys [login-uri credential-fn login-failure-handler] :as form-config}]
  (fn [{:keys [request-method params form-params] :as request}]    
    (when (and (= (gets :login-uri form-config (::friend/auth-config request)) (req/path-info request))
               (= :post request-method))

      (let [credentials {:username (username form-params params)
                         :password (password form-params params)}
            {:keys [username password]} credentials]
        (if-let [user-record (and username password
                                  ((gets :credential-fn form-config (::friend/auth-config request))
                                   (with-meta credentials {::friend/workflow :api-workflow})))]
          (workflows/make-auth user-record
                     {::friend/workflow :api-workflow
                      ::friend/redirect-on-auth? false})
          ((or (gets :login-failure-handler form-config (::friend/auth-config request))
               (fn [handler] {:status 400 :body "Incorrect credentials for API authentication."}))
           (update-in request [::friend/auth-config] merge form-config)))))))

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions