Skip to content

Instantly share code, notes, and snippets.

@realyze
Created November 23, 2014 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save realyze/faf8c79bd18287ba3f67 to your computer and use it in GitHub Desktop.
Save realyze/faf8c79bd18287ba3f67 to your computer and use it in GitHub Desktop.
(ns myApp.auth.google
"Google OAuth2 authentication using Friend auth framework."
(:require [compojure.core :refer :all]
[compojure.handler :as handler]
[compojure.route :as route]
[cheshire.core :as j]
[clj-http.client :as client]
[clojure.string :refer [split]]
[environ.core :refer [env]]
[taoensso.timbre :as timbre]
[myApp.auth.roles :as roles]
[cemerick.friend :as friend]
(cemerick.friend [workflows :as workflows]
[credentials :as creds])
[friend-oauth2.workflow :as oauth2]
[friend-oauth2.util :refer [format-config-uri]]))
;; OAuth env vars
(def ^:private domain (env :domain))
(def ^:private google-client-id (env :google-client-id))
(def ^:private google-client-secret (env :google-client-secret))
;; Email domains allowed to sign in.
(def allowed-domains ["salsitasoft.com"])
(def client-config
{:client-id google-client-id
:client-secret google-client-secret
:callback {:domain domain :path "/oauth2callback"}})
(def uri-config
{:authentication-uri {:url "https://accounts.google.com/o/oauth2/auth"
:query {:client_id (:client-id client-config)
:response_type "code"
:redirect_uri (format-config-uri client-config)
:scope "email"}}
:access-token-uri {:url "https://accounts.google.com/o/oauth2/token"
:query {:client_id (:client-id client-config)
:client_secret (:client-secret client-config)
:grant_type "authorization_code"
:redirect_uri (format-config-uri client-config)}}})
(defn allowed-email?
"Returns true iff `email` is allowed to be used to log in."
[email]
(if-not email false
(let [domain (last (split email #"@"))]
(some #{domain} allowed-domains))))
(defn credential-fn
"Credential fun for our Google OAuth2 Friend workflow."
[creds]
(let [token (:access-token creds)
res (client/get "https://www.googleapis.com/oauth2/v1/userinfo"
{:query-params {:access_token token}
:as :json})
email (get-in res [:body :email])]
(if (allowed-email? email)
(do
(timbre/info "Successfully logged in")
{:identity token :roles #{roles/user} :email email})
(do
(timbre/info "Email" email "not allowed. Logging in as anonymous.")
{:identity token :roles #{roles/anonymous} :email email}))))
(def friend-config
{:allow-anon? true
:default-landing-uri "/"
:login-uri "/login"
:workflows [(oauth2/workflow
{:client-config client-config
:uri-config uri-config
:credential-fn credential-fn})]})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment