8.9 KiB · text History e569b6d
defmodule CartosnapAppWeb.InviteController do
  @moduledoc """
  The ways on from an invite link for someone signed out, which need the
  session (a LiveView can't set it). Two kinds of invite let someone make an
  account while registration is closed: registration invites
  (`/users/register?invite=…`, `CartosnapApp.Accounts.Invite`) and trip
  invites (`/trips/join/…`).

  Locally:

    * an addressed invite makes the account for its address, confirmed, and
      signs them in (`register_invited/2`, `join/2`);
    * otherwise they register by email with the invite, or log in, and come
      back (`register/2`, `log_in/2`).

  With NEIAM (`OIDC_PROVISION=invite_only`, as the siblings), a first NEIAM
  login with no account is refused as not invited and kept pending by
  neiam_auth. So `registration_sso/2` and `trip_sso/2` remember the invite
  before sending the browser to NEIAM, and
  `CartosnapApp.NeiamAuthAdapter.handle_error/2` sends a refused login back
  to that invite. There `register_sso/2` and `join_sso/2` make the account
  (the invite's address, or else the one NEIAM gave), spend the invite and
  link the pending login to it (`NeiamAuth.link_pending/2`). Nothing is made
  without that pending login. The same works in `sso_strict`, where it is
  the only way to a new account.
  """
  use CartosnapAppWeb, :controller

  alias CartosnapApp.{Accounts, Repo, Trips}
  alias CartosnapAppWeb.UserAuth

  # Session keys: the invite a NEIAM login is for, then (set by the
  # adapter) the invite a refused login came back to, and the address it
  # brought.
  @invite :cartosnap_invite
  @trip_invite :cartosnap_trip_invite
  @invite_sso :cartosnap_invite_sso
  @trip_invite_sso :cartosnap_trip_invite_sso
  @sso_email :cartosnap_sso_email

  @doc false
  def session_keys,
    do: %{
      invite: @invite,
      trip_invite: @trip_invite,
      invite_sso: @invite_sso,
      trip_invite_sso: @trip_invite_sso,
      sso_email: @sso_email
    }

  ## Trip invites

  def join(%{assigns: %{current_scope: %{user: %{}}}} = conn, %{"token" => token}) do
    # Signed in already: the invite page has the Join button.
    redirect(conn, to: ~p"/trips/join/#{token}")
  end

  def join(conn, %{"token" => token}) do
    if NeiamAuth.local_login_enabled?() do
      join_with_new_account(conn, token)
    else
      # OIDC_LOGIN_MODE=sso_strict: accounts come only through NEIAM.
      conn
      |> put_flash(:info, "Sign in with NEIAM to accept the invite.")
      |> log_in(%{"token" => token})
    end
  end

  defp join_with_new_account(conn, token) do
    case Trips.join_by_invite(token) do
      {:ok, user, trip} ->
        conn
        # A "Sign in with NEIAM" refused as not invited, earlier in this
        # browser, is linked to the new account (before log_in_user renews
        # the session and drops it).
        |> NeiamAuth.link_pending(user)
        |> put_session(:user_return_to, ~p"/trips/#{trip}")
        |> put_flash(:info, "Welcome to #{trip.name}! Add your photos to the album.")
        |> UserAuth.log_in_user(user)

      {:error, :has_account} ->
        conn
        |> put_flash(:error, "That address already has an account. Log in to accept the invite.")
        |> log_in(%{"token" => token})

      {:error, :not_addressed} ->
        conn
        |> put_flash(:error, "Log in or register to accept this invite.")
        |> redirect(to: ~p"/trips/join/#{token}")

      {:error, _} ->
        conn
        |> put_flash(:error, "That invite link doesn't work any more.")
        |> redirect(to: ~p"/trips/join/#{token}")
    end
  end

  def log_in(conn, %{"token" => token}) do
    conn
    |> put_session(:user_return_to, ~p"/trips/join/#{token}")
    |> redirect(to: ~p"/users/log-in")
  end

  # Registering from a trip invite: UserLive.Registration lets them in on
  # it while registration is closed, and spends it on the new account.
  def register(conn, %{"token" => token}) do
    conn
    |> put_session(:user_return_to, ~p"/trips/join/#{token}")
    |> put_session(@trip_invite, token)
    |> redirect(to: ~p"/users/register")
  end

  # "Sign in with NEIAM" from a trip invite: remembered, so a login refused
  # as not invited comes back to it. One that succeeds returns to the
  # invite page, signed in, to join.
  def trip_sso(conn, %{"token" => token, "provider" => id}) do
    case NeiamAuth.config(id) do
      {:ok, provider} ->
        conn
        |> put_session(@trip_invite, token)
        |> redirect(
          to: NeiamAuth.Components.login_href(provider.id, ~p"/trips/join/#{token}", false)
        )

      _ ->
        conn
        |> put_flash(:error, "That sign-in isn't available.")
        |> redirect(to: ~p"/trips/join/#{token}")
    end
  end

  def join_sso(conn, %{"token" => token}) do
    result =
      with :ok <- pending_for(conn, @trip_invite_sso, token) do
        Repo.transact(fn ->
          with {:ok, user, trip} <- Trips.join_by_invite(token, get_session(conn, @sso_email)) do
            linked(conn, user, trip)
          end
        end)
      end

    case result do
      {:ok, {conn, user, trip}} ->
        conn
        |> clear_sso()
        |> put_session(:user_return_to, ~p"/trips/#{trip}")
        |> put_flash(:info, "Welcome to #{trip.name}! Add your photos to the album.")
        |> UserAuth.log_in_user(user)

      {:error, :has_account} ->
        conn
        |> put_flash(:error, "That address already has an account. Log in to accept the invite.")
        |> log_in(%{"token" => token})

      {:error, :not_signed_in} ->
        conn
        |> put_flash(:error, "Sign in with NEIAM first, then accept the invite.")
        |> redirect(to: ~p"/trips/join/#{token}")

      {:error, _} ->
        conn
        |> put_flash(:error, "That invite link doesn't work any more.")
        |> redirect(to: ~p"/trips/join/#{token}")
    end
  end

  ## Registration invites

  # An invite addressed to an email, signed out, NEIAM aside: make that
  # account (confirmed by the link), spend the invite and sign in. The
  # registration page posts here.
  def register_invited(conn, %{"invite" => token}) when is_binary(token) do
    if NeiamAuth.local_login_enabled?() do
      case Accounts.register_by_invite(token) do
        {:ok, user} ->
          conn
          |> NeiamAuth.link_pending(user)
          |> put_flash(:info, "Welcome to CartoSnap!")
          |> UserAuth.log_in_user(user)

        error ->
          registration_error(conn, error)
      end
    else
      conn
      |> put_flash(:error, "Sign in with NEIAM to accept the invite.")
      |> redirect(to: ~p"/users/register?#{[invite: token]}")
    end
  end

  # "Sign in with NEIAM" from a registration invite: as trip_sso/2.
  def registration_sso(conn, %{"invite" => token, "provider" => id}) when is_binary(token) do
    case NeiamAuth.config(id) do
      {:ok, provider} ->
        conn
        |> put_session(@invite, token)
        |> redirect(to: NeiamAuth.Components.login_href(provider.id, nil, false))

      _ ->
        conn
        |> put_flash(:error, "That sign-in isn't available.")
        |> redirect(to: ~p"/users/register?#{[invite: token]}")
    end
  end

  def register_sso(conn, %{"invite" => token}) when is_binary(token) do
    result =
      with :ok <- pending_for(conn, @invite_sso, token) do
        Repo.transact(fn ->
          with {:ok, user} <- Accounts.register_by_invite(token, get_session(conn, @sso_email)) do
            linked(conn, user, nil)
          end
        end)
      end

    case result do
      {:ok, {conn, user, nil}} ->
        conn
        |> clear_sso()
        |> put_flash(:info, "Welcome to CartoSnap!")
        |> UserAuth.log_in_user(user)

      {:error, :not_signed_in} ->
        conn
        |> put_flash(:error, "Sign in with NEIAM first, then accept the invite.")
        |> redirect(to: ~p"/users/register?#{[invite: token]}")

      error ->
        registration_error(conn, error)
    end
  end

  defp registration_error(conn, {:error, :has_account}) do
    conn
    |> put_flash(:error, "That address already has an account. Log in instead.")
    |> redirect(to: ~p"/users/log-in")
  end

  defp registration_error(conn, _error) do
    conn
    |> put_flash(:error, "That invite link doesn't work any more.")
    |> redirect(to: ~p"/users/register")
  end

  ## NEIAM

  # The adapter marks which invite a refused NEIAM login came back to: only
  # that one may be accepted with it.
  defp pending_for(conn, key, token) do
    if get_session(conn, key) == token, do: :ok, else: {:error, :not_signed_in}
  end

  # Links this browser's pending NEIAM login to the new account; without
  # one (expired, say) nothing is made: the transaction rolls back.
  defp linked(conn, user, trip) do
    conn = NeiamAuth.link_pending(conn, user)

    if NeiamAuth.identities(user) == [],
      do: {:error, :not_signed_in},
      else: {:ok, {conn, user, trip}}
  end

  defp clear_sso(conn) do
    [@invite, @trip_invite, @invite_sso, @trip_invite_sso, @sso_email]
    |> Enum.reduce(conn, &delete_session(&2, &1))
  end
end