memEx/lib/memex/accounts.ex

555 lines
15 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}
2023-02-04 17:22:06 -05:00
alias Memex.Accounts.{Invite, Invites, 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
2023-02-25 00:49:29 -05:00
iex> get_user_by_email("foo@example.com")
%User{}
2021-03-11 21:12:55 -05:00
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
2023-02-04 17:22:06 -05:00
def get_user_by_email(email) when is_binary(email) do
Repo.get_by(User, email: email)
end
2021-03-11 21:12:55 -05:00
@doc """
Gets a user by email and password.
## Examples
2023-02-25 00:49:29 -05:00
iex> get_user_by_email_and_password("foo@example.com", "valid_password")
%User{}
2021-03-11 21:12:55 -05:00
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
2023-02-25 00:49:29 -05:00
iex> get_user!(user_id)
2023-01-29 14:36:44 -05:00
user
2021-03-11 21:12:55 -05:00
2023-02-25 00:49:29 -05:00
iex> get_user!()
2021-03-11 21:12:55 -05:00
** (Ecto.NoResultsError)
"""
2023-02-25 00:49:29 -05:00
@spec get_user!(User.id()) :: User.t()
2023-02-04 17:22:06 -05:00
def get_user!(id) do
Repo.get!(User, id)
end
2021-03-11 21:12:55 -05:00
2022-02-25 21:52:17 -05:00
@doc """
Returns all users grouped by role.
## Examples
2023-02-25 00:49:29 -05:00
iex> list_all_users_by_role(user1)
%{admin: [%User{role: :admin}], user: [%User{role: :user}]}
2022-02-25 21:52:17 -05:00
"""
2023-01-29 14:36:44 -05:00
@spec list_all_users_by_role(User.t()) :: %{User.role() => [User.t()]}
2022-02-25 21:52:17 -05:00
def list_all_users_by_role(%User{role: :admin}) do
2023-01-29 14:36:44 -05:00
Repo.all(from u in User, order_by: u.email) |> Enum.group_by(fn %{role: role} -> role end)
2022-02-25 21:52:17 -05:00
end
@doc """
Returns all users for a certain role.
## Examples
2023-02-25 00:49:29 -05:00
iex> list_users_by_role(:admin)
[%User{role: :admin}]
2022-02-25 21:52:17 -05:00
"""
2023-01-29 14:36:44 -05:00
@spec list_users_by_role(:admin) :: [User.t()]
def list_users_by_role(:admin = role) do
2022-02-25 21:52:17 -05:00
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
2023-02-25 00:49:29 -05:00
iex> register_user(%{email: "foo@example.com", password: "valid_password"})
{:ok, %User{email: "foo@example.com"}}
2021-03-11 21:12:55 -05:00
2023-02-25 00:49:29 -05:00
iex> register_user(%{email: "foo@example"})
{:error, %Changeset{}}
2021-03-11 21:12:55 -05:00
"""
2023-02-04 21:52:23 -05:00
@spec register_user(attrs :: map()) ::
{:ok, User.t()} | {:error, :invalid_token | User.changeset()}
2023-02-04 17:22:06 -05:00
@spec register_user(attrs :: map(), Invite.token() | nil) ::
{:ok, User.t()} | {:error, :invalid_token | User.changeset()}
def register_user(attrs, invite_token \\ nil) 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))
2023-02-04 17:22:06 -05:00
|> Multi.run(:use_invite, fn _changes_so_far, _repo ->
if allow_registration?() and invite_token |> is_nil() do
{:ok, nil}
else
Invites.use_invite(invite_token)
end
end)
|> Multi.insert(:add_user, fn %{users_count: count, use_invite: invite} ->
2022-11-23 21:15:52 -05:00
# if no registered users, make first user an admin
2023-01-29 12:56:44 -05:00
role = if count == 0, do: :admin, else: :user
2023-02-04 17:22:06 -05:00
User.registration_changeset(attrs, invite) |> User.role_changeset(role)
2022-11-23 21:15:52 -05:00
end)
|> Repo.transaction()
|> case do
{:ok, %{add_user: user}} -> {:ok, user}
2023-02-04 17:22:06 -05:00
{:error, :use_invite, :invalid_token, _changes_so_far} -> {:error, :invalid_token}
2022-11-23 21:15:52 -05:00
{: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
2023-02-25 00:49:29 -05:00
iex> change_user_registration()
%Changeset{}
2023-01-29 14:36:44 -05:00
2023-02-25 00:49:29 -05:00
iex> change_user_registration(%{password: "hi"}
%Changeset{}
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()
2023-02-04 17:22:06 -05:00
def change_user_registration(attrs \\ %{}) do
User.registration_changeset(attrs, nil, hash_password: false)
end
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
2023-02-25 00:49:29 -05:00
iex> change_user_email(%User{email: "foo@example.com"})
%Changeset{}
2021-03-11 21:12:55 -05:00
"""
2023-01-29 14:36:44 -05:00
@spec change_user_email(User.t()) :: User.changeset()
2022-11-23 21:15:52 -05:00
@spec change_user_email(User.t(), attrs :: map()) :: User.changeset()
2023-02-04 17:22:06 -05:00
def change_user_email(user, attrs \\ %{}) do
User.email_changeset(user, attrs)
end
2022-02-25 21:52:17 -05:00
@doc """
Returns an `%Changeset{}` for changing the user role.
## Examples
2023-02-25 00:49:29 -05:00
iex> change_user_role(%User{}, :user)
%Changeset{}
2022-02-25 21:52:17 -05:00
"""
2022-11-23 21:15:52 -05:00
@spec change_user_role(User.t(), User.role()) :: User.changeset()
2023-02-04 17:22:06 -05:00
def change_user_role(user, role) do
User.role_changeset(user, role)
end
2021-03-11 21:12:55 -05:00
@doc """
Emulates that the email will change without actually changing
it in the database.
## Examples
2023-02-25 00:49:29 -05:00
iex> apply_user_email(user, "valid_password", %{email: "new_email@account.com"})
{:ok, %User{}}
2021-03-11 21:12:55 -05:00
2023-02-25 00:49:29 -05:00
iex> apply_user_email(user, "invalid password", %{email: "new_email@account"})
{:error, %Changeset{}}
2021-03-11 21:12:55 -05:00
"""
2023-01-29 14:36:44 -05:00
@spec apply_user_email(User.t(), email :: String.t(), attrs :: map()) ::
2022-11-23 21:15:52 -05:00
{: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
2023-01-29 14:36:44 -05:00
_error_tuple -> :error
2021-03-11 21:12:55 -05:00
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
2023-02-25 00:49:29 -05:00
iex> deliver_update_email_instructions(user, "new_foo@example.com", fn _token -> "example url" end)
%Oban.Job{args: %{email: :update_email, user_id: ^user_id, attrs: %{url: "example url"}}}
2021-03-11 21:12:55 -05:00
"""
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
2023-02-25 00:49:29 -05:00
iex> change_user_password(%User{})
%Changeset{}
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()
2023-02-04 17:22:06 -05:00
def change_user_password(user, attrs \\ %{}) do
User.password_changeset(user, attrs, hash_password: false)
end
2021-03-11 21:12:55 -05:00
@doc """
Updates the user password.
## Examples
2023-02-25 00:49:29 -05:00
iex> reset_user_password(user, %{
...> password: "new password",
...> password_confirmation: "new password"
...> })
{:ok, %User{}}
iex> update_user_password(user, "invalid password", %{password: "123"})
{:error, %Changeset{}}
2021-03-11 21:12:55 -05:00
"""
2023-01-29 14:36:44 -05:00
@spec update_user_password(User.t(), String.t(), attrs :: map()) ::
2022-11-23 21:15:52 -05:00
{: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}
2023-01-29 14:36:44 -05:00
{:error, :user, changeset, _changes_so_far} -> {:error, changeset}
2021-03-11 21:12:55 -05:00
end
end
2022-05-05 20:55:59 -04:00
@doc """
2023-01-29 14:36:44 -05:00
Returns an `Ecto.Changeset.t()` for changing the user locale.
2022-05-05 20:55:59 -04:00
## Examples
2023-02-25 00:49:29 -05:00
iex> change_user_locale(%User{})
%Changeset{}
2022-05-05 20:55:59 -04:00
"""
2022-11-23 21:15:52 -05:00
@spec change_user_locale(User.t()) :: User.changeset()
2023-02-04 17:22:06 -05:00
def change_user_locale(%{locale: locale} = user) do
User.locale_changeset(user, locale)
end
2022-05-05 20:55:59 -04:00
@doc """
Updates the user locale.
## Examples
2023-02-25 00:49:29 -05:00
iex> update_user_locale(user, "en_US")
{:ok, %User{}}
2022-05-05 20:55:59 -04:00
"""
@spec update_user_locale(User.t(), locale :: String.t()) ::
2022-11-23 21:15:52 -05:00
{:ok, User.t()} | {:error, User.changeset()}
2023-02-04 17:22:06 -05:00
def update_user_locale(user, locale) do
user |> User.locale_changeset(locale) |> Repo.update()
end
2022-05-05 20:55:59 -04:00
2022-02-25 21:52:17 -05:00
@doc """
Deletes a user. must be performed by an admin or the same user!
## Examples
2023-02-25 00:49:29 -05:00
iex> delete_user!(user, %User{id: 123, role: :admin})
%User{}
2022-02-25 21:52:17 -05:00
2023-02-25 00:49:29 -05:00
iex> delete_user!(user, user)
%User{}
2022-02-25 21:52:17 -05:00
"""
2022-11-23 21:15:52 -05:00
@spec delete_user!(user_to_delete :: User.t(), User.t()) :: User.t()
2023-02-04 17:22:06 -05:00
def delete_user!(user, %User{role: :admin}) do
user |> Repo.delete!()
end
def delete_user!(%User{id: user_id} = user, %User{id: user_id}) do
user |> Repo.delete!()
end
2022-02-25 21:52:17 -05:00
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.
"""
2023-04-13 23:29:29 -04:00
@spec delete_user_session_token(token :: String.t()) :: :ok
def delete_user_session_token(token) do
2023-02-04 17:22:06 -05:00
UserToken.token_and_context_query(token, "session") |> Repo.delete_all()
2021-03-11 21:12:55 -05:00
: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
2023-02-04 09:57:10 -05:00
Application.get_env(:memex, Memex.Accounts)[:registration] == "public" or
2022-02-25 21:52:17 -05:00
list_users_by_role(:admin) |> Enum.empty?()
end
2023-03-18 01:31:56 -04:00
@doc """
Returns an atom representing the current configured registration mode
"""
@spec registration_mode() :: :public | :invite_only
def registration_mode do
case Application.get_env(:memex, Memex.Accounts)[:registration] do
"public" -> :public
_other -> :invite_only
end
end
2022-02-25 21:52:17 -05:00
@doc """
Checks if user is an admin
2023-01-29 14:36:44 -05:00
## Examples
2024-02-23 22:17:19 -05:00
iex> admin?(%User{role: :admin})
2023-01-29 14:36:44 -05:00
true
2024-02-23 22:17:19 -05:00
iex> admin?(%User{})
2023-01-29 14:36:44 -05:00
false
2022-02-25 21:52:17 -05:00
"""
2024-02-23 22:17:19 -05:00
@spec admin?(User.t()) :: boolean()
def admin?(%User{id: user_id}) do
2023-01-29 14:36:44 -05:00
Repo.exists?(from u in User, where: u.id == ^user_id, where: 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
2023-01-29 14:36:44 -05:00
## Examples
iex> already_admin?(%User{role: :admin})
2023-01-29 14:36:44 -05:00
true
iex> already_admin?(%User{})
2023-01-29 14:36:44 -05:00
false
2022-11-24 17:14:53 -05:00
"""
@spec already_admin?(User.t() | nil) :: boolean()
def already_admin?(%User{role: :admin}), do: true
def already_admin?(_invalid_user), do: false
2022-11-24 17:14:53 -05:00
2021-03-11 21:12:55 -05:00
## Confirmation
@doc """
Delivers the confirmation email instructions to the given user.
## Examples
2023-02-25 00:49:29 -05:00
iex> deliver_user_confirmation_instructions(user, fn _token -> "example url" end)
%Oban.Job{args: %{email: :welcome, user_id: ^user_id, attrs: %{url: "example url"}}}
2021-03-11 21:12:55 -05:00
2023-01-29 14:36:44 -05:00
iex> deliver_user_confirmation_instructions(user, fn _token -> "example url" end)
2021-03-11 21:12:55 -05:00
{: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.
"""
2023-01-29 14:36:44 -05:00
@spec confirm_user(token :: String.t()) :: {:ok, User.t()} | :error
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
2023-01-29 14:36:44 -05:00
_error_tuple -> :error
2021-03-11 21:12:55 -05:00
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
2023-02-25 00:49:29 -05:00
iex> deliver_user_reset_password_instructions(user, fn _token -> "example url" end)
%Oban.Job{args: %{email: :reset_password, user_id: ^user_id, attrs: %{url: "example url"}}}
2021-03-11 21:12:55 -05:00
"""
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
2023-02-25 00:49:29 -05:00
iex> get_user_by_reset_password_token(encoded_token)
%User{}
2021-03-11 21:12:55 -05:00
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
2023-01-29 14:36:44 -05:00
_error_tuple -> nil
2021-03-11 21:12:55 -05:00
end
end
@doc """
Resets the user password.
## Examples
2023-02-25 00:49:29 -05:00
iex> reset_user_password(user, %{
...> password: "new password",
...> password_confirmation: "new password"
...> })
{:ok, %User{}}
iex> reset_user_password(user, %{password: "valid", password_confirmation: "not the same"})
{: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}
2023-01-29 14:36:44 -05:00
{:error, :user, changeset, _changes_so_far} -> {:error, changeset}
2021-03-11 21:12:55 -05:00
end
end
end