memEx/lib/lokal/accounts/user.ex

215 lines
7.0 KiB
Elixir
Raw Normal View History

2021-03-11 21:12:55 -05:00
defmodule Lokal.Accounts.User do
2022-01-22 20:44:38 -05:00
@moduledoc """
2022-02-25 21:55:17 -05:00
A Lokal user
2022-01-22 20:44:38 -05:00
"""
2021-03-11 21:12:55 -05:00
use Ecto.Schema
import Ecto.Changeset
2022-02-25 21:55:17 -05:00
import LokalWeb.Gettext
2023-02-04 16:11:58 -05:00
alias Ecto.{Association, Changeset, UUID}
2023-02-04 14:14:45 -05:00
alias Lokal.Accounts.{Invite, User}
2021-03-11 21:12:55 -05:00
2023-01-29 14:30:42 -05:00
@derive {Jason.Encoder,
only: [
:id,
:email,
:confirmed_at,
:role,
2023-02-04 17:28:53 -05:00
:locale,
:inserted_at,
:updated_at
2023-01-29 14:30:42 -05:00
]}
2021-03-11 21:12:55 -05:00
@derive {Inspect, except: [:password]}
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "users" do
field :email, :string
field :password, :string, virtual: true
field :hashed_password, :string
field :confirmed_at, :naive_datetime
2022-02-25 21:55:17 -05:00
field :role, Ecto.Enum, values: [:admin, :user], default: :user
2022-05-05 20:55:59 -04:00
field :locale, :string
2022-02-25 21:55:17 -05:00
2023-02-04 16:11:58 -05:00
has_many :created_invites, Invite, foreign_key: :created_by_id
belongs_to :invite, Invite
2021-03-11 21:12:55 -05:00
timestamps()
end
2022-02-25 21:55:17 -05:00
@type t :: %User{
id: id(),
email: String.t(),
password: String.t(),
hashed_password: String.t(),
confirmed_at: NaiveDateTime.t(),
2023-01-29 14:30:42 -05:00
role: role(),
2022-05-05 20:55:59 -04:00
locale: String.t() | nil,
2023-02-04 16:11:58 -05:00
created_invites: [Invite.t()] | Association.NotLoaded.t(),
invite: Invite.t() | nil | Association.NotLoaded.t(),
invite_id: Invite.id() | nil,
2022-02-25 21:55:17 -05:00
inserted_at: NaiveDateTime.t(),
updated_at: NaiveDateTime.t()
}
@type new_user :: %User{}
@type id :: UUID.t()
2023-01-29 14:30:42 -05:00
@type changeset :: Changeset.t(t() | new_user())
@type role :: :admin | :user
2022-02-25 21:55:17 -05:00
2021-03-11 21:12:55 -05:00
@doc """
A user changeset for registration.
It is important to validate the length of both email and password.
Otherwise databases may truncate the email without warnings, which
could lead to unpredictable or insecure behaviour. Long passwords may
also be very expensive to hash for certain algorithms.
## Options
* `:hash_password` - Hashes the password so it can be stored securely
in the database and ensures the password field is cleared to prevent
leaks in the logs. If password hashing is not needed and clearing the
password field is not desired (like when using this changeset for
validations on a LiveView form), this option can be set to `false`.
Defaults to `true`.
"""
2023-02-04 16:11:58 -05:00
@spec registration_changeset(attrs :: map(), Invite.t() | nil) :: changeset()
@spec registration_changeset(attrs :: map(), Invite.t() | nil, opts :: keyword()) :: changeset()
def registration_changeset(attrs, invite, opts \\ []) do
2023-01-29 14:30:42 -05:00
%User{}
|> cast(attrs, [:email, :password, :locale])
2023-02-04 16:11:58 -05:00
|> put_change(:invite_id, if(invite, do: invite.id))
2021-03-11 21:12:55 -05:00
|> validate_email()
|> validate_password(opts)
end
2022-02-25 21:55:17 -05:00
@doc """
A user changeset for role.
"""
2023-01-29 14:30:42 -05:00
@spec role_changeset(t() | new_user() | changeset(), role()) :: changeset()
2022-02-25 21:55:17 -05:00
def role_changeset(user, role) do
2023-01-29 14:30:42 -05:00
user |> change(role: role)
2022-02-25 21:55:17 -05:00
end
2023-01-29 14:30:42 -05:00
@spec validate_email(changeset()) :: changeset()
2021-03-11 21:12:55 -05:00
defp validate_email(changeset) do
changeset
|> validate_required([:email])
2022-02-25 21:55:17 -05:00
|> validate_format(:email, ~r/^[^\s]+@[^\s]+$/,
message: dgettext("errors", "must have the @ sign and no spaces")
)
2021-03-11 21:12:55 -05:00
|> validate_length(:email, max: 160)
|> unsafe_validate_unique(:email, Lokal.Repo)
|> unique_constraint(:email)
end
2023-01-29 14:30:42 -05:00
@spec validate_password(changeset(), opts :: keyword()) ::
changeset()
2021-03-11 21:12:55 -05:00
defp validate_password(changeset, opts) do
changeset
|> validate_required([:password])
|> validate_length(:password, min: 12, max: 80)
# |> validate_format(:password, ~r/[a-z]/, message: "at least one lower case character")
# |> validate_format(:password, ~r/[A-Z]/, message: "at least one upper case character")
# |> validate_format(:password, ~r/[!?@#$%^&*_0-9]/, message: "at least one digit or punctuation character")
|> maybe_hash_password(opts)
end
2023-01-29 14:30:42 -05:00
@spec maybe_hash_password(changeset(), opts :: keyword()) :: changeset()
2021-03-11 21:12:55 -05:00
defp maybe_hash_password(changeset, opts) do
hash_password? = Keyword.get(opts, :hash_password, true)
password = get_change(changeset, :password)
if hash_password? && password && changeset.valid? do
changeset
|> put_change(:hashed_password, Bcrypt.hash_pwd_salt(password))
|> delete_change(:password)
else
changeset
end
end
@doc """
A user changeset for changing the email.
It requires the email to change otherwise an error is added.
"""
2023-01-29 14:30:42 -05:00
@spec email_changeset(t(), attrs :: map()) :: changeset()
2021-03-11 21:12:55 -05:00
def email_changeset(user, attrs) do
user
|> cast(attrs, [:email])
|> validate_email()
|> case do
%{changes: %{email: _}} = changeset -> changeset
2022-02-25 21:55:17 -05:00
%{} = changeset -> add_error(changeset, :email, dgettext("errors", "did not change"))
2021-03-11 21:12:55 -05:00
end
end
@doc """
A user changeset for changing the password.
## Options
* `:hash_password` - Hashes the password so it can be stored securely
in the database and ensures the password field is cleared to prevent
leaks in the logs. If password hashing is not needed and clearing the
password field is not desired (like when using this changeset for
validations on a LiveView form), this option can be set to `false`.
Defaults to `true`.
"""
2023-01-29 14:30:42 -05:00
@spec password_changeset(t(), attrs :: map()) :: changeset()
@spec password_changeset(t(), attrs :: map(), opts :: keyword()) :: changeset()
2021-03-11 21:12:55 -05:00
def password_changeset(user, attrs, opts \\ []) do
user
|> cast(attrs, [:password])
2022-02-25 21:55:17 -05:00
|> validate_confirmation(:password, message: dgettext("errors", "does not match password"))
2021-03-11 21:12:55 -05:00
|> validate_password(opts)
end
@doc """
Confirms the account by setting `confirmed_at`.
"""
2023-01-29 14:30:42 -05:00
@spec confirm_changeset(t() | changeset()) :: changeset()
2022-02-25 21:55:17 -05:00
def confirm_changeset(user_or_changeset) do
2021-03-11 21:12:55 -05:00
now = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second)
2022-02-25 21:55:17 -05:00
user_or_changeset |> change(confirmed_at: now)
2021-03-11 21:12:55 -05:00
end
@doc """
Verifies the password.
If there is no user or the user doesn't have a password, we call
`Bcrypt.no_user_verify/0` to avoid timing attacks.
"""
2022-02-25 21:55:17 -05:00
@spec valid_password?(t(), String.t()) :: boolean()
def valid_password?(%User{hashed_password: hashed_password}, password)
2021-03-11 21:12:55 -05:00
when is_binary(hashed_password) and byte_size(password) > 0 do
Bcrypt.verify_pass(password, hashed_password)
end
2023-01-29 14:30:42 -05:00
def valid_password?(_invalid_user, _invalid_password) do
2021-03-11 21:12:55 -05:00
Bcrypt.no_user_verify()
false
end
@doc """
Validates the current password otherwise adds an error to the changeset.
"""
2023-01-29 14:30:42 -05:00
@spec validate_current_password(changeset(), String.t()) :: changeset()
2021-03-11 21:12:55 -05:00
def validate_current_password(changeset, password) do
2022-02-25 21:55:17 -05:00
if valid_password?(changeset.data, password),
do: changeset,
else: changeset |> add_error(:current_password, dgettext("errors", "is not valid"))
2021-03-11 21:12:55 -05:00
end
2022-05-05 20:55:59 -04:00
@doc """
A changeset for changing the user's locale
"""
2023-01-29 14:30:42 -05:00
@spec locale_changeset(t() | changeset(), locale :: String.t() | nil) :: changeset()
2022-05-05 20:55:59 -04:00
def locale_changeset(user_or_changeset, locale) do
user_or_changeset
|> cast(%{"locale" => locale}, [:locale])
|> validate_required(:locale)
end
2021-03-11 21:12:55 -05:00
end