BACK

0
Posted by albydarned 1 month ago
How to use the OAuth2 Library (https://github.com/scrogson/oauth2) to connect with GitHub in Elixir. ...

defmodule App.GitHub do
  use OAuth2.Strategy

  # Public API

  def client do
    OAuth2.Client.new([
      strategy: __MODULE__,
      client_id: Application.get_env(:app, :github_client_id),
      client_secret: Application.get_env(:app, :github_client_secret),
      redirect_uri: "https://localhost:4000/auth/github/callback",
      site: "https://api.github.com",
      authorize_url: "https://github.com/login/oauth/authorize",
      token_url: "https://github.com/login/oauth/access_token"
    ])
    |> OAuth2.Client.put_serializer("application/json", Jason)
  end

  def authorize_url! do
    OAuth2.Client.authorize_url!(client(), scope: "read:user,user:email,gist")
  end

  def get_token!(params \\ [], headers \\ [], opts \\ []) do
    client = OAuth2.Client.get_token!(client(), params, headers, opts)

    if is_nil client.token.access_token do
      raise "Could not get token #{client.token["error"]} #{client.token["error_description"]}"
    end

    client

  end

  def get_user!(client) do
    token = client.token.access_token

    OAuth2.Client.get!(client, "/user").body
  end

end