peburrows / goth

Elixir package for Oauth authentication via Google Cloud APIs
http://hexdocs.pm/goth
MIT License
284 stars 108 forks source link

How to do impersonalisation? #96

Closed sam701 closed 3 years ago

sam701 commented 3 years ago

I'd like to call Gmail API with a service account key. Goth 1.2.0 has Goth.Token.for_scope/2, where I can put the user ID in the second argument. But how can I achieve the same with Goth 1.3.0?

Here is my code

  def start_goth do
    info("Starting goth")
    credentials = Application.fetch_env!(:my_app, :gmail_token_file)
      |> Path.expand()
      |> File.read!()
      |> Jason.decode!()
    source = {:service_account, credentials, scope: "https://www.googleapis.com/auth/gmail.readonly"}
    children = [{Goth, name: :my_goth, source: source}]
    {:ok, _} = Supervisor.start_link(children, strategy: :one_for_one)

    {:ok, token} = Goth.fetch(:my_goth)
    conn = GoogleApi.Gmail.V1.Connection.new(token.token)
    warn("token: #{inspect(token)}")

    GoogleApi.Gmail.V1.Api.Users.gmail_users_messages_list(conn, "abc@example.com", [maxResults: 10])
  end
wojtekmach commented 3 years ago

Thanks for the report, I just added a support for a :sub option on master. You'd use it like this:

source = {:service_account, credentials, scope: "https://www.googleapis.com/auth/gmail.readonly", sub: "abc@example.com"}

please try it out and let us know if you run into any issues!

sam701 commented 3 years ago

@wojtekmach It works. Thanks a bunch for the quick fix. 👍