memEx/lib/memex/accounts.ex

492 lines
14 KiB
Elixir
Raw Permalink Normal View History

2022-07-25 19:31:54 -04:00
defmodule Memex.Accounts do
2021-03-11 21:12:55 -05:00
@moduledoc """
The Accounts context.
"""
import Ecto.Query, warn: false
2022-07-25 19:31:54 -04:00
alias Memex.{Mailer, Repo}
alias Memex.Accounts.{User, UserToken}
2022-02-25 21:52:17 -05:00
alias Ecto.{Changeset, Multi}
2022-02-25 22:12:55 -05:00
alias Oban.Job
2021-03-11 21:12:55 -05:00
## 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
"""
2022-11-23 21:15:52 -05:00
@spec get_user_by_email(email :: String.t()) :: User.t() | nil
2022-02-25 21:52:17 -05:00
def get_user_by_email(email) when is_binary(email), do: Repo.get_by(User, email: email)
2021-03-11 21:12:55 -05:00
@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
"""
2022-11-23 21:15:52 -05:00
@spec get_user_by_email_and_password(email :: String.t(), password :: String.t()) ::
2022-02-25 21:52:17 -05:00
User.t() | nil
2021-03-11 21:12:55 -05:00
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)
"""
2022-02-25 21:52:17 -05:00
@spec get_user!(User.t()) :: User.t()
2021-03-11 21:12:55 -05:00
def get_user!(id), do: Repo.get!(User, id)
2022-02-25 21:52:17 -05:00
@doc """
Returns all users grouped by role.
## Examples
iex> list_users_by_role(%User{id: 123, role: :admin})
[admin: [%User{}], user: [%User{}, %User{}]]
"""
@spec list_all_users_by_role(User.t()) :: %{String.t() => [User.t()]}
def list_all_users_by_role(%User{role: :admin}) do
Repo.all(from u in User, order_by: u.email) |> Enum.group_by(fn user -> user.role end)
end
@doc """
Returns all users for a certain role.
## Examples
iex> list_users_by_role(%User{id: 123, role: :admin})
[%User{}]
"""
2022-11-23 21:15:52 -05:00
@spec list_users_by_role(User.role()) :: [User.t()]
2022-02-25 21:52:17 -05:00
def list_users_by_role(role) do
role = role |> to_string()
Repo.all(from u in User, where: u.role == ^role, order_by: u.email)
end
2021-03-11 21:12:55 -05:00
## User registration
@doc """
Registers a user.
## Examples
iex> register_user(%{field: value})
{:ok, %User{}}
iex> register_user(%{field: bad_value})
2022-02-25 21:52:17 -05:00
{:error, %Changeset{}}
2021-03-11 21:12:55 -05:00
"""
2022-11-23 21:15:52 -05:00
@spec register_user(attrs :: map()) :: {:ok, User.t()} | {:error, User.changeset()}
2021-03-11 21:12:55 -05:00
def register_user(attrs) do
2022-11-23 21:15:52 -05:00
Multi.new()
|> Multi.one(:users_count, from(u in User, select: count(u.id), distinct: true))
|> Multi.insert(:add_user, fn %{users_count: count} ->
# if no registered users, make first user an admin
role = if count == 0, do: "admin", else: "user"
2022-02-25 21:52:17 -05:00
2022-11-23 21:15:52 -05:00
User.registration_changeset(attrs) |> User.role_changeset(role)
end)
|> Repo.transaction()
|> case do
{:ok, %{add_user: user}} -> {:ok, user}
{:error, :add_user, changeset, _changes_so_far} -> {:error, changeset}
end
2021-03-11 21:12:55 -05:00
end
@doc """
2022-02-25 21:52:17 -05:00
Returns an `%Changeset{}` for tracking user changes.
2021-03-11 21:12:55 -05:00
## Examples
iex> change_user_registration(user)
2022-02-25 21:52:17 -05:00
%Changeset{data: %User{}}
2021-03-11 21:12:55 -05:00
"""
2022-11-23 21:15:52 -05:00
@spec change_user_registration() :: User.changeset()
@spec change_user_registration(attrs :: map()) :: User.changeset()
def change_user_registration(attrs \\ %{}),
do: User.registration_changeset(attrs, hash_password: false)
2021-03-11 21:12:55 -05:00
## Settings
@doc """
2022-02-25 21:52:17 -05:00
Returns an `%Changeset{}` for changing the user email.
2021-03-11 21:12:55 -05:00
## Examples
iex> change_user_email(user)
2022-02-25 21:52:17 -05:00
%Changeset{data: %User{}}
2021-03-11 21:12:55 -05:00
"""
2022-11-23 21:15:52 -05:00
@spec change_user_email(User.t(), attrs :: map()) :: User.changeset()
2022-02-25 21:52:17 -05:00
def change_user_email(user, attrs \\ %{}), do: User.email_changeset(user, attrs)
@doc """
Returns an `%Changeset{}` for changing the user role.
## Examples
iex> change_user_role(user)
%Changeset{data: %User{}}
"""
2022-11-23 21:15:52 -05:00
@spec change_user_role(User.t(), User.role()) :: User.changeset()
2022-02-25 21:52:17 -05:00
def change_user_role(user, role), do: User.role_changeset(user, role)
2021-03-11 21:12:55 -05:00
@doc """
Emulates that the email will change without actually changing
it in the database.
## Examples
iex> apply_user_email(user, "valid password", %{email: ...})
{:ok, %User{}}
iex> apply_user_email(user, "invalid password", %{email: ...})
2022-02-25 21:52:17 -05:00
{:error, %Changeset{}}
2021-03-11 21:12:55 -05:00
"""
2022-11-23 21:15:52 -05:00
@spec apply_user_email(User.t(), password :: String.t(), attrs :: map()) ::
{:ok, User.t()} | {:error, User.changeset()}
2021-03-11 21:12:55 -05:00
def apply_user_email(user, password, attrs) do
user
|> User.email_changeset(attrs)
|> User.validate_current_password(password)
2022-02-25 21:52:17 -05:00
|> Changeset.apply_action(:update)
2021-03-11 21:12:55 -05:00
end
@doc """
Updates the user email using the given token.
If the token matches, the user email is updated and the token is deleted.
The confirmed_at date is also updated to the current time.
"""
2022-11-23 21:15:52 -05:00
@spec update_user_email(User.t(), token :: String.t()) :: :ok | :error
2021-03-11 21:12:55 -05:00
def update_user_email(user, token) do
context = "change:#{user.email}"
with {:ok, query} <- UserToken.verify_change_email_token_query(token, context),
%UserToken{sent_to: email} <- Repo.one(query),
{:ok, _} <- Repo.transaction(user_email_multi(user, email, context)) do
:ok
else
_ -> :error
end
end
2022-11-23 21:15:52 -05:00
@spec user_email_multi(User.t(), email :: String.t(), context :: String.t()) :: Multi.t()
2021-03-11 21:12:55 -05:00
defp user_email_multi(user, email, context) do
changeset = user |> User.email_changeset(%{email: email}) |> User.confirm_changeset()
2022-02-25 21:52:17 -05:00
Multi.new()
|> Multi.update(:user, changeset)
|> Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, [context]))
2021-03-11 21:12:55 -05:00
end
@doc """
Delivers the update email instructions to the given user.
## Examples
iex> deliver_update_email_instructions(user, current_email, &Routes.user_update_email_url(conn, :edit, &1))
{:ok, %{to: ..., body: ...}}
"""
2022-11-23 21:15:52 -05:00
@spec deliver_update_email_instructions(User.t(), current_email :: String.t(), function) ::
Job.t()
2022-02-25 21:52:17 -05:00
def deliver_update_email_instructions(user, current_email, update_email_url_fun)
2021-03-11 21:12:55 -05:00
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)
2022-02-25 21:52:17 -05:00
Mailer.deliver_update_email_instructions(user, update_email_url_fun.(encoded_token))
2021-03-11 21:12:55 -05:00
end
@doc """
2022-02-25 21:52:17 -05:00
Returns an `%Changeset{}` for changing the user password.
2021-03-11 21:12:55 -05:00
## Examples
iex> change_user_password(user)
2022-02-25 21:52:17 -05:00
%Changeset{data: %User{}}
2021-03-11 21:12:55 -05:00
"""
2022-11-23 21:15:52 -05:00
@spec change_user_password(User.t(), attrs :: map()) :: User.changeset()
2022-02-25 21:52:17 -05:00
def change_user_password(user, attrs \\ %{}),
do: User.password_changeset(user, attrs, hash_password: false)
2021-03-11 21:12:55 -05:00
@doc """
Updates the user password.
## Examples
iex> update_user_password(user, "valid password", %{password: ...})
{:ok, %User{}}
iex> update_user_password(user, "invalid password", %{password: ...})
2022-02-25 21:52:17 -05:00
{:error, %Changeset{}}
2021-03-11 21:12:55 -05:00
"""
2022-11-23 21:15:52 -05:00
@spec update_user_password(User.t(), password :: String.t(), attrs :: map()) ::
{:ok, User.t()} | {:error, User.changeset()}
2021-03-11 21:12:55 -05:00
def update_user_password(user, password, attrs) do
changeset =
user
|> User.password_changeset(attrs)
|> User.validate_current_password(password)
2022-02-25 21:52:17 -05:00
Multi.new()
|> Multi.update(:user, changeset)
|> Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, :all))
2021-03-11 21:12:55 -05:00
|> Repo.transaction()
|> case do
{:ok, %{user: user}} -> {:ok, user}
{:error, :user, changeset, _} -> {:error, changeset}
end
end
2022-05-05 20:55:59 -04:00
@doc """
Returns an `%Changeset{}` for changing the user locale.
## Examples
iex> change_user_locale(user)
%Changeset{data: %User{}}
"""
2022-11-23 21:15:52 -05:00
@spec change_user_locale(User.t()) :: User.changeset()
2022-05-05 20:55:59 -04:00
def change_user_locale(%{locale: locale} = user), do: User.locale_changeset(user, locale)
@doc """
Updates the user locale.
## Examples
iex> update_user_locale(user, "valid locale")
{:ok, %User{}}
iex> update_user_password(user, "invalid locale")
{:error, %Changeset{}}
"""
@spec update_user_locale(User.t(), locale :: String.t()) ::
2022-11-23 21:15:52 -05:00
{:ok, User.t()} | {:error, User.changeset()}
2022-05-05 20:55:59 -04:00
def update_user_locale(user, locale),
do: user |> User.locale_changeset(locale) |> Repo.update()
2022-02-25 21:52:17 -05:00
@doc """
Deletes a user. must be performed by an admin or the same user!
## Examples
iex> delete_user!(user_to_delete, %User{id: 123, role: :admin})
%User{}
iex> delete_user!(%User{id: 123}, %User{id: 123})
%User{}
"""
2022-11-23 21:15:52 -05:00
@spec delete_user!(user_to_delete :: User.t(), User.t()) :: User.t()
2022-02-25 21:52:17 -05:00
def delete_user!(user, %User{role: :admin}), do: user |> Repo.delete!()
def delete_user!(%User{id: user_id} = user, %User{id: user_id}), do: user |> Repo.delete!()
2021-03-11 21:12:55 -05:00
## Session
@doc """
Generates a session token.
"""
2022-02-25 21:52:17 -05:00
@spec generate_user_session_token(User.t()) :: String.t()
2021-03-11 21:12:55 -05:00
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.
"""
2022-11-23 21:15:52 -05:00
@spec get_user_by_session_token(token :: String.t()) :: User.t()
2021-03-11 21:12:55 -05:00
def get_user_by_session_token(token) do
{:ok, query} = UserToken.verify_session_token_query(token)
Repo.one(query)
end
@doc """
Deletes the signed token with the given context.
"""
2022-11-23 21:15:52 -05:00
@spec delete_session_token(token :: String.t()) :: :ok
2021-03-11 21:12:55 -05:00
def delete_session_token(token) do
Repo.delete_all(UserToken.token_and_context_query(token, "session"))
:ok
end
2022-02-25 21:52:17 -05:00
@doc """
Returns a boolean if registration is allowed or not
"""
@spec allow_registration?() :: boolean()
def allow_registration? do
2022-07-25 19:31:54 -04:00
Application.get_env(:memex, MemexWeb.Endpoint)[:registration] == "public" or
2022-02-25 21:52:17 -05:00
list_users_by_role(:admin) |> Enum.empty?()
end
@doc """
Checks if user is an admin
"""
@spec is_admin?(User.t()) :: boolean()
def is_admin?(%User{id: user_id}) do
2022-11-24 17:14:53 -05:00
Repo.exists?(from u in User, where: u.id == ^user_id and u.role == :admin)
2022-02-25 21:52:17 -05:00
end
2022-11-24 17:14:53 -05:00
@doc """
Checks to see if user has the admin role
"""
@spec is_already_admin?(User.t() | nil) :: boolean()
def is_already_admin?(%User{role: :admin}), do: true
def is_already_admin?(_invalid_user), do: false
2021-03-11 21:12:55 -05:00
## Confirmation
@doc """
Delivers the confirmation email instructions to the given user.
## Examples
iex> deliver_user_confirmation_instructions(user, &Routes.user_confirmation_url(conn, :confirm, &1))
{:ok, %{to: ..., body: ...}}
iex> deliver_user_confirmation_instructions(confirmed_user, &Routes.user_confirmation_url(conn, :confirm, &1))
{:error, :already_confirmed}
"""
2022-02-25 21:52:17 -05:00
@spec deliver_user_confirmation_instructions(User.t(), function) :: Job.t()
def deliver_user_confirmation_instructions(user, confirmation_url_fun)
2021-03-11 21:12:55 -05:00
when is_function(confirmation_url_fun, 1) do
if user.confirmed_at do
{:error, :already_confirmed}
else
{encoded_token, user_token} = UserToken.build_email_token(user, "confirm")
Repo.insert!(user_token)
2022-02-25 21:52:17 -05:00
Mailer.deliver_confirmation_instructions(user, confirmation_url_fun.(encoded_token))
2021-03-11 21:12:55 -05:00
end
end
@doc """
Confirms a user by the given token.
If the token matches, the user account is marked as confirmed
and the token is deleted.
"""
2022-11-23 21:15:52 -05:00
@spec confirm_user(token :: String.t()) :: {:ok, User.t()} | atom()
2021-03-11 21:12:55 -05:00
def confirm_user(token) do
with {:ok, query} <- UserToken.verify_email_token_query(token, "confirm"),
%User{} = user <- Repo.one(query),
{:ok, %{user: user}} <- Repo.transaction(confirm_user_multi(user)) do
{:ok, user}
else
_ -> :error
end
end
2022-02-25 21:52:17 -05:00
@spec confirm_user_multi(User.t()) :: Multi.t()
def confirm_user_multi(user) do
2022-02-25 21:52:17 -05:00
Multi.new()
|> Multi.update(:user, User.confirm_changeset(user))
|> Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, ["confirm"]))
2021-03-11 21:12:55 -05:00
end
## Reset password
@doc """
Delivers the reset password email to the given user.
## Examples
iex> deliver_user_reset_password_instructions(user, &Routes.user_reset_password_url(conn, :edit, &1))
{:ok, %{to: ..., body: ...}}
"""
2022-02-25 21:52:17 -05:00
@spec deliver_user_reset_password_instructions(User.t(), function()) :: Job.t()
def deliver_user_reset_password_instructions(user, reset_password_url_fun)
2021-03-11 21:12:55 -05:00
when is_function(reset_password_url_fun, 1) do
{encoded_token, user_token} = UserToken.build_email_token(user, "reset_password")
Repo.insert!(user_token)
2022-02-25 21:52:17 -05:00
Mailer.deliver_reset_password_instructions(user, reset_password_url_fun.(encoded_token))
2021-03-11 21:12:55 -05:00
end
@doc """
Gets the user by reset password token.
## Examples
iex> get_user_by_reset_password_token("validtoken")
%User{}
iex> get_user_by_reset_password_token("invalidtoken")
nil
"""
2022-11-23 21:15:52 -05:00
@spec get_user_by_reset_password_token(token :: String.t()) :: User.t() | nil
2021-03-11 21:12:55 -05:00
def get_user_by_reset_password_token(token) do
with {:ok, query} <- UserToken.verify_email_token_query(token, "reset_password"),
%User{} = user <- Repo.one(query) do
user
else
_ -> nil
end
end
@doc """
Resets the user password.
## Examples
iex> reset_user_password(user, %{password: "new long password", password_confirmation: "new long password"})
{:ok, %User{}}
iex> reset_user_password(user, %{password: "valid", password_confirmation: "not the same"})
2022-02-25 21:52:17 -05:00
{:error, %Changeset{}}
2021-03-11 21:12:55 -05:00
"""
2022-11-23 21:15:52 -05:00
@spec reset_user_password(User.t(), attrs :: map()) ::
{:ok, User.t()} | {:error, User.changeset()}
2021-03-11 21:12:55 -05:00
def reset_user_password(user, attrs) do
2022-02-25 21:52:17 -05:00
Multi.new()
|> Multi.update(:user, User.password_changeset(user, attrs))
|> Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, :all))
2021-03-11 21:12:55 -05:00
|> Repo.transaction()
|> case do
{:ok, %{user: user}} -> {:ok, user}
{:error, :user, changeset, _} -> {:error, changeset}
end
end
end