harden account deletion

This commit is contained in:
shibao 2022-02-12 00:34:11 -05:00
parent c0b3de75a9
commit 332f92a02f
3 changed files with 32 additions and 16 deletions

View File

@ -63,17 +63,20 @@ defmodule Cannery.Accounts do
@spec get_user!(User.t()) :: User.t() @spec get_user!(User.t()) :: User.t()
def get_user!(id), do: Repo.get!(User, id) def get_user!(id), do: Repo.get!(User, id)
@spec list_users_by_role(atom()) :: [User.t()]
def list_users_by_role(role), do: Repo.all(from u in User, where: u.role == ^role)
@spec list_all_users(boolean()) :: [User.t()] @doc """
def list_all_users(confirmed_users_only \\ true) do Returns all users for a certain role.
if confirmed_users_only do
from u in User, where: u.confirmed_at ## Examples
else
User iex> list_users_by_role(%User{id: 123, role: :admin})
end [%User{}]
|> Repo.all()
"""
@spec list_users_by_role(:admin | :user) :: [User.t()]
def list_users_by_role(role) do
role = role |> to_string()
Repo.all(from u in User, where: u.role == ^role)
end end
## User registration ## User registration
@ -253,8 +256,21 @@ defmodule Cannery.Accounts do
end end
end end
@spec delete_user!(User.t()) :: User.t() @doc """
def delete_user!(user), do: user |> Repo.delete!() 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{}
"""
@spec delete_user!(User.t(), User.t()) :: User.t()
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!()
## Session ## Session

View File

@ -70,9 +70,9 @@ defmodule CanneryWeb.UserSettingsController do
end end
end end
def delete(conn, %{"id" => user_id}) do def delete(%{assigns: %{current_user: current_user}} = conn, %{"id" => user_id}) do
if user_id == conn.assigns.current_user.id do if user_id == current_user.id do
Accounts.delete_user!(conn.assigns.current_user) current_user |> Accounts.delete_user!(current_user)
conn conn
|> put_flash(:error, dgettext("prompts", "Your account has been deleted")) |> put_flash(:error, dgettext("prompts", "Your account has been deleted"))

View File

@ -103,10 +103,10 @@ msgid "Saving..."
msgstr "" msgstr ""
#, elixir-format, ex-autogen #, elixir-format, ex-autogen
#: lib/cannery_web/components/tag_card.ex:33
#: lib/cannery_web/live/ammo_type_live/show.html.heex:26 #: lib/cannery_web/live/ammo_type_live/show.html.heex:26
#: lib/cannery_web/live/container_live/index.html.heex:36 #: lib/cannery_web/live/container_live/index.html.heex:36
#: lib/cannery_web/live/container_live/show.html.heex:36 #: lib/cannery_web/live/container_live/show.html.heex:36
#: lib/cannery_web/live/tag_live/index.html.heex:36
msgid "Are you sure you want to delete %{name}?" msgid "Are you sure you want to delete %{name}?"
msgstr "" msgstr ""