Skip to content

Instantly share code, notes, and snippets.

Last active May 11, 2022 06:54
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save benjamin-asdf/ed35f92dad7f3e50ac7a253cb59704f9 to your computer and use it in GitHub Desktop.
Ths is for requesting tokens for a google service
[cheshire.core :as json]
[babashka.curl :as curl]
[buddy.core.keys :as keys]
[buddy.sign.jwt :as jwt]
[clojure.string :as str])
(set! *warn-on-reflection* true)
(defn load-creds
"Takes a path to a service account .json credentials file"
(-> secrets-json-path slurp (json/parse-string keyword)))
[creds & [{:keys [sub scopes]}]]
(let [^java.time.Instant now (java.time.Instant/now)
claim (merge
{:iss (:client_email creds)
:scope (str/join " " scopes)
:aud ""
:exp (+ (.getEpochSecond now) (* 60 60))
:iat (.getEpochSecond now)}
;; when using the Admin API, delegating access, :sub may be needed
{:sub sub}))]
(:private_key creds))
{:alg :rs256})))
(defn request-token [creds opts]
(let [claim (create-claim creds opts)
resp (curl/post
{:grant_type "urn:ietf:params:oauth:grant-type:jwt-bearer"
:assertion claim}
:as :json})]
(if (= 200 (-> resp :status))
(-> resp :body (json/decode keyword) :access_token)
[request token]
(assoc-in [:headers "Authorization"] (str "Bearer " token))))
(defn -main [credentials-path & scopes]
(load-creds credentials-path)
{:scopes scopes})))
(load-creds "/home/benj/tmp/alert-drive-creds.json")
{:scopes [""]}))
(:deps {babashka/babashka.curl {:mvn/version "0.1.2"}
cheshire/cheshire {:mvn/version "5.10.2"}
babashka/fs {:mvn/version "0.1.6"}
org.clojure/data.csv {:mvn/version "1.0.1"}
buddy/buddy-sign {:mvn/version "3.4.333"}
buddy/buddy-core {:mvn/version "1.10.413"}})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment