Last active
February 14, 2024 02:13
-
-
Save kurtharriger/7bd07ef03a9b28725f6f765f085455ac to your computer and use it in GitHub Desktop.
electric clojure server auth
This file contains hidden or 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
#?(:cljs (def !client-jwt-token (atom nil))) | |
(def !user (atom nil)) | |
(e/def user (e/watch !user)) | |
(def ^:dynamic *user* nil) | |
(e/defn ProvideUserContext [] | |
(e/client | |
(let [token (.getItem js/localStorage token-local-storage-key)] | |
(reset! !client-jwt-token token))) | |
(e/client | |
(let [token (e/watch !client-jwt-token)] | |
(.setItem js/localStorage token-local-storage-key token) | |
; token can techically be decoded on client side | |
; but need the public key to validate signature and have not | |
; yet created a endpoint to expose public key | |
; it can also be decoded without validation but an inavlid | |
; token will just result in future errors when token is validated | |
; on server | |
(reset! !user (when token (e/server (jwt/read-token token))))))) | |
#?(:clj | |
(defn print-user [] | |
(println "user" *user*) | |
(println "user" user))) | |
#?(:clj | |
(defn with-auth [token f & args] | |
(binding [*user* (when token (jwt/read-token token))] | |
(apply f args)))) | |
(e/defn PrintUserButton [] | |
(e/client | |
(ui/button | |
(e/fn [] | |
(let [token (e/watch !client-jwt-token)] | |
(println "token" token) | |
(e/server | |
(println "token" token) | |
; electric seems to intercept binding and complain *user* its not an electric def | |
; further more if I make it a electric def it semes to be wrapped in | |
; #object[hyperfiddle.electric.impl.lang$electric_only | |
#_(binding [user (when token (jwt/read-token token))] | |
(print-user)) | |
(with-auth token print-user)))) | |
(dom/text "Print User")))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Better solution: add atom to the e/http-request object and store data there