Skip to content

Instantly share code, notes, and snippets.

@hakunin
Last active May 15, 2017 18:47
Show Gist options
  • Save hakunin/292bcd45724cdfbab720d1eb8922f5f7 to your computer and use it in GitHub Desktop.
Save hakunin/292bcd45724cdfbab720d1eb8922f5f7 to your computer and use it in GitHub Desktop.
Coinbase Oauth2 strategy for elixir / phoenix.
defmodule Myapp.Web.AuthController do
use BlockViz.Web, :controller
def connect(conn, _params) do
conn |> redirect(external: BlockViz.Oauth2.Strategies.Coinbase.authorize_url!)
end
def callback(conn, params) do
IO.inspect params
client = BlockViz.Oauth2.Strategies.Coinbase.get_token!(code: params["code"])
changeset = %{
name: "Coinbase wallet",
type: "coinbase",
data: "{}",
user_id: Coherence.current_user(conn).id,
access_token: client.token.access_token,
refresh_token: client.token.refresh_token,
}
case MyApp.Accounts.create_connection(changeset) do
{:ok, struct} ->
conn
|> put_flash(:info, "Coinbase added!")
|> redirect(to: auth_path(conn, :index))
{:error, changeset} ->
conn
|> put_flash(:info, "There was a problem with adding Coinbase.")
|> redirect(to: auth_path(conn, :index))
end
end
end
defmodule MyApp.Oauth2.Strategies.Coinbase do
use OAuth2.Strategy
# Public API
def client do
OAuth2.Client.new([
strategy: __MODULE__,
client_id: System.get_env("COINBASE_CLIENT_ID"),
client_secret: System.get_env("COINBASE_CLIENT_SECRET"),
redirect_uri: System.get_env("COINBASE_REDIRECT_URI"),
site: "https://api.coinbase.com",
authorize_url: "https://www.coinbase.com/oauth/authorize",
token_url: "https://api.coinbase.com/oauth/token"
])
end
def authorize_url! do
OAuth2.Client.authorize_url!(client(), scope: "wallet:user:read")
end
# you can pass options to the underlying http library via `opts` parameter
def get_token!(params \\ [], headers \\ [], opts \\ []) do
OAuth2.Client.get_token!(client(), params, headers, opts)
end
# Strategy Callbacks
def authorize_url(client, params) do
OAuth2.Strategy.AuthCode.authorize_url(client, params)
end
def get_token(client, params, headers) do
client
|> put_param(:client_secret, client.client_secret)
|> put_header("accept", "application/json")
|> OAuth2.Strategy.AuthCode.get_token(params, headers)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment