Created
April 2, 2016 04:13
-
-
Save mrmcc3/ef016f2362cb58f8a6834bcd11eedea6 to your computer and use it in GitHub Desktop.
Generate Firebase JWTs in Clojure (with buddy-sign)
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 tokens | |
(:require [buddy.sign.jws :as jws] | |
[buddy.sign.util :refer [to-timestamp]] | |
[clj-time.core :as time])) | |
;; see https://www.firebase.com/docs/rest/guide/user-auth.html#section-token-generation | |
(defn firebase-token | |
"generates a firebase JWT. (generated JWT must be less than 1024 characters) | |
a nil token is returned if requirements aren't met | |
(Required args) | |
uid is a unique identifier (must be lest than 256 characters) | |
data is a map (accessible in firebase rules as auth. not encrypted!) | |
secret is a firebase secret used to sign the JWT | |
(Optional keyword args) | |
exp is the number of hours (from time of generation) until the JWT expires (default 24 hours) | |
nbf is the number of hours (from time of generation) until the JWT is valid (default is 0) | |
admin if true grants complete read/write access to the entire firebase (default is false) | |
debug if true enables debug mode (more verbose error messages) (default is false) | |
" | |
[uid data secret & {:keys [exp nbf admin debug]}] | |
(let [now (time/now) | |
add-hours #(to-timestamp (time/plus %1 (time/hours %2))) | |
payload {:v 0 :d (assoc data :uid uid) :iat (to-timestamp now)} | |
token (when (< (count uid) 256) | |
(cond-> payload | |
exp (assoc :exp (add-hours now exp)) | |
nbf (assoc :nbf (add-hours now nbf)) | |
admin (assoc :admin true) | |
debug (assoc :debug true) | |
true (jws/sign secret)))] | |
(when (< (count token) 1024) token))) | |
(comment | |
(-> (firebase-token "test" {:some "data"} "firebase secret key" :exp 36) | |
(jws/unsign "firebase secret key")) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment