Skip to content

Instantly share code, notes, and snippets.

@tvaisanen
Created May 17, 2021 05:44
Show Gist options
  • Save tvaisanen/f8c77a4f9cdf1e71c2a20c8b400989e7 to your computer and use it in GitHub Desktop.
Save tvaisanen/f8c77a4f9cdf1e71c2a20c8b400989e7 to your computer and use it in GitHub Desktop.
(ns project.auth0
(:require [re-frame.core :as rf]
[ajax.core :as ajax]
["@auth0/auth0-spa-js" :as spa]
[reitit.frontend.easy :as rfe]
[clojure.string :as str])
(:import [goog.history Html5History]))
(defonce client
(spa/Auth0Client.
(clj->js {:client_id js/window.auth0FrontendClientId
:domain js/window.auth0Domain
:redirect_uri (-> js/window .-location .-href)
:advancedOptions {:defaultScope "email"}})))
(rf/reg-event-db
::logout
(fn [db [_ profile]]
(assoc db :user nil)))
(rf/reg-event-fx
::set-user-claims
(fn [cofx [_ claims]]
{:db (assoc (:db cofx)
:user
{:id-token (:__raw claims)
:profile (dissoc claims :__raw)})
:fx []}))
(rf/reg-sub
:user/id-token
(fn [db _]
(get-in db [:user :id-token])))
(rf/reg-sub
:user/profile
(fn [db _]
(get-in db [:user :profile])))
(defn swap-hash-n-search
"
Reroute from Auth0 causes the url be in form:
search -> hash and this interferes with the routing
use this function in window load to swap the search
and hash"
[]
(let [loc js/window.location
swapped (str loc.pathname loc.hash loc.search)]
(.replaceState js/window.history nil {} swapped)))
(defn url-search-params []
(-> js/window.location.href
(str/split "?")
(get 1)
(js/URLSearchParams.)))
(defn should-handle-redirect
"Handle auth0 redirect?"
[]
(let [params (url-search-params)]
(and
(.has params "state")
(.has params "code"))))
(defn auth-action-to-take []
(pr "What auth action to take?")
(if (should-handle-redirect)
:handle-redirect
:load-silently))
(defn id-token-claims-to-user [claims]
(let [claims-map (js->clj claims :keywordize-keys true)]
(rf/dispatch [::set-user-claims claims-map])))
(defn load-profile
"Should be an effect"
[]
(->
(.getIdTokenClaims client)
(.then id-token-claims-to-user)))
(defn handle-auth-redirect []
(->
(.handleRedirectCallback client)
(.then load-profile)))
(defn load-silently []
(pr "load silently")
(-> (.getTokenSilently client)
(.then load-profile)
(.catch #(pr %))))
(defn on-window-load []
(swap-hash-n-search)
(let [action (auth-action-to-take)]
(pr action)
(case action
:handle-redirect (handle-auth-redirect)
:load-silently (load-silently)
(pr "no action"))))
(defn login [] (.loginWithRedirect client))
(defn logout [] (->
(.logout client)
(.then #(rf/dispatch [::logout]))
(.finally #(.clear js/window.sessionStorage))))
(.addEventListener js/window "load" on-window-load)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment