Skip to content

Instantly share code, notes, and snippets.

@iancharters
Created April 19, 2019 06:09
Show Gist options
  • Save iancharters/8f71cf4f36811cb6b9e19b4da0194685 to your computer and use it in GitHub Desktop.
Save iancharters/8f71cf4f36811cb6b9e19b4da0194685 to your computer and use it in GitHub Desktop.
defmodule Api.OAuth.Github do
use OK.Pipe
@authorize_url "https://github.com/login/oauth/authorize"
@token_url "https://github.com/login/oauth/access_token"
@api_url_base "https://api.github.com"
@base_url "http://localhost:4000"
@client_id System.get_env("GITHUB_CLIENT_ID")
@client_secret System.get_env("GITHUB_CLIENT_SECRET")
def client(token) do
middleware = [
{Tesla.Middleware.BaseUrl, @api_url_base},
Tesla.Middleware.JSON,
{Tesla.Middleware.Headers,
[
{"authorization", "token: " <> token},
{"User-Agent", "AuthKit:#{@client_id}"}
]}
]
Tesla.client(middleware)
end
def get_url(state) do
Tesla.get(@authorize_url,
query: [
response_type: "code",
client_id: @client_id,
state: state,
redirect_uri: @base_url <> "/test"
]
)
~>> Map.get(:headers)
|> Enum.find(fn {x, _} -> x == "location" end)
|> elem(1)
end
def get_token(code) do
Tesla.get(@token_url,
query: [
grant_type: "authorization_code",
client_id: @client_id,
client_secret: @client_secret,
redirect_uri: @base_url <> "/test",
code: code
]
)
~>> Map.get(:body)
|> URI.decode_query()
|> Map.get("access_token")
end
def generate_state do
:crypto.strong_rand_bytes(25)
|> Base.url_encode64()
|> binary_part(0, 25)
end
def user_repos(client, username) do
Tesla.get(client, "/users/" <> username <> "/repos")
end
def user_installations(client, username) do
Tesla.get(client, "/user/installations")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment