10.9 KiB · text History 573fef1
defmodule VigilWeb.UserLive.Registration do
  @moduledoc """
  Sign-up. Invite-only unless registration is open
  (`Vigil.Accounts.registration_open?/0`), as the sibling apps:

    * no invite: a notice, and no form;
    * a registration invite addressed to an email: one button makes that
      account, confirmed, and signs them in
      (`VigilWeb.InviteController.register_invited/2`);
    * an unaddressed one: the usual email form, which spends the invite on
      the new account;
    * NEIAM, from an invite: out through `InviteController` so a first
      login comes back here, then one button accepts the invite with it
      (`InviteController.register_sso/2`). Under `OIDC_LOGIN_MODE=sso_strict`
      that is the only way, and with no invite the page sends them to log in.
  """
  use VigilWeb, :live_view

  alias Vigil.Accounts
  alias Vigil.Accounts.User

  @impl true
  def render(assigns) do
    ~H"""
    <Layouts.app flash={@flash} current_scope={@current_scope}>
      <div class="shader-glass mx-auto max-w-sm space-y-6">
        <div class="text-center">
          <.header>
            {if @invite, do: "Accept your invite", else: "Register for an account"}
            <:subtitle>
              Already registered?
              <.link navigate={~p"/users/log-in"} class="font-semibold text-brand hover:underline">
                Log in
              </.link>
              to your account now.
            </:subtitle>
          </.header>
        </div>

        <%= cond do %>
          <% @has_account? -> %>
            <div
              id="registration-has-account"
              class="space-y-4 rounded-box border border-base-300 bg-base-200 p-6 text-sm"
            >
              <p>
                <span class="font-mono">{@invite.email}</span>
                already has an account, so there's nothing to register. Log in with it instead.
              </p>
              <.link id="invite-log-in" navigate={~p"/users/log-in"} class="btn btn-primary w-full">
                Log in
              </.link>
            </div>
          <% @gated -> %>
            <div id="registration-gated" class="alert alert-warning">
              <.icon name="hero-lock-closed" class="size-5" />
              <div>
                <p class="font-semibold">Registration is invite-only.</p>
                <p class="text-sm">
                  You'll need an invite link from someone already here.
                </p>
              </div>
            </div>
          <% @sso_pending? -> %>
            <%!-- Back from NEIAM, refused as not invited (and so pending):
                 accepting the invite makes the account and links the login. --%>
            <.form
              for={%{}}
              id="invite-sso-accept"
              action={~p"/users/register/invite/sso"}
              class="space-y-3 rounded-box border border-primary/40 bg-base-100 p-5"
            >
              <input type="hidden" name="invite" value={@invite_token} />
              <p class="text-sm">
                You're signed in with NEIAM<span :if={@sso_email}> as <span class="font-mono">{@sso_email}</span></span>.
                <%= if @invite.email do %>
                  This makes your Vigil account for <span class="font-mono">{@invite.email}</span>, signed in with NEIAM from now on.
                <% else %>
                  This makes your Vigil account, signed in with NEIAM from now on.
                <% end %>
              </p>
              <button type="submit" class="btn btn-primary w-full" phx-disable-with="Creating…">
                Create my account
              </button>
            </.form>
          <% not @local? -> %>
            <%!-- OIDC_LOGIN_MODE=sso_strict: an invite is accepted through NEIAM. --%>
            <div id="invite-sso" class="space-y-3">
              <p class="text-sm">Sign in with NEIAM; you'll come back here to finish.</p>
              <.invite_sso_buttons invite_token={@invite_token} />
            </div>
          <% @invite && @invite.email -> %>
            <div id="registration-invited" class="space-y-4">
              <.invite_sso_buttons invite_token={@invite_token} divider />
              <.form for={%{}} id="invite_registration_form" action={~p"/users/register/invite"}>
                <input type="hidden" name="invite" value={@invite_token} />
                <p class="mb-3 text-sm">
                  This invite is for <span id="invite-email" class="font-mono">{@invite.email}</span>,
                  so the address counts as confirmed. You'll sign in later with a link we email you.
                </p>
                <button type="submit" class="btn btn-primary w-full" phx-disable-with="Creating…">
                  Create my account
                </button>
              </.form>
            </div>
          <% true -> %>
            <div :if={@invite} id="registration-invited" class="alert alert-success">
              <.icon name="hero-envelope-open" class="size-5" />
              <p>Your invite is valid. Finish making your account below.</p>
            </div>

            <%= cond do %>
              <% @invite -> %>
                <.invite_sso_buttons invite_token={@invite_token} divider />
              <% NeiamAuth.enabled?() and NeiamAuth.providers() != [] -> %>
                <div class="space-y-4">
                  <NeiamAuth.Components.neiam_sign_in_buttons class="btn btn-primary w-full" />
                  <div class="divider">or</div>
                </div>
              <% true -> %>
            <% end %>

            <.form for={@form} id="registration_form" phx-submit="save" phx-change="validate">
              <.input
                field={@form[:email]}
                type="email"
                label="Email"
                autocomplete="username"
                spellcheck="false"
                required
                phx-mounted={JS.focus()}
              />

              <.button phx-disable-with="Creating account..." class="btn btn-primary w-full">
                Create an account
              </.button>
            </.form>
        <% end %>
      </div>
    </Layouts.app>
    """
  end

  attr :invite_token, :string, required: true
  attr :divider, :boolean, default: false

  # NEIAM from a registration invite: through InviteController, which
  # remembers the invite so a first login comes back here.
  defp invite_sso_buttons(assigns) do
    ~H"""
    <div :if={NeiamAuth.enabled?() and NeiamAuth.providers() != []} class="space-y-4">
      <.link
        :for={p <- NeiamAuth.providers()}
        id={"invite-sso-#{p.id}"}
        href={~p"/users/register/invite/sso?#{[invite: @invite_token, provider: p.id]}"}
        class="btn btn-primary w-full"
      >
        {p.label}
      </.link>
      <div :if={@divider} class="divider">or</div>
    </div>
    """
  end

  @impl true
  def mount(_params, _session, %{assigns: %{current_scope: %{user: user}}} = socket)
      when not is_nil(user) do
    {:ok, redirect(socket, to: VigilWeb.UserAuth.signed_in_path(socket))}
  end

  def mount(params, session, socket) do
    token = params["invite"]
    invite = Accounts.get_active_invite(token)
    local? = NeiamAuth.local_login_enabled?()

    if local? or invite do
      {:ok,
       socket
       |> assign(:local?, local?)
       |> assign_invite(invite, token)
       # Set by NeiamAuthAdapter.handle_error/2: a NEIAM login for this
       # invite came back refused as not invited, and is pending.
       |> assign(:sso_pending?, !!invite and session["vigil_invite_sso"] == token)
       |> assign(:sso_email, session["vigil_sso_email"])
       |> assign_form(Accounts.change_user_email(%User{}, %{}, validate_unique: false)),
       temporary_assigns: [form: nil]}
    else
      # OIDC_LOGIN_MODE=sso_strict and no invite: accounts come from NEIAM
      # (and an invite).
      {:ok,
       socket
       |> put_flash(:error, "Sign up by signing in with NEIAM.")
       |> redirect(to: ~p"/users/log-in")}
    end
  end

  defp assign_invite(socket, invite, token) do
    socket
    |> assign(:invite, invite)
    # The raw token from the link: only its hash is stored, so this is the
    # one copy there is to spend the invite with.
    |> assign(:invite_token, invite && token)
    |> assign(:gated, not Accounts.registration_open?() and is_nil(invite))
    # An addressed invite whose address has an account: they log in (a link
    # never signs anyone in to an existing account).
    |> assign(:has_account?, addressed_account?(invite))
  end

  defp addressed_account?(%{email: email}) when is_binary(email),
    do: Accounts.get_user_by_email(email) != nil

  defp addressed_account?(_invite), do: false

  @impl true
  def handle_event("save", %{"user" => user_params}, socket) do
    a = socket.assigns

    cond do
      a.gated or not a.local? or a.has_account? ->
        {:noreply, put_flash(socket, :error, "Registration is invite-only.")}

      # An addressed invite registers only its own address, by its own form.
      a.invite && a.invite.email ->
        {:noreply, put_flash(socket, :error, "This invite is for #{a.invite.email}.")}

      true ->
        save(socket, user_params)
    end
  end

  def handle_event("validate", %{"user" => user_params}, socket) do
    changeset = Accounts.change_user_email(%User{}, user_params, validate_unique: false)
    {:noreply, assign_form(socket, Map.put(changeset, :action, :validate))}
  end

  defp save(socket, user_params) do
    case register(socket.assigns, user_params) do
      {:ok, user} ->
        # Not `{:ok, _} = ...`: the user (and any invite) is already
        # committed, so a failed send mustn't crash the page and strand them.
        {kind, message} =
          case Accounts.deliver_login_instructions(user, &url(~p"/users/log-in/#{&1}")) do
            {:ok, _} ->
              {:info,
               "An email was sent to #{user.email}, please access it to confirm your account."}

            {:error, _} ->
              {:error,
               "Your account was made, but we couldn't send the email. Ask for a login link to try again."}
          end

        {:noreply,
         socket
         |> put_flash(kind, message)
         |> push_navigate(to: ~p"/users/log-in")}

      {:error, %Ecto.Changeset{} = changeset} ->
        {:noreply, assign_form(socket, changeset)}

      {:error, _gone} ->
        {:noreply,
         socket
         |> assign(invite: nil, invite_token: nil)
         |> assign(:gated, not Accounts.registration_open?())
         |> put_flash(:error, "That invite has been used up or has expired.")}
    end
  end

  # The invite is re-checked and spent in the same transaction as the
  # account is made, so one link can't be used twice from two open tabs.
  defp register(%{invite_token: token}, params) when is_binary(token),
    do: Accounts.register_user_with_invite(params, token)

  defp register(_assigns, params), do: Accounts.register_user(params)

  defp assign_form(socket, %Ecto.Changeset{} = changeset) do
    assign(socket, form: to_form(changeset, as: "user"))
  end
end