/
google_auth.clj
61 lines (54 loc) · 1.79 KB
/
google_auth.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
(ns nsfw.google-auth
(:require [nsfw.util :as util]
[nsfw.http-client :as hc]
[clj-jwt.core :as jwt]))
(defn exchange [ring-req
{:keys [client-id
client-secret
redirect-uri]}]
(let [code (-> ring-req :params :code)
{:keys [status body] :as resp}
(hc/request
{:method :post
:url "https://www.googleapis.com/oauth2/v3/token"
:query-params
{:code code
:client_id client-id
:client_secret client-secret
:grant_type "authorization_code"
:redirect_uri redirect-uri}})
{:keys [error
error_description
access_token
id_token]} (util/from-json body)]
(if error
{:success? false :error-code error :error error_description}
(let [jwt (jwt/str->jwt id_token)
{:keys [email email_verified]} (:claims jwt)]
{:success? true
:access-token access_token
:email email :email-verified? email_verified
:jwt (into {} jwt)}))))
(defn handler [opts f]
(fn [r] (f r (exchange r opts))))
(defn button [])
#_(exchange
{:params {:code "foo"}}
{:client-id "485322283358-kb9f73crtfsdqkseh60ko09nojj6654b.apps.googleusercontent.com"
:client-secret "LRuB8djiGO_68TVz7uz1BzcO"
:redirect-uri "http://localhost:8080/admin-login/callback"})
(defn sign-in-url [{:keys [client-id redirect-uri]}]
(str
"https://accounts.google.com/o/oauth2/auth?"
"response_type=code"
"&"
"client_id=" client-id
"&"
"redirect_uri=" (util/url-encode redirect-uri)
"&"
"scope=email"))
(defn sign-in-link [opts & children]
(vec
(concat
[:a.ga-sign-in {:href (sign-in-url opts)}]
children)))