lib/google_auth_set.ex

defmodule PlugParadoxAuth.GoogleAuthSet do
  import Plug.Conn

  def init(options) do
    options
  end

  def call(conn, _opts) do
    %{params: %{"code" => code}} = conn
    {:ok, token} = ElixirAuthGoogle.get_token(code, conn)
    # TODO make sure this is a paradox profile
    {:ok, profile} = ElixirAuthGoogle.get_user_profile(token.access_token)

    if profile.hd != "paradox.ai" do
      send_resp(conn, 403, "User must belong to paradox.ai")
    else
      # https://github.com/elixir-plug/plug/issues/1017
      url = conn |> fetch_session |> get_session(:google_auth_success_url)

      conn
      |> fetch_session
      |> put_session(:google_user, profile.email)
      |> put_resp_header("location", url)
      |> send_resp(302, "text/html")
    end
  end
end