lib/google_auth_set.ex

defmodule PlugParadoxAuth.GoogleAuthSet do
  import Plug.Conn

  def init(options) do
    options
  end

  def call(conn, _opts) do
    with %{params: %{"code" => code}} <- conn,
          {:ok, %{access_token: token}} <- ElixirAuthGoogle.get_token(code, conn),
          {:ok, %{hd: domain, email: email}} <- ElixirAuthGoogle.get_user_profile(token)
    do
      if domain != "paradox.ai" do
        send_resp(conn, 403, "Google user must belong to paradox.ai")
      else
        url = conn |> fetch_session |> get_session(:google_auth_success_url)
        conn = delete_session(conn, :google_auth_success_url)

        conn
        |> fetch_session
        |> put_session(:google_user, email)
        |> put_resp_header("location", url)
        |> send_resp(302, "text/html")
      end
    else
      error ->
        conn
        |> send_resp(400, inspect(error))
    end
  end
end