11.3 KiB · text History 4b6fe3b
defmodule OhMyExOhIrcd.Accounts do
  @moduledoc """
  The Accounts context.
  """

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

  alias OhMyExOhIrcd.Accounts.{User, UserToken, UserNotifier}

  ## 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

  ## 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 `OhMyExOhIrcd.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 `OhMyExOhIrcd.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

  ## IRC operator status

  @doc """
  Flip the `is_oper` bit on a user. Returns the updated `%User{}` or an
  `{:error, changeset}` tuple. Used by the `mix opers.grant/.revoke`
  tasks and by future admin tooling.
  """
  def set_oper(%User{} = user, is_oper) when is_boolean(is_oper) do
    user |> User.oper_changeset(is_oper) |> Repo.update()
  end

  @doc "True iff the user is flagged as an IRC operator."
  def oper?(%User{is_oper: true}), do: true
  def oper?(_), do: false

  @doc """
  Set (or clear, with `nil`) a user's persistent vhost. Applied to their
  IRC prefix on the next connection; `OhMyExOhIrcd.IRC.Vhost.set_live/3`
  also pushes it to any currently-connected session. Returns the updated
  `%User{}` or `{:error, changeset}`.
  """
  def set_vhost(%User{} = user, vhost) when is_binary(vhost) or is_nil(vhost) do
    user |> User.vhost_changeset(vhost) |> Repo.update()
  end

  @doc """
  Set a persistent vhost by account email (for offline users). Returns
  `{:error, :not_found}` if no such account.
  """
  def set_vhost_by_email(email, vhost) when is_binary(email) do
    case get_user_by_email(email) do
      %User{} = user -> set_vhost(user, vhost)
      nil -> {:error, :not_found}
    end
  end

  ## Invites (invite-only registration)

  alias OhMyExOhIrcd.Accounts.Invite

  @doc """
  Current registration mode. `:open` is the legacy free-signup behaviour;
  `:invite_only` requires a valid `Invite` token at registration time.
  Read from `:oh_my_ex_oh_ircd, :registration_mode` (set in `runtime.exs`).
  """
  def registration_mode do
    Application.get_env(:oh_my_ex_oh_ircd, :registration_mode, :invite_only)
  end

  @doc "Mint a fresh invite. `created_by` is the User who's issuing it (may be nil)."
  def create_invite(opts \\ []) do
    attrs = %{
      token: Invite.fresh_token(),
      note: Keyword.get(opts, :note, ""),
      created_by_id: opts[:created_by] && opts[:created_by].id,
      expires_at:
        case Keyword.get(opts, :expires_in_seconds) do
          nil -> nil
          secs when is_integer(secs) and secs > 0 -> DateTime.add(DateTime.utc_now(), secs)
        end
    }

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

  @doc """
  Look up an invite by token. Returns the record if it exists and is
  still valid (unconsumed + not expired), else `nil`.
  """
  def valid_invite(token) when is_binary(token) and token != "" do
    case Repo.get_by(Invite, token: token) do
      nil -> nil
      %Invite{consumed_at: ts} when not is_nil(ts) -> nil
      %Invite{expires_at: ts} = inv -> if expired?(ts), do: nil, else: inv
    end
  end

  def valid_invite(_), do: nil

  defp expired?(nil), do: false
  defp expired?(%DateTime{} = ts), do: DateTime.compare(ts, DateTime.utc_now()) == :lt

  @doc "Mark an invite consumed by a user."
  def consume_invite(%Invite{} = invite, %User{} = user) do
    invite |> Invite.consume_changeset(user.id) |> Repo.update()
  end

  def list_active_invites do
    Repo.all(
      from i in Invite,
        where: is_nil(i.consumed_at),
        order_by: [desc: i.inserted_at],
        preload: [:created_by]
    )
  end

  @doc """
  Delete (revoke) an invite by id. Returns `:ok` whether or not a row
  existed, so it's idempotent against double-clicks / stale lists.
  """
  def delete_invite(id) do
    case Repo.get(Invite, id) do
      nil -> :ok
      %Invite{} = invite -> with {:ok, _} <- Repo.delete(invite), do: :ok
    end
  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
end