19.4 KiB · text History 1ba5ec3
defmodule CartosnapApp.Accounts do
  @moduledoc """
  The Accounts context.
  """

  import Ecto.Query, warn: false
  alias CartosnapApp.Repo

  alias CartosnapApp.Accounts.{Invite, User, UserToken, UserNotifier}

  ## Names

  @doc "What to call a user on screen: the part of their email before the @."
  def display_name(%User{email: email}), do: email |> String.split("@") |> hd()

  @doc "Display names for the given user ids: `%{id => name}`."
  def display_names(ids) do
    ids = ids |> Enum.reject(&is_nil/1) |> Enum.uniq()

    from(u in User, where: u.id in ^ids)
    |> Repo.all()
    |> Map.new(&{&1.id, display_name(&1)})
  end

  ## Database getters

  @doc """
  Gets a user by email.

  ## Examples

      iex> get_user_by_email("foo@example.com")
      %User{}

      iex> get_user_by_email("unknown@example.com")
      nil

  """
  def get_user_by_email(email) when is_binary(email) do
    Repo.get_by(User, email: email)
  end

  @doc """
  Gets a user by email and password.

  ## Examples

      iex> get_user_by_email_and_password("foo@example.com", "correct_password")
      %User{}

      iex> get_user_by_email_and_password("foo@example.com", "invalid_password")
      nil

  """
  def get_user_by_email_and_password(email, password)
      when is_binary(email) and is_binary(password) do
    user = Repo.get_by(User, email: email)
    if User.valid_password?(user, password), do: user
  end

  @doc """
  Gets a single user.

  Raises `Ecto.NoResultsError` if the User does not exist.

  ## Examples

      iex> get_user!(123)
      %User{}

      iex> get_user!(456)
      ** (Ecto.NoResultsError)

  """
  def get_user!(id), do: Repo.get!(User, id)

  ## User registration

  @doc """
  Registers a user.

  ## Examples

      iex> register_user(%{field: value})
      {:ok, %User{}}

      iex> register_user(%{field: bad_value})
      {:error, %Ecto.Changeset{}}

  """
  def register_user(attrs) do
    %User{}
    |> User.email_changeset(attrs)
    |> Repo.insert()
  end

  @doc """
  An account for an address someone has proven they hold another way (an
  invite link mailed to it), so it starts confirmed. Passwordless: they
  sign in by magic link like everyone else.
  """
  def register_confirmed_user(email) do
    %User{}
    |> User.email_changeset(%{email: email})
    |> Ecto.Changeset.put_change(:confirmed_at, DateTime.utc_now(:second))
    |> Repo.insert()
  end

  ## Registration invites

  @doc """
  Whether anyone may make an account. When false (the default, as the
  sibling apps), registration needs an invite: a registration invite
  (`CartosnapApp.Accounts.Invite`) or a trip invite. `REGISTRATION_OPEN=true`
  opens it.
  """
  @spec registration_open?() :: boolean()
  def registration_open? do
    Application.get_env(:cartosnap_app, :registration_open, false) == true
  end

  @doc """
  Creates a registration invite, owned by `owner`, or by nobody when `owner`
  is nil (the very first invite, from the command line).

  `attrs` may carry `:note`, `:email` (to address it to one person) and
  `:expires_at`, or `:days` to expire that many days from now.

  The returned invite carries its raw link `token`, the only time it exists.
  """
  def create_invite(owner, attrs \\ %{}) do
    attrs = Map.new(attrs)

    expires_at =
      case attrs[:days] do
        days when is_integer(days) and days > 0 ->
          DateTime.utc_now(:second) |> DateTime.add(days, :day)

        _ ->
          attrs[:expires_at]
      end

    attrs =
      attrs
      |> Map.take([:note, :email])
      |> Map.reject(fn {_k, v} -> v in [nil, ""] end)
      |> Map.put(:expires_at, expires_at)
      |> Map.put(:created_by_id, owner && owner.id)

    %Invite{}
    |> Invite.create_changeset(attrs)
    |> Repo.insert()
  end

  @doc """
  The command-line way in, shared by `mix cartosnap.invite` and the
  release's `bin/invite`: `opts` are `:email` (whom it is for), `:note`,
  `:days` and `:by` (an owner's email).
  """
  def create_invite_from_cli(opts) do
    owner =
      case opts[:by] do
        nil ->
          {:ok, nil}

        email ->
          if user = get_user_by_email(email), do: {:ok, user}, else: {:error, :no_such_user}
      end

    with {:ok, owner} <- owner do
      create_invite(owner, Map.take(Map.new(opts), [:email, :note, :days]))
    end
  end

  @doc "Registration invites a user made, newest first, with who used them."
  def list_invites(%User{id: id}) do
    from(i in Invite,
      where: i.created_by_id == ^id,
      order_by: [desc: i.inserted_at],
      preload: [:consumed_by]
    )
    |> Repo.all()
  end

  @doc "The registration invite a link's raw token names, if it can still be used."
  def get_active_invite(token) when is_binary(token) and token != "" do
    case Repo.get_by(Invite, token_hash: Invite.hash_token(token)) do
      nil -> nil
      invite -> if Invite.active?(invite), do: invite
    end
  end

  def get_active_invite(_), do: nil

  @doc """
  Registers from an unaddressed registration invite, by email (confirmed
  later by magic link, as open registration), and spends the invite in the
  same transaction, so one link can't make two accounts.
  `{:error, :invite_used}` when it went in the meantime.
  """
  def register_user_with_invite(attrs, token) do
    Repo.transact(fn ->
      with %Invite{} = invite <- lock_active_invite(token) || {:error, :invite_used},
           {:ok, user} <- register_user(attrs),
           {:ok, _} <- consume_invite(invite, user) do
        {:ok, user}
      end
    end)
  end

  @doc """
  Makes the account a registration invite is for, confirmed, and spends the
  invite, in one transaction: `{:ok, user}`, and the caller signs them in.

  The address is the invite's own when it is addressed. Otherwise it must
  be given (`email`): the one a NEIAM login brought, which the identity
  provider vouches for. A bare unaddressed link proves no address, so the
  local way with one is `register_user_with_invite/2`.

  Refuses `{:error, :has_account}` when the address already has an account:
  an invite must never sign anyone in to an existing account, or addressing
  an invite to someone would hand theirs over. `{:error, :invalid}` for a
  spent or expired invite, or no address to use.
  """
  def register_by_invite(token, email \\ nil)

  def register_by_invite(token, email) when is_binary(token) do
    Repo.transact(fn ->
      invite = lock_active_invite(token)
      email = invite && (invite.email || email)

      cond do
        is_nil(invite) or not is_binary(email) -> {:error, :invalid}
        get_user_by_email(email) -> {:error, :has_account}
        true -> with {:ok, user} <- register_confirmed_user(email), do: consume(invite, user)
      end
    end)
  end

  def register_by_invite(_, _), do: {:error, :invalid}

  defp consume(invite, user) do
    with {:ok, _} <- consume_invite(invite, user), do: {:ok, user}
  end

  # Locked, so two submits of one link can't both spend it.
  defp lock_active_invite(token) when is_binary(token) do
    query =
      from(i in Invite, where: i.token_hash == ^Invite.hash_token(token), lock: "FOR UPDATE")

    case Repo.one(query) do
      %Invite{} = invite -> if Invite.active?(invite), do: invite
      nil -> nil
    end
  end

  defp lock_active_invite(_), do: nil

  @doc "Marks a registration invite as consumed by the given user."
  def consume_invite(%Invite{} = invite, %User{} = user) do
    invite |> Invite.consume_changeset(user) |> Repo.update()
  end

  @doc """
  Gives one of `owner`'s active invites a new token, so any earlier copy of
  the link stops working. The returned invite carries the new raw `token`,
  to show once. Anyone else's, or a spent one, is `{:error, :not_found}`.
  """
  def rotate_invite(%User{id: owner_id}, invite_id) do
    with {:ok, invite_id} <- Ecto.UUID.cast(invite_id),
         %Invite{} = invite <- Repo.get_by(Invite, id: invite_id, created_by_id: owner_id),
         true <- Invite.active?(invite),
         {:ok, invite} <- invite |> Invite.rotate_token_changeset() |> Repo.update() do
      {:ok, Repo.preload(invite, :consumed_by)}
    else
      _ -> {:error, :not_found}
    end
  end

  @doc """
  The command-line way to a fresh link for the newest active invite
  addressed to `email` (whoever owns it): rotates its token, so earlier
  links stop working. `{:error, :not_found}` when there is none.
  """
  def rotate_invite_for_email(email) when is_binary(email) do
    from(i in Invite,
      where: i.email == ^(email |> String.trim() |> String.downcase()) and is_nil(i.consumed_at),
      order_by: [desc: i.inserted_at]
    )
    |> Repo.all()
    |> Enum.find(&Invite.active?/1)
    |> case do
      nil -> {:error, :not_found}
      invite -> invite |> Invite.rotate_token_changeset() |> Repo.update()
    end
  end

  @doc "Revokes one of `owner`'s unused invites. Anyone else's, or a missing one, is `{:error, :not_found}`."
  def revoke_invite(%User{id: owner_id}, invite_id) do
    with {:ok, invite_id} <- Ecto.UUID.cast(invite_id),
         %Invite{consumed_at: nil} = invite <-
           Repo.get_by(Invite, id: invite_id, created_by_id: owner_id),
         {:ok, invite} <-
           invite
           |> Ecto.Changeset.change(consumed_at: DateTime.utc_now(:second))
           |> Repo.update() do
      {:ok, Repo.preload(invite, :consumed_by)}
    else
      _ -> {:error, :not_found}
    end
  end

  ## Settings

  @doc """
  Checks whether the user is in sudo mode.

  The user is in sudo mode when the last authentication was done no further
  than 20 minutes ago. The limit can be given as second argument in minutes.
  """
  def sudo_mode?(user, minutes \\ -20)

  def sudo_mode?(%User{authenticated_at: ts}, minutes) when is_struct(ts, DateTime) do
    DateTime.after?(ts, DateTime.utc_now() |> DateTime.add(minutes, :minute))
  end

  def sudo_mode?(_user, _minutes), do: false

  @doc """
  Returns an `%Ecto.Changeset{}` for changing the user email.

  See `CartosnapApp.Accounts.User.email_changeset/3` for a list of supported options.

  ## Examples

      iex> change_user_email(user)
      %Ecto.Changeset{data: %User{}}

  """
  def change_user_email(user, attrs \\ %{}, opts \\ []) do
    User.email_changeset(user, attrs, opts)
  end

  @doc """
  Updates the user email using the given token.

  If the token matches, the user email is updated and the token is deleted.
  """
  def update_user_email(user, token) do
    context = "change:#{user.email}"

    Repo.transact(fn ->
      with {:ok, query} <- UserToken.verify_change_email_token_query(token, context),
           %UserToken{sent_to: email} <- Repo.one(query),
           {:ok, user} <- Repo.update(User.email_changeset(user, %{email: email})),
           {_count, _result} <-
             Repo.delete_all(from(UserToken, where: [user_id: ^user.id, context: ^context])) do
        {:ok, user}
      else
        _ -> {:error, :transaction_aborted}
      end
    end)
  end

  @doc """
  Returns an `%Ecto.Changeset{}` for changing the user password.

  See `CartosnapApp.Accounts.User.password_changeset/3` for a list of supported options.

  ## Examples

      iex> change_user_password(user)
      %Ecto.Changeset{data: %User{}}

  """
  def change_user_password(user, attrs \\ %{}, opts \\ []) do
    User.password_changeset(user, attrs, opts)
  end

  @doc """
  Updates the user password.

  Returns a tuple with the updated user, as well as a list of expired tokens.

  ## Examples

      iex> update_user_password(user, %{password: ...})
      {:ok, {%User{}, [...]}}

      iex> update_user_password(user, %{password: "too short"})
      {:error, %Ecto.Changeset{}}

  """
  def update_user_password(user, attrs) do
    user
    |> User.password_changeset(attrs)
    |> update_user_and_delete_all_tokens()
  end

  ## Session

  @doc """
  Generates a session token.
  """
  def generate_user_session_token(user) do
    {token, user_token} = UserToken.build_session_token(user)
    Repo.insert!(user_token)
    token
  end

  @doc """
  Gets the user with the given signed token.

  If the token is valid `{user, token_inserted_at}` is returned, otherwise `nil` is returned.
  """
  def get_user_by_session_token(token) do
    {:ok, query} = UserToken.verify_session_token_query(token)
    Repo.one(query)
  end

  @doc """
  Gets the user with the given magic link token.
  """
  def get_user_by_magic_link_token(token) do
    with {:ok, query} <- UserToken.verify_magic_link_token_query(token),
         {user, _token} <- Repo.one(query) do
      user
    else
      _ -> nil
    end
  end

  @doc """
  Logs the user in by magic link.

  There are three cases to consider:

  1. The user has already confirmed their email. They are logged in
     and the magic link is expired.

  2. The user has not confirmed their email and no password is set.
     In this case, the user gets confirmed, logged in, and all tokens -
     including session ones - are expired. In theory, no other tokens
     exist but we delete all of them for best security practices.

  3. The user has not confirmed their email but a password is set.
     This cannot happen in the default implementation but may be the
     source of security pitfalls. See the "Mixing magic link and password registration" section of
     `mix help phx.gen.auth`.
  """
  def login_user_by_magic_link(token) do
    {:ok, query} = UserToken.verify_magic_link_token_query(token)

    case Repo.one(query) do
      # Prevent session fixation attacks by disallowing magic links for unconfirmed users with password
      {%User{confirmed_at: nil, hashed_password: hash}, _token} when not is_nil(hash) ->
        raise """
        magic link log in is not allowed for unconfirmed users with a password set!

        This cannot happen with the default implementation, which indicates that you
        might have adapted the code to a different use case. Please make sure to read the
        "Mixing magic link and password registration" section of `mix help phx.gen.auth`.
        """

      {%User{confirmed_at: nil} = user, _token} ->
        user
        |> User.confirm_changeset()
        |> update_user_and_delete_all_tokens()

      {user, token} ->
        Repo.delete!(token)
        {:ok, {user, []}}

      nil ->
        {:error, :not_found}
    end
  end

  @doc ~S"""
  Delivers the update email instructions to the given user.

  ## Examples

      iex> deliver_user_update_email_instructions(user, current_email, &url(~p"/users/settings/confirm-email/#{&1}"))
      {:ok, %{to: ..., body: ...}}

  """
  def deliver_user_update_email_instructions(%User{} = user, current_email, update_email_url_fun)
      when is_function(update_email_url_fun, 1) do
    {encoded_token, user_token} = UserToken.build_email_token(user, "change:#{current_email}")

    Repo.insert!(user_token)
    UserNotifier.deliver_update_email_instructions(user, update_email_url_fun.(encoded_token))
  end

  @doc """
  Delivers the magic link login instructions to the given user.
  """
  def deliver_login_instructions(%User{} = user, magic_link_url_fun)
      when is_function(magic_link_url_fun, 1) do
    {encoded_token, user_token} = UserToken.build_email_token(user, "login")
    Repo.insert!(user_token)
    UserNotifier.deliver_login_instructions(user, magic_link_url_fun.(encoded_token))
  end

  @doc """
  Deletes the signed token with the given context.
  """
  def delete_user_session_token(token) do
    Repo.delete_all(from(UserToken, where: [token: ^token, context: "session"]))
    :ok
  end

  ## Token helper

  defp update_user_and_delete_all_tokens(changeset) do
    Repo.transact(fn ->
      with {:ok, user} <- Repo.update(changeset) do
        tokens_to_expire = Repo.all_by(UserToken, user_id: user.id)

        Repo.delete_all(from(t in UserToken, where: t.id in ^Enum.map(tokens_to_expire, & &1.id)))

        {:ok, {user, tokens_to_expire}}
      end
    end)
  end

  ## Paired devices

  @doc """
  Makes a key for a device to sign in with (the Android app), returning
  it encoded. It's shown once, as the pairing code; only its hash is kept.
  """
  def create_api_token(%User{} = user, label \\ nil) do
    {encoded, user_token} = UserToken.build_api_token(user, label)
    Repo.insert!(user_token)
    encoded
  end

  @doc """
  Signs the app in: a device key, exactly as pairing makes one
  (`create_api_token/2`, labelled with the device name), in the body every
  `/api/v1/auth/*` sign-in answers with. `method` (`:password`,
  `:magic_link`, `:oidc`) is for the caller; the key is the same.
  Used by `CartosnapAppWeb.Api.V1.AuthController` and
  `NeiamAuth.App.ExchangePlug`.
  """
  def issue_app_token(%User{} = user, device_name, _method) do
    token = create_api_token(user, device_name)

    {:ok,
     %{
       token: token,
       token_type: "Bearer",
       user: %{id: user.id, email: user.email}
     }}
  end

  @doc """
  Whether mail actually leaves the server. Without SMTP_RELAY the mailer
  only logs (config/runtime.exs), so the app hides the "Email me a sign-in
  link" button.
  """
  def mail_configured? do
    Application.get_env(:cartosnap_app, CartosnapApp.Mailer, [])[:adapter] not in [
      nil,
      Swoosh.Adapters.Logger
    ]
  end

  @doc """
  The user a device key belongs to, and the key's id, or nil when it's
  unknown, revoked or lapsed. Each use (at most daily) extends it.
  """
  def fetch_user_by_api_token(token) when is_binary(token) do
    with {:ok, query} <- UserToken.verify_api_token_query(token),
         {user, user_token} <- Repo.one(query) do
      if UserToken.api_token_needs_refresh?(user_token) do
        user_token
        |> Ecto.Changeset.change(authenticated_at: DateTime.utc_now(:second))
        |> Repo.update!()
      end

      {user, user_token.id}
    else
      _ -> nil
    end
  end

  def fetch_user_by_api_token(_token), do: nil

  @doc """
  A code for pairing a new device, `"XK4F-9TQ2"`, good for ten minutes and
  one device. Making one cancels any earlier unused code.
  """
  def create_pairing_code(%User{} = user) do
    Repo.delete_all(from(t in UserToken, where: t.user_id == ^user.id and t.context == "pair"))
    {code, user_token} = UserToken.build_pairing_code(user)
    Repo.insert!(user_token)
    code
  end

  @doc """
  Trades a pairing code for a device key, `{:ok, key, user}`, using the
  code up. `:error` when it's wrong, used or lapsed.
  """
  def redeem_pairing_code(code, label \\ nil) when is_binary(code) do
    Repo.transact(fn ->
      with {user, pairing} <- Repo.one(UserToken.verify_pairing_code_query(code)),
           {1, _} <- Repo.delete_all(from(t in UserToken, where: t.id == ^pairing.id)) do
        {:ok, {create_api_token(user, label), user}}
      else
        _ -> {:error, :invalid}
      end
    end)
    |> case do
      {:ok, {key, user}} -> {:ok, key, user}
      {:error, _} -> :error
    end
  end

  @doc "A user's paired devices, most recently used first."
  def list_api_tokens(%User{id: user_id}) do
    from(t in UserToken,
      where: t.user_id == ^user_id and t.context == "api",
      order_by: [desc: t.authenticated_at]
    )
    |> Repo.all()
  end

  @doc "Names a paired device, as it calls itself."
  def label_api_token(%User{id: user_id}, token_id, label) when is_binary(label) do
    label = label |> String.trim() |> String.slice(0, 80)

    from(t in UserToken,
      where: t.id == ^token_id and t.user_id == ^user_id and t.context == "api"
    )
    |> Repo.update_all(set: [label: if(label == "", do: nil, else: label)])

    :ok
  end

  @doc "Unpairs a device: its key stops working."
  def delete_api_token(%User{id: user_id}, token_id) do
    from(t in UserToken,
      where: t.id == ^token_id and t.user_id == ^user_id and t.context == "api"
    )
    |> Repo.delete_all()

    :ok
  end
end