8.4 KiB · text History e569b6d
defmodule CartosnapAppWeb.UserLive.Settings do
  use CartosnapAppWeb, :live_view

  on_mount {CartosnapAppWeb.UserAuth, :require_sudo_mode}

  alias CartosnapApp.Accounts

  @impl true
  def render(assigns) do
    ~H"""
    <Layouts.app flash={@flash} current_scope={@current_scope}>
      <div class="text-center">
        <.header>
          Account Settings
          <:subtitle>Manage your account email address and password settings</:subtitle>
        </.header>
      </div>

      <.form for={@email_form} id="email_form" phx-submit="update_email" phx-change="validate_email">
        <.input
          field={@email_form[:email]}
          type="email"
          label="Email"
          autocomplete="username"
          spellcheck="false"
          required
        />
        <.button variant="primary" phx-disable-with="Changing...">Change Email</.button>
      </.form>

      <div class="divider" />

      <.form
        for={@password_form}
        id="password_form"
        action={~p"/users/update-password"}
        method="post"
        phx-change="validate_password"
        phx-submit="update_password"
        phx-trigger-action={@trigger_submit}
      >
        <input
          name={@password_form[:email].name}
          type="hidden"
          id="hidden_user_email"
          spellcheck="false"
          value={@current_email}
        />
        <.input
          field={@password_form[:password]}
          type="password"
          label="New password"
          autocomplete="new-password"
          spellcheck="false"
          required
        />
        <.input
          field={@password_form[:password_confirmation]}
          type="password"
          label="Confirm new password"
          autocomplete="new-password"
          spellcheck="false"
        />
        <.button variant="primary" phx-disable-with="Saving...">
          Save Password
        </.button>
      </.form>

      <div class="divider" />

      <%!-- Link this account to NEIAM; nothing while OIDC_ENABLED is off. --%>
      <div :if={NeiamAuth.providers() != []} id="neiam_auth_settings" class="space-y-2">
        <NeiamAuth.Components.neiam_link_buttons user={@current_scope.user} class="btn w-full" />
        <NeiamAuth.Components.neiam_global_logout user={@current_scope.user} class="link text-sm" />
        <div class="divider" />
      </div>

      <section id="devices" class="space-y-3">
        <div class="flex flex-wrap items-center justify-between gap-2">
          <div>
            <h2 class="font-semibold">Connected devices</h2>
            <p class="text-sm text-base-content/60">
              The CartoSnap Android app, for sharing photos straight from your phone.
            </p>
          </div>
          <button type="button" id="pair-device" phx-click="pair" class="btn btn-primary btn-sm">
            <.icon name="hero-device-phone-mobile-micro" class="size-4" /> Pair a device
          </button>
        </div>

        <div
          :if={@pairing_code}
          id="pairing"
          class="rounded-box border border-primary/40 bg-primary/5 p-4 text-center"
        >
          <p class="text-sm text-base-content/70">In the app, enter this server and code:</p>
          <p class="mt-2 font-mono text-sm text-base-content/70" id="pairing-server">
            {@pairing_server}
          </p>
          <p
            id="pairing-code"
            class="mt-1 select-all font-mono text-3xl font-bold tracking-[0.2em] text-primary"
          >
            {@pairing_code}
          </p>
          <p class="mt-2 text-xs text-base-content/60">
            Works once, for the next ten minutes.
          </p>
        </div>

        <ul id="device-list" class="divide-y divide-base-300 rounded-box border border-base-300">
          <li :if={@devices == []} class="p-4 text-center text-sm text-base-content/60">
            No devices paired yet.
          </li>
          <li
            :for={device <- @devices}
            id={"device-#{device.id}"}
            class="flex items-center justify-between gap-3 px-4 py-2"
          >
            <div class="min-w-0">
              <p class="truncate text-sm font-medium">{device.label || "Android device"}</p>
              <p class="text-xs text-base-content/60">
                Paired {Calendar.strftime(device.inserted_at, "%b %-d, %Y")} · last used {Calendar.strftime(
                  device.authenticated_at,
                  "%b %-d"
                )}
              </p>
            </div>
            <button
              type="button"
              phx-click="unpair"
              phx-value-id={device.id}
              data-confirm="Unpair this device? It stops uploading until it's paired again."
              class="btn btn-ghost btn-xs text-error"
            >
              Unpair
            </button>
          </li>
        </ul>
      </section>
    </Layouts.app>
    """
  end

  @impl true
  def mount(%{"token" => token}, _session, socket) do
    socket =
      case Accounts.update_user_email(socket.assigns.current_scope.user, token) do
        {:ok, _user} ->
          put_flash(socket, :info, "Email changed successfully.")

        {:error, _} ->
          put_flash(socket, :error, "Email change link is invalid or it has expired.")
      end

    {:ok, push_navigate(socket, to: ~p"/users/settings")}
  end

  def mount(_params, _session, socket) do
    user = socket.assigns.current_scope.user
    email_changeset = Accounts.change_user_email(user, %{}, validate_unique: false)
    password_changeset = Accounts.change_user_password(user, %{}, hash_password: false)

    socket =
      socket
      |> assign(:current_email, user.email)
      |> assign(:email_form, to_form(email_changeset))
      |> assign(:password_form, to_form(password_changeset))
      |> assign(:trigger_submit, false)
      |> assign(:pairing_code, nil)
      |> assign(:pairing_server, pairing_server())
      |> assign(:devices, Accounts.list_api_tokens(user))

    {:ok, socket}
  end

  @impl true
  def handle_event("validate_email", params, socket) do
    %{"user" => user_params} = params

    email_form =
      socket.assigns.current_scope.user
      |> Accounts.change_user_email(user_params, validate_unique: false)
      |> Map.put(:action, :validate)
      |> to_form()

    {:noreply, assign(socket, email_form: email_form)}
  end

  def handle_event("update_email", params, socket) do
    %{"user" => user_params} = params
    user = socket.assigns.current_scope.user
    true = Accounts.sudo_mode?(user)

    case Accounts.change_user_email(user, user_params) do
      %{valid?: true} = changeset ->
        Accounts.deliver_user_update_email_instructions(
          Ecto.Changeset.apply_action!(changeset, :insert),
          user.email,
          &url(~p"/users/settings/confirm-email/#{&1}")
        )

        info = "A link to confirm your email change has been sent to the new address."
        {:noreply, socket |> put_flash(:info, info)}

      changeset ->
        {:noreply, assign(socket, :email_form, to_form(changeset, action: :insert))}
    end
  end

  def handle_event("pair", _params, socket) do
    code = Accounts.create_pairing_code(socket.assigns.current_scope.user)
    {:noreply, assign(socket, :pairing_code, code)}
  end

  def handle_event("unpair", %{"id" => id}, socket) do
    user = socket.assigns.current_scope.user
    :ok = Accounts.delete_api_token(user, id)
    {:noreply, assign(socket, :devices, Accounts.list_api_tokens(user))}
  end

  def handle_event("validate_password", params, socket) do
    %{"user" => user_params} = params

    password_form =
      socket.assigns.current_scope.user
      |> Accounts.change_user_password(user_params, hash_password: false)
      |> Map.put(:action, :validate)
      |> to_form()

    {:noreply, assign(socket, password_form: password_form)}
  end

  def handle_event("update_password", params, socket) do
    %{"user" => user_params} = params
    user = socket.assigns.current_scope.user
    true = Accounts.sudo_mode?(user)

    case Accounts.change_user_password(user, user_params) do
      %{valid?: true} = changeset ->
        {:noreply, assign(socket, trigger_submit: true, password_form: to_form(changeset))}

      changeset ->
        {:noreply, assign(socket, password_form: to_form(changeset, action: :insert))}
    end
  end

  # What the phone should connect to: this server, unless it's only
  # reachable here (dev on localhost), when CARTOSNAP_PUBLIC_URL says.
  defp pairing_server do
    Application.get_env(:cartosnap_app, :public_url) || CartosnapAppWeb.Endpoint.url()
  end
end