4.8 KiB · text History bbb2a48
defmodule VigilWeb.InviteController do
  @moduledoc """
  The ways on from a registration invite link (`/users/register?invite=…`,
  `Vigil.Accounts.Invite`) for someone signed out, which need the session
  (a LiveView can't set it).

  Locally, an addressed invite makes the account for its address,
  confirmed, and signs them in (`register_invited/2`). An unaddressed one is
  spent by the registration form itself (`VigilWeb.UserLive.Registration`).

  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` remembers the invite before sending
  the browser to NEIAM, and `Vigil.NeiamAuthAdapter.handle_error/2` sends a
  refused login back to that invite. There `register_sso/2` makes the
  account (the invite's address, or else the one NEIAM gave), spends the
  invite and links 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 VigilWeb, :controller

  alias Vigil.{Accounts, Repo}
  alias VigilWeb.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 :vigil_invite
  @invite_sso :vigil_invite_sso
  @sso_email :vigil_sso_email

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

  # 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
          # 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_flash(:info, "Welcome to Vigil!")
          |> 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: remembered, so a login
  # refused as not invited comes back to it.
  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, token) do
        Repo.transact(fn ->
          with {:ok, user} <- Accounts.register_by_invite(token, get_session(conn, @sso_email)) do
            linked(conn, user)
          end
        end)
      end

    case result do
      {:ok, {conn, user}} ->
        conn
        |> clear_sso()
        |> put_flash(:info, "Welcome to Vigil!")
        |> 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

  # The adapter marks which invite a refused NEIAM login came back to: only
  # that one may be accepted with it.
  defp pending_for(conn, token) do
    if get_session(conn, @invite_sso) == 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) do
    conn = NeiamAuth.link_pending(conn, user)

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

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