Skip to content

Instantly share code, notes, and snippets.

@arifian
Last active June 25, 2018 13:03
Show Gist options
  • Save arifian/865245e309321359dbf04b544c5e6063 to your computer and use it in GitHub Desktop.
Save arifian/865245e309321359dbf04b544c5e6063 to your computer and use it in GitHub Desktop.
Clojure - Pedestal - Oauth2 - Google sign-in example. inspired by: https://blog.knoldus.com/2014/04/05/google-sign-in-using-clojure/
(ns oauth-google
(:require
[io.pedestal.interceptor :refer [interceptor]]
[io.pedestal.interceptor.chain :refer [terminate]]
[io.pedestal.http :as http]
[io.pedestal.log :as log]
[cheshire.core :as cheshire]
[clj-http.client :as client-clj]
[ring.util.response :as ring-resp]
[ring.util.codec :as codec]))
(def google-red
{:name ::google-red
:enter (fn [{{:keys [session form-params] :as request} :request
response :response
datomic :datomic
config :config
:as context}]
(let [gcreds (->> config :oauth2-creds :google)
red (str "https://accounts.google.com/o/oauth2/auth?"
"scope=email%20profile&"
"redirect_uri=" (codec/url-encode (->> gcreds :redirect-uri)) "&"
"response_type=code&"
"client_id=" (codec/url-encode (->> gcreds :client-id)) "&"
"approval_prompt=force")]
(assoc context :response (ring-resp/redirect red))))})
(defn google [q-params client-id client-secret redirect-uri]
(let [access-token-response (->> {:form-params {:code (->> q-params :code)
:client_id client-id
:client_secret client-secret
:redirect_uri redirect-uri
:grant_type "authorization_code"}}
(client-clj/post "https://accounts.google.com/o/oauth2/token"))
access-token (get (->> access-token-response :body cheshire/parse-string) "access_token")
user-details (->> access-token
(str "https://www.googleapis.com/oauth2/v1/userinfo?access_token=")
client-clj/get
:body
cheshire/parse-string)]
user-details))
(def oauth2-google
{:name ::oauth2-google
:enter (fn [{{:keys [session form-params query-params] :as request} :request
response :response
datomic :datomic
config :config
:as context}]
(let [gcreds (->> config :oauth2-creds :google)]
(clojure.pprint/pprint (google query-params
(->> gcreds :client-id)
(->> gcreds :client-secret)
(->> gcreds :redirect-uri)))))})
(comment
"You can't use this directly on repl, notice that client-id, redirect-uri and client-secret taken out from the context's config"
"You need to have a running pedestal service"
"res ex"
{"verified_email" true,
"id" "5264680293438599876546",
"gender" "male",
"email" "arifian.r@gmail.com",
"given_name" "Arifian",
"name" "Arifian Rahardianda",
"locale" "en",
"link" "https://plus.google.com/105468029343859983435",
"picture"
"https://lh5.googleusercontent.com/-r7Y25M7Ozn4/AAAAAAAAAAI/AAAAAAAAAPE/AuBdJkT4ktM/photo.jpg",
"family_name" "Rahardianda"})
(def routes
[["/google" :get [google-red] :route-name :google-red]
["/auth_google" :get [oauth2-google] :route-name :oauth2-google]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment