forked from shibao/cannery
rename to cannery
This commit is contained in:
543
lib/cannery/accounts.ex
Normal file
543
lib/cannery/accounts.ex
Normal file
@ -0,0 +1,543 @@
|
||||
defmodule Cannery.Accounts do
|
||||
@moduledoc """
|
||||
The Accounts context.
|
||||
"""
|
||||
|
||||
import Ecto.Query, warn: false
|
||||
alias Cannery.{Mailer, Repo}
|
||||
alias Cannery.Accounts.{Invite, Invites, User, UserToken}
|
||||
alias Ecto.{Changeset, Multi}
|
||||
alias Oban.Job
|
||||
|
||||
## 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
|
||||
|
||||
"""
|
||||
@spec get_user_by_email(email :: String.t()) :: User.t() | 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", "valid_password")
|
||||
%User{}
|
||||
|
||||
iex> get_user_by_email_and_password("foo@example.com", "invalid_password")
|
||||
nil
|
||||
|
||||
"""
|
||||
@spec get_user_by_email_and_password(email :: String.t(), password :: String.t()) ::
|
||||
User.t() | 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!(user_id)
|
||||
user
|
||||
|
||||
iex> get_user!()
|
||||
** (Ecto.NoResultsError)
|
||||
|
||||
"""
|
||||
@spec get_user!(User.id()) :: User.t()
|
||||
def get_user!(id) do
|
||||
Repo.get!(User, id)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns all users grouped by role.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> list_all_users_by_role(user1)
|
||||
%{admin: [%User{role: :admin}], user: [%User{role: :user}]}
|
||||
|
||||
"""
|
||||
@spec list_all_users_by_role(User.t()) :: %{User.role() => [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 %{role: role} -> role end)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns all users for a certain role.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> list_users_by_role(:admin)
|
||||
[%User{role: :admin}]
|
||||
|
||||
"""
|
||||
@spec list_users_by_role(:admin) :: [User.t()]
|
||||
def list_users_by_role(:admin = role) do
|
||||
Repo.all(from u in User, where: u.role == ^role, order_by: u.email)
|
||||
end
|
||||
|
||||
## User registration
|
||||
|
||||
@doc """
|
||||
Registers a user.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> register_user(%{email: "foo@example.com", password: "valid_password"})
|
||||
{:ok, %User{email: "foo@example.com"}}
|
||||
|
||||
iex> register_user(%{email: "foo@example"})
|
||||
{:error, %Changeset{}}
|
||||
|
||||
"""
|
||||
@spec register_user(attrs :: map()) ::
|
||||
{:ok, User.t()} | {:error, :invalid_token | User.changeset()}
|
||||
@spec register_user(attrs :: map(), Invite.token() | nil) ::
|
||||
{:ok, User.t()} | {:error, :invalid_token | User.changeset()}
|
||||
def register_user(attrs, invite_token \\ nil) do
|
||||
Multi.new()
|
||||
|> Multi.one(:users_count, from(u in User, select: count(u.id), distinct: true))
|
||||
|> 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} ->
|
||||
# if no registered users, make first user an admin
|
||||
role = if count == 0, do: :admin, else: :user
|
||||
User.registration_changeset(attrs, invite) |> User.role_changeset(role)
|
||||
end)
|
||||
|> Repo.transaction()
|
||||
|> case do
|
||||
{:ok, %{add_user: user}} -> {:ok, user}
|
||||
{:error, :use_invite, :invalid_token, _changes_so_far} -> {:error, :invalid_token}
|
||||
{:error, :add_user, changeset, _changes_so_far} -> {:error, changeset}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns an `%Changeset{}` for tracking user changes.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> change_user_registration()
|
||||
%Changeset{}
|
||||
|
||||
iex> change_user_registration(%{password: "hi"}
|
||||
%Changeset{}
|
||||
|
||||
"""
|
||||
@spec change_user_registration() :: User.changeset()
|
||||
@spec change_user_registration(attrs :: map()) :: User.changeset()
|
||||
def change_user_registration(attrs \\ %{}) do
|
||||
User.registration_changeset(attrs, nil, hash_password: false)
|
||||
end
|
||||
|
||||
## Settings
|
||||
|
||||
@doc """
|
||||
Returns an `%Changeset{}` for changing the user email.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> change_user_email(%User{email: "foo@example.com"})
|
||||
%Changeset{}
|
||||
|
||||
"""
|
||||
@spec change_user_email(User.t()) :: User.changeset()
|
||||
@spec change_user_email(User.t(), attrs :: map()) :: User.changeset()
|
||||
def change_user_email(user, attrs \\ %{}) do
|
||||
User.email_changeset(user, attrs)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns an `%Changeset{}` for changing the user role.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> change_user_role(%User{}, :user)
|
||||
%Changeset{}
|
||||
|
||||
"""
|
||||
@spec change_user_role(User.t(), User.role()) :: User.changeset()
|
||||
def change_user_role(user, role) do
|
||||
User.role_changeset(user, role)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Emulates that the email will change without actually changing
|
||||
it in the database.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> apply_user_email(user, "valid_password", %{email: "new_email@account.com"})
|
||||
{:ok, %User{}}
|
||||
|
||||
iex> apply_user_email(user, "invalid password", %{email: "new_email@account"})
|
||||
{:error, %Changeset{}}
|
||||
|
||||
"""
|
||||
@spec apply_user_email(User.t(), email :: String.t(), attrs :: map()) ::
|
||||
{:ok, User.t()} | {:error, User.changeset()}
|
||||
def apply_user_email(user, password, attrs) do
|
||||
user
|
||||
|> User.email_changeset(attrs)
|
||||
|> User.validate_current_password(password)
|
||||
|> Changeset.apply_action(:update)
|
||||
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.
|
||||
"""
|
||||
@spec update_user_email(User.t(), token :: String.t()) :: :ok | :error
|
||||
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_tuple -> :error
|
||||
end
|
||||
end
|
||||
|
||||
@spec user_email_multi(User.t(), email :: String.t(), context :: String.t()) :: Multi.t()
|
||||
defp user_email_multi(user, email, context) do
|
||||
changeset = user |> User.email_changeset(%{email: email}) |> User.confirm_changeset()
|
||||
|
||||
Multi.new()
|
||||
|> Multi.update(:user, changeset)
|
||||
|> Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, [context]))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Delivers the update email instructions to the given user.
|
||||
|
||||
## Examples
|
||||
|
||||
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"}}}
|
||||
|
||||
"""
|
||||
@spec deliver_update_email_instructions(User.t(), current_email :: String.t(), function) ::
|
||||
Job.t()
|
||||
def deliver_update_email_instructions(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)
|
||||
Mailer.deliver_update_email_instructions(user, update_email_url_fun.(encoded_token))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns an `%Changeset{}` for changing the user password.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> change_user_password(%User{})
|
||||
%Changeset{}
|
||||
|
||||
"""
|
||||
@spec change_user_password(User.t(), attrs :: map()) :: User.changeset()
|
||||
def change_user_password(user, attrs \\ %{}) do
|
||||
User.password_changeset(user, attrs, hash_password: false)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Updates the user password.
|
||||
|
||||
## Examples
|
||||
|
||||
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{}}
|
||||
|
||||
"""
|
||||
@spec update_user_password(User.t(), String.t(), attrs :: map()) ::
|
||||
{:ok, User.t()} | {:error, User.changeset()}
|
||||
def update_user_password(user, password, attrs) do
|
||||
changeset =
|
||||
user
|
||||
|> User.password_changeset(attrs)
|
||||
|> User.validate_current_password(password)
|
||||
|
||||
Multi.new()
|
||||
|> Multi.update(:user, changeset)
|
||||
|> Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, :all))
|
||||
|> Repo.transaction()
|
||||
|> case do
|
||||
{:ok, %{user: user}} -> {:ok, user}
|
||||
{:error, :user, changeset, _changes_so_far} -> {:error, changeset}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns an `Ecto.Changeset.t()` for changing the user locale.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> change_user_locale(%User{})
|
||||
%Changeset{}
|
||||
|
||||
"""
|
||||
@spec change_user_locale(User.t()) :: User.changeset()
|
||||
def change_user_locale(%{locale: locale} = user) do
|
||||
User.locale_changeset(user, locale)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Updates the user locale.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> update_user_locale(user, "en_US")
|
||||
{:ok, %User{}}
|
||||
|
||||
"""
|
||||
@spec update_user_locale(User.t(), locale :: String.t()) ::
|
||||
{:ok, User.t()} | {:error, User.changeset()}
|
||||
def update_user_locale(user, locale) do
|
||||
user |> User.locale_changeset(locale) |> Repo.update()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deletes a user. must be performed by an admin or the same user!
|
||||
|
||||
## Examples
|
||||
|
||||
iex> delete_user!(user, %User{id: 123, role: :admin})
|
||||
%User{}
|
||||
|
||||
iex> delete_user!(user, user)
|
||||
%User{}
|
||||
|
||||
"""
|
||||
@spec delete_user!(user_to_delete :: User.t(), User.t()) :: User.t()
|
||||
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
|
||||
|
||||
## Session
|
||||
|
||||
@doc """
|
||||
Generates a session token.
|
||||
"""
|
||||
@spec generate_user_session_token(User.t()) :: String.t()
|
||||
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.
|
||||
"""
|
||||
@spec get_user_by_session_token(token :: String.t()) :: User.t()
|
||||
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.
|
||||
"""
|
||||
@spec delete_session_token(token :: String.t()) :: :ok
|
||||
def delete_session_token(token) do
|
||||
UserToken.token_and_context_query(token, "session") |> Repo.delete_all()
|
||||
:ok
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a boolean if registration is allowed or not
|
||||
"""
|
||||
@spec allow_registration?() :: boolean()
|
||||
def allow_registration? do
|
||||
Application.get_env(:cannery, Cannery.Accounts)[:registration] == "public" or
|
||||
list_users_by_role(:admin) |> Enum.empty?()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Checks if user is an admin
|
||||
|
||||
## Examples
|
||||
|
||||
iex> is_admin?(%User{role: :admin})
|
||||
true
|
||||
|
||||
iex> is_admin?(%User{})
|
||||
false
|
||||
|
||||
"""
|
||||
@spec is_admin?(User.t()) :: boolean()
|
||||
def is_admin?(%User{id: user_id}) do
|
||||
Repo.exists?(from u in User, where: u.id == ^user_id, where: u.role == :admin)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Checks to see if user has the admin role
|
||||
|
||||
## Examples
|
||||
|
||||
iex> is_already_admin?(%User{role: :admin})
|
||||
true
|
||||
|
||||
iex> is_already_admin?(%User{})
|
||||
false
|
||||
|
||||
"""
|
||||
@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
|
||||
|
||||
## Confirmation
|
||||
|
||||
@doc """
|
||||
Delivers the confirmation email instructions to the given user.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> deliver_user_confirmation_instructions(user, fn _token -> "example url" end)
|
||||
%Oban.Job{args: %{email: :welcome, user_id: ^user_id, attrs: %{url: "example url"}}}
|
||||
|
||||
iex> deliver_user_confirmation_instructions(user, fn _token -> "example url" end)
|
||||
{:error, :already_confirmed}
|
||||
|
||||
"""
|
||||
@spec deliver_user_confirmation_instructions(User.t(), function) :: Job.t()
|
||||
def deliver_user_confirmation_instructions(user, confirmation_url_fun)
|
||||
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)
|
||||
Mailer.deliver_confirmation_instructions(user, confirmation_url_fun.(encoded_token))
|
||||
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.
|
||||
"""
|
||||
@spec confirm_user(token :: String.t()) :: {:ok, User.t()} | :error
|
||||
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_tuple -> :error
|
||||
end
|
||||
end
|
||||
|
||||
@spec confirm_user_multi(User.t()) :: Multi.t()
|
||||
def confirm_user_multi(user) do
|
||||
Multi.new()
|
||||
|> Multi.update(:user, User.confirm_changeset(user))
|
||||
|> Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, ["confirm"]))
|
||||
end
|
||||
|
||||
## Reset password
|
||||
|
||||
@doc """
|
||||
Delivers the reset password email to the given user.
|
||||
|
||||
## Examples
|
||||
|
||||
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"}}}
|
||||
|
||||
"""
|
||||
@spec deliver_user_reset_password_instructions(User.t(), function()) :: Job.t()
|
||||
def deliver_user_reset_password_instructions(user, reset_password_url_fun)
|
||||
when is_function(reset_password_url_fun, 1) do
|
||||
{encoded_token, user_token} = UserToken.build_email_token(user, "reset_password")
|
||||
Repo.insert!(user_token)
|
||||
Mailer.deliver_reset_password_instructions(user, reset_password_url_fun.(encoded_token))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets the user by reset password token.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> get_user_by_reset_password_token(encoded_token)
|
||||
%User{}
|
||||
|
||||
iex> get_user_by_reset_password_token("invalidtoken")
|
||||
nil
|
||||
|
||||
"""
|
||||
@spec get_user_by_reset_password_token(token :: String.t()) :: User.t() | nil
|
||||
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
|
||||
_error_tuple -> nil
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Resets the user password.
|
||||
|
||||
## Examples
|
||||
|
||||
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{}}
|
||||
|
||||
"""
|
||||
@spec reset_user_password(User.t(), attrs :: map()) ::
|
||||
{:ok, User.t()} | {:error, User.changeset()}
|
||||
def reset_user_password(user, attrs) do
|
||||
Multi.new()
|
||||
|> Multi.update(:user, User.password_changeset(user, attrs))
|
||||
|> Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, :all))
|
||||
|> Repo.transaction()
|
||||
|> case do
|
||||
{:ok, %{user: user}} -> {:ok, user}
|
||||
{:error, :user, changeset, _changes_so_far} -> {:error, changeset}
|
||||
end
|
||||
end
|
||||
end
|
48
lib/cannery/accounts/email.ex
Normal file
48
lib/cannery/accounts/email.ex
Normal file
@ -0,0 +1,48 @@
|
||||
defmodule Cannery.Email do
|
||||
@moduledoc """
|
||||
Emails that can be sent using Swoosh.
|
||||
|
||||
You can find the base email templates at
|
||||
`lib/Cannery_web/templates/layout/email.html.heex` for html emails and
|
||||
`lib/Cannery_web/templates/layout/email.txt.heex` for text emails.
|
||||
"""
|
||||
|
||||
use Phoenix.Swoosh, view: CanneryWeb.EmailView, layout: {CanneryWeb.LayoutView, :email}
|
||||
import CanneryWeb.Gettext
|
||||
alias Cannery.Accounts.User
|
||||
alias CanneryWeb.EmailView
|
||||
|
||||
@typedoc """
|
||||
Represents an HTML and text body email that can be sent
|
||||
"""
|
||||
@type t() :: Swoosh.Email.t()
|
||||
|
||||
@spec base_email(User.t(), String.t()) :: t()
|
||||
defp base_email(%User{email: email}, subject) do
|
||||
from = Application.get_env(:Cannery, Cannery.Mailer)[:email_from] || "noreply@localhost"
|
||||
name = Application.get_env(:Cannery, Cannery.Mailer)[:email_name]
|
||||
new() |> to(email) |> from({name, from}) |> subject(subject)
|
||||
end
|
||||
|
||||
@spec generate_email(key :: String.t(), User.t(), attrs :: map()) :: t()
|
||||
def generate_email("welcome", user, %{"url" => url}) do
|
||||
user
|
||||
|> base_email(dgettext("emails", "Confirm your Cannery account"))
|
||||
|> render_body("confirm_email.html", %{user: user, url: url})
|
||||
|> text_body(EmailView.render("confirm_email.txt", %{user: user, url: url}))
|
||||
end
|
||||
|
||||
def generate_email("reset_password", user, %{"url" => url}) do
|
||||
user
|
||||
|> base_email(dgettext("emails", "Reset your Cannery password"))
|
||||
|> render_body("reset_password.html", %{user: user, url: url})
|
||||
|> text_body(EmailView.render("reset_password.txt", %{user: user, url: url}))
|
||||
end
|
||||
|
||||
def generate_email("update_email", user, %{"url" => url}) do
|
||||
user
|
||||
|> base_email(dgettext("emails", "Update your Cannery email"))
|
||||
|> render_body("update_email.html", %{user: user, url: url})
|
||||
|> text_body(EmailView.render("update_email.txt", %{user: user, url: url}))
|
||||
end
|
||||
end
|
13
lib/cannery/accounts/email_worker.ex
Normal file
13
lib/cannery/accounts/email_worker.ex
Normal file
@ -0,0 +1,13 @@
|
||||
defmodule Cannery.EmailWorker do
|
||||
@moduledoc """
|
||||
Oban worker that dispatches emails
|
||||
"""
|
||||
|
||||
use Oban.Worker, queue: :mailers, tags: ["email"]
|
||||
alias Cannery.{Accounts, Email, Mailer}
|
||||
|
||||
@impl Oban.Worker
|
||||
def perform(%Oban.Job{args: %{"email" => email, "user_id" => user_id, "attrs" => attrs}}) do
|
||||
Email.generate_email(email, user_id |> Accounts.get_user!(), attrs) |> Mailer.deliver()
|
||||
end
|
||||
end
|
63
lib/cannery/accounts/invite.ex
Normal file
63
lib/cannery/accounts/invite.ex
Normal file
@ -0,0 +1,63 @@
|
||||
defmodule Cannery.Accounts.Invite do
|
||||
@moduledoc """
|
||||
An invite, created by an admin to allow someone to join their instance. An
|
||||
invite can be enabled or disabled, and can have an optional number of uses if
|
||||
`:uses_left` is defined.
|
||||
"""
|
||||
|
||||
use Ecto.Schema
|
||||
import Ecto.Changeset
|
||||
alias Cannery.Accounts.User
|
||||
alias Ecto.{Association, Changeset, UUID}
|
||||
|
||||
@primary_key {:id, :binary_id, autogenerate: true}
|
||||
@foreign_key_type :binary_id
|
||||
schema "invites" do
|
||||
field :name, :string
|
||||
field :token, :string
|
||||
field :uses_left, :integer, default: nil
|
||||
field :disabled_at, :naive_datetime
|
||||
|
||||
belongs_to :created_by, User
|
||||
|
||||
has_many :users, User
|
||||
|
||||
timestamps()
|
||||
end
|
||||
|
||||
@type t :: %__MODULE__{
|
||||
id: id(),
|
||||
name: String.t(),
|
||||
token: token(),
|
||||
uses_left: integer() | nil,
|
||||
disabled_at: NaiveDateTime.t(),
|
||||
created_by: User.t() | nil | Association.NotLoaded.t(),
|
||||
created_by_id: User.id() | nil,
|
||||
users: [User.t()] | Association.NotLoaded.t(),
|
||||
inserted_at: NaiveDateTime.t(),
|
||||
updated_at: NaiveDateTime.t()
|
||||
}
|
||||
@type new_invite :: %__MODULE__{}
|
||||
@type id :: UUID.t()
|
||||
@type changeset :: Changeset.t(t() | new_invite())
|
||||
@type token :: String.t()
|
||||
|
||||
@doc false
|
||||
@spec create_changeset(User.t(), token(), attrs :: map()) :: changeset()
|
||||
def create_changeset(%User{id: user_id}, token, attrs) do
|
||||
%__MODULE__{}
|
||||
|> change(token: token, created_by_id: user_id)
|
||||
|> cast(attrs, [:name, :uses_left, :disabled_at])
|
||||
|> validate_required([:name, :token, :created_by_id])
|
||||
|> validate_number(:uses_left, greater_than_or_equal_to: 0)
|
||||
end
|
||||
|
||||
@doc false
|
||||
@spec update_changeset(t() | new_invite(), attrs :: map()) :: changeset()
|
||||
def update_changeset(invite, attrs) do
|
||||
invite
|
||||
|> cast(attrs, [:name, :uses_left, :disabled_at])
|
||||
|> validate_required([:name])
|
||||
|> validate_number(:uses_left, greater_than_or_equal_to: 0)
|
||||
end
|
||||
end
|
198
lib/cannery/accounts/invites.ex
Normal file
198
lib/cannery/accounts/invites.ex
Normal file
@ -0,0 +1,198 @@
|
||||
defmodule Cannery.Accounts.Invites do
|
||||
@moduledoc """
|
||||
The Invites context.
|
||||
"""
|
||||
|
||||
import Ecto.Query, warn: false
|
||||
alias Ecto.Multi
|
||||
alias Cannery.Accounts.{Invite, User}
|
||||
alias Cannery.Repo
|
||||
|
||||
@invite_token_length 20
|
||||
|
||||
@doc """
|
||||
Returns the list of invites.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> list_invites(%User{id: 123, role: :admin})
|
||||
[%Invite{}, ...]
|
||||
|
||||
"""
|
||||
@spec list_invites(User.t()) :: [Invite.t()]
|
||||
def list_invites(%User{role: :admin}) do
|
||||
Repo.all(from i in Invite, order_by: i.name)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets a single invite for a user
|
||||
|
||||
Raises `Ecto.NoResultsError` if the Invite does not exist.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> get_invite!(123, %User{id: 123, role: :admin})
|
||||
%Invite{}
|
||||
|
||||
> get_invite!(456, %User{id: 123, role: :admin})
|
||||
** (Ecto.NoResultsError)
|
||||
|
||||
"""
|
||||
@spec get_invite!(Invite.id(), User.t()) :: Invite.t()
|
||||
def get_invite!(id, %User{role: :admin}) do
|
||||
Repo.get!(Invite, id)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns if an invite token is still valid
|
||||
|
||||
## Examples
|
||||
|
||||
iex> valid_invite_token?("valid_token")
|
||||
%Invite{}
|
||||
|
||||
iex> valid_invite_token?("invalid_token")
|
||||
nil
|
||||
"""
|
||||
@spec valid_invite_token?(Invite.token() | nil) :: boolean()
|
||||
def valid_invite_token?(token) when token in [nil, ""], do: false
|
||||
|
||||
def valid_invite_token?(token) do
|
||||
Repo.exists?(
|
||||
from i in Invite,
|
||||
where: i.token == ^token,
|
||||
where: i.disabled_at |> is_nil()
|
||||
)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Uses invite by decrementing uses_left, or marks invite invalid if it's been
|
||||
completely used.
|
||||
"""
|
||||
@spec use_invite(Invite.token()) :: {:ok, Invite.t()} | {:error, :invalid_token}
|
||||
def use_invite(invite_token) do
|
||||
Multi.new()
|
||||
|> Multi.run(:invite, fn _changes_so_far, _repo ->
|
||||
invite_token |> get_invite_by_token()
|
||||
end)
|
||||
|> Multi.update(:decrement_invite, fn %{invite: invite} ->
|
||||
decrement_invite_changeset(invite)
|
||||
end)
|
||||
|> Repo.transaction()
|
||||
|> case do
|
||||
{:ok, %{decrement_invite: invite}} -> {:ok, invite}
|
||||
{:error, :invite, :invalid_token, _changes_so_far} -> {:error, :invalid_token}
|
||||
end
|
||||
end
|
||||
|
||||
@spec get_invite_by_token(Invite.token() | nil) :: {:ok, Invite.t()} | {:error, :invalid_token}
|
||||
defp get_invite_by_token(token) when token in [nil, ""], do: {:error, :invalid_token}
|
||||
|
||||
defp get_invite_by_token(token) do
|
||||
Repo.one(
|
||||
from i in Invite,
|
||||
where: i.token == ^token,
|
||||
where: i.disabled_at |> is_nil()
|
||||
)
|
||||
|> case do
|
||||
nil -> {:error, :invalid_token}
|
||||
invite -> {:ok, invite}
|
||||
end
|
||||
end
|
||||
|
||||
@spec get_use_count(Invite.t(), User.t()) :: non_neg_integer()
|
||||
def get_use_count(%Invite{id: invite_id}, %User{role: :admin}) do
|
||||
Repo.one(
|
||||
from u in User,
|
||||
where: u.invite_id == ^invite_id,
|
||||
select: count(u.id)
|
||||
)
|
||||
end
|
||||
|
||||
@spec decrement_invite_changeset(Invite.t()) :: Invite.changeset()
|
||||
defp decrement_invite_changeset(%Invite{uses_left: nil} = invite) do
|
||||
invite |> Invite.update_changeset(%{})
|
||||
end
|
||||
|
||||
defp decrement_invite_changeset(%Invite{uses_left: 1} = invite) do
|
||||
now = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second)
|
||||
invite |> Invite.update_changeset(%{uses_left: 0, disabled_at: now})
|
||||
end
|
||||
|
||||
defp decrement_invite_changeset(%Invite{uses_left: uses_left} = invite) do
|
||||
invite |> Invite.update_changeset(%{uses_left: uses_left - 1})
|
||||
end
|
||||
|
||||
@doc """
|
||||
Creates a invite.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> create_invite(%User{id: 123, role: :admin}, %{field: value})
|
||||
{:ok, %Invite{}}
|
||||
|
||||
iex> create_invite(%User{id: 123, role: :admin}, %{field: bad_value})
|
||||
{:error, %Changeset{}}
|
||||
|
||||
"""
|
||||
@spec create_invite(User.t(), attrs :: map()) ::
|
||||
{:ok, Invite.t()} | {:error, Invite.changeset()}
|
||||
def create_invite(%User{role: :admin} = user, attrs) do
|
||||
token =
|
||||
:crypto.strong_rand_bytes(@invite_token_length)
|
||||
|> Base.url_encode64()
|
||||
|> binary_part(0, @invite_token_length)
|
||||
|
||||
Invite.create_changeset(user, token, attrs) |> Repo.insert()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Updates a invite.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> update_invite(invite, %{field: new_value}, %User{id: 123, role: :admin})
|
||||
{:ok, %Invite{}}
|
||||
|
||||
iex> update_invite(invite, %{field: bad_value}, %User{id: 123, role: :admin})
|
||||
{:error, %Changeset{}}
|
||||
|
||||
"""
|
||||
@spec update_invite(Invite.t(), attrs :: map(), User.t()) ::
|
||||
{:ok, Invite.t()} | {:error, Invite.changeset()}
|
||||
def update_invite(invite, attrs, %User{role: :admin}) do
|
||||
invite |> Invite.update_changeset(attrs) |> Repo.update()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deletes a invite.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> delete_invite(invite, %User{id: 123, role: :admin})
|
||||
{:ok, %Invite{}}
|
||||
|
||||
iex> delete_invite(invite, %User{id: 123, role: :admin})
|
||||
{:error, %Changeset{}}
|
||||
|
||||
"""
|
||||
@spec delete_invite(Invite.t(), User.t()) ::
|
||||
{:ok, Invite.t()} | {:error, Invite.changeset()}
|
||||
def delete_invite(invite, %User{role: :admin}) do
|
||||
invite |> Repo.delete()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deletes a invite.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> delete_invite(invite, %User{id: 123, role: :admin})
|
||||
%Invite{}
|
||||
|
||||
"""
|
||||
@spec delete_invite!(Invite.t(), User.t()) :: Invite.t()
|
||||
def delete_invite!(invite, %User{role: :admin}) do
|
||||
invite |> Repo.delete!()
|
||||
end
|
||||
end
|
214
lib/cannery/accounts/user.ex
Normal file
214
lib/cannery/accounts/user.ex
Normal file
@ -0,0 +1,214 @@
|
||||
defmodule Cannery.Accounts.User do
|
||||
@moduledoc """
|
||||
A Cannery user
|
||||
"""
|
||||
|
||||
use Ecto.Schema
|
||||
import Ecto.Changeset
|
||||
import CanneryWeb.Gettext
|
||||
alias Ecto.{Association, Changeset, UUID}
|
||||
alias Cannery.Accounts.{Invite, User}
|
||||
|
||||
@derive {Jason.Encoder,
|
||||
only: [
|
||||
:id,
|
||||
:email,
|
||||
:confirmed_at,
|
||||
:role,
|
||||
:locale,
|
||||
:inserted_at,
|
||||
:updated_at
|
||||
]}
|
||||
@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
|
||||
field :role, Ecto.Enum, values: [:admin, :user], default: :user
|
||||
field :locale, :string
|
||||
|
||||
has_many :created_invites, Invite, foreign_key: :created_by_id
|
||||
|
||||
belongs_to :invite, Invite
|
||||
|
||||
timestamps()
|
||||
end
|
||||
|
||||
@type t :: %User{
|
||||
id: id(),
|
||||
email: String.t(),
|
||||
password: String.t(),
|
||||
hashed_password: String.t(),
|
||||
confirmed_at: NaiveDateTime.t(),
|
||||
role: role(),
|
||||
locale: String.t() | nil,
|
||||
created_invites: [Invite.t()] | Association.NotLoaded.t(),
|
||||
invite: Invite.t() | nil | Association.NotLoaded.t(),
|
||||
invite_id: Invite.id() | nil,
|
||||
inserted_at: NaiveDateTime.t(),
|
||||
updated_at: NaiveDateTime.t()
|
||||
}
|
||||
@type new_user :: %User{}
|
||||
@type id :: UUID.t()
|
||||
@type changeset :: Changeset.t(t() | new_user())
|
||||
@type role :: :admin | :user
|
||||
|
||||
@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`.
|
||||
"""
|
||||
@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
|
||||
%User{}
|
||||
|> cast(attrs, [:email, :password, :locale])
|
||||
|> put_change(:invite_id, if(invite, do: invite.id))
|
||||
|> validate_email()
|
||||
|> validate_password(opts)
|
||||
end
|
||||
|
||||
@doc """
|
||||
A user changeset for role.
|
||||
"""
|
||||
@spec role_changeset(t() | new_user() | changeset(), role()) :: changeset()
|
||||
def role_changeset(user, role) do
|
||||
user |> change(role: role)
|
||||
end
|
||||
|
||||
@spec validate_email(changeset()) :: changeset()
|
||||
defp validate_email(changeset) do
|
||||
changeset
|
||||
|> validate_required([:email])
|
||||
|> validate_format(:email, ~r/^[^\s]+@[^\s]+$/,
|
||||
message: dgettext("errors", "must have the @ sign and no spaces")
|
||||
)
|
||||
|> validate_length(:email, max: 160)
|
||||
|> unsafe_validate_unique(:email, Cannery.Repo)
|
||||
|> unique_constraint(:email)
|
||||
end
|
||||
|
||||
@spec validate_password(changeset(), opts :: keyword()) ::
|
||||
changeset()
|
||||
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
|
||||
|
||||
@spec maybe_hash_password(changeset(), opts :: keyword()) :: changeset()
|
||||
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.
|
||||
"""
|
||||
@spec email_changeset(t(), attrs :: map()) :: changeset()
|
||||
def email_changeset(user, attrs) do
|
||||
user
|
||||
|> cast(attrs, [:email])
|
||||
|> validate_email()
|
||||
|> case do
|
||||
%{changes: %{email: _}} = changeset -> changeset
|
||||
%{} = changeset -> add_error(changeset, :email, dgettext("errors", "did not change"))
|
||||
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`.
|
||||
"""
|
||||
@spec password_changeset(t(), attrs :: map()) :: changeset()
|
||||
@spec password_changeset(t(), attrs :: map(), opts :: keyword()) :: changeset()
|
||||
def password_changeset(user, attrs, opts \\ []) do
|
||||
user
|
||||
|> cast(attrs, [:password])
|
||||
|> validate_confirmation(:password, message: dgettext("errors", "does not match password"))
|
||||
|> validate_password(opts)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Confirms the account by setting `confirmed_at`.
|
||||
"""
|
||||
@spec confirm_changeset(t() | changeset()) :: changeset()
|
||||
def confirm_changeset(user_or_changeset) do
|
||||
now = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second)
|
||||
user_or_changeset |> change(confirmed_at: now)
|
||||
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.
|
||||
"""
|
||||
@spec valid_password?(t(), String.t()) :: boolean()
|
||||
def valid_password?(%User{hashed_password: hashed_password}, password)
|
||||
when is_binary(hashed_password) and byte_size(password) > 0 do
|
||||
Bcrypt.verify_pass(password, hashed_password)
|
||||
end
|
||||
|
||||
def valid_password?(_invalid_user, _invalid_password) do
|
||||
Bcrypt.no_user_verify()
|
||||
false
|
||||
end
|
||||
|
||||
@doc """
|
||||
Validates the current password otherwise adds an error to the changeset.
|
||||
"""
|
||||
@spec validate_current_password(changeset(), String.t()) :: changeset()
|
||||
def validate_current_password(changeset, password) do
|
||||
if valid_password?(changeset.data, password),
|
||||
do: changeset,
|
||||
else: changeset |> add_error(:current_password, dgettext("errors", "is not valid"))
|
||||
end
|
||||
|
||||
@doc """
|
||||
A changeset for changing the user's locale
|
||||
"""
|
||||
@spec locale_changeset(t() | changeset(), locale :: String.t() | nil) :: changeset()
|
||||
def locale_changeset(user_or_changeset, locale) do
|
||||
user_or_changeset
|
||||
|> cast(%{"locale" => locale}, [:locale])
|
||||
|> validate_required(:locale)
|
||||
end
|
||||
end
|
77
lib/cannery/accounts/user_notifier.ex
Normal file
77
lib/cannery/accounts/user_notifier.ex
Normal file
@ -0,0 +1,77 @@
|
||||
defmodule Cannery.Accounts.UserNotifier do
|
||||
@moduledoc """
|
||||
Contains templates and messages for user messages
|
||||
"""
|
||||
|
||||
# For simplicity, this module simply logs messages to the terminal.
|
||||
# You should replace it by a proper email or notification tool, such as:
|
||||
#
|
||||
# * Swoosh - https://hexdocs.pm/swoosh
|
||||
# * Bamboo - https://hexdocs.pm/bamboo
|
||||
#
|
||||
defp deliver(to, body) do
|
||||
require Logger
|
||||
Logger.debug(body)
|
||||
{:ok, %{to: to, body: body}}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deliver instructions to confirm account.
|
||||
"""
|
||||
def deliver_confirmation_instructions(user, url) do
|
||||
deliver(user.email, """
|
||||
|
||||
==============================
|
||||
|
||||
Hi #{user.email},
|
||||
|
||||
You can confirm your account by visiting the URL below:
|
||||
|
||||
#{url}
|
||||
|
||||
If you didn't create an account with us, please ignore this.
|
||||
|
||||
==============================
|
||||
""")
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deliver instructions to reset a user password.
|
||||
"""
|
||||
def deliver_reset_password_instructions(user, url) do
|
||||
deliver(user.email, """
|
||||
|
||||
==============================
|
||||
|
||||
Hi #{user.email},
|
||||
|
||||
You can reset your password by visiting the URL below:
|
||||
|
||||
#{url}
|
||||
|
||||
If you didn't request this change, please ignore this.
|
||||
|
||||
==============================
|
||||
""")
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deliver instructions to update a user email.
|
||||
"""
|
||||
def deliver_update_email_instructions(user, url) do
|
||||
deliver(user.email, """
|
||||
|
||||
==============================
|
||||
|
||||
Hi #{user.email},
|
||||
|
||||
You can change your email by visiting the URL below:
|
||||
|
||||
#{url}
|
||||
|
||||
If you didn't request this change, please ignore this.
|
||||
|
||||
==============================
|
||||
""")
|
||||
end
|
||||
end
|
161
lib/cannery/accounts/user_token.ex
Normal file
161
lib/cannery/accounts/user_token.ex
Normal file
@ -0,0 +1,161 @@
|
||||
defmodule Cannery.Accounts.UserToken do
|
||||
@moduledoc """
|
||||
Schema for a user's session token
|
||||
"""
|
||||
|
||||
use Ecto.Schema
|
||||
import Ecto.Query
|
||||
alias Cannery.Accounts.User
|
||||
alias Ecto.{Association, UUID}
|
||||
|
||||
@hash_algorithm :sha256
|
||||
@rand_size 32
|
||||
|
||||
# It is very important to keep the reset password token expiry short,
|
||||
# since someone with access to the email may take over the account.
|
||||
@reset_password_validity_in_days 1
|
||||
@confirm_validity_in_days 7
|
||||
@change_email_validity_in_days 7
|
||||
@session_validity_in_days 60
|
||||
|
||||
@primary_key {:id, :binary_id, autogenerate: true}
|
||||
@foreign_key_type :binary_id
|
||||
schema "users_tokens" do
|
||||
field :token, :binary
|
||||
field :context, :string
|
||||
field :sent_to, :string
|
||||
|
||||
belongs_to :user, User
|
||||
|
||||
timestamps(updated_at: false)
|
||||
end
|
||||
|
||||
@type t :: %__MODULE__{
|
||||
id: id(),
|
||||
token: token(),
|
||||
context: String.t(),
|
||||
sent_to: String.t(),
|
||||
user: User.t() | Association.NotLoaded.t(),
|
||||
user_id: User.id() | nil,
|
||||
inserted_at: NaiveDateTime.t()
|
||||
}
|
||||
@type new_user_token :: %__MODULE__{}
|
||||
@type id :: UUID.t()
|
||||
@type token :: binary()
|
||||
|
||||
@doc """
|
||||
Generates a token that will be stored in a signed place,
|
||||
such as session or cookie. As they are signed, those
|
||||
tokens do not need to be hashed.
|
||||
"""
|
||||
def build_session_token(user) do
|
||||
token = :crypto.strong_rand_bytes(@rand_size)
|
||||
{token, %__MODULE__{token: token, context: "session", user_id: user.id}}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Checks if the token is valid and returns its underlying lookup query.
|
||||
|
||||
The query returns the user found by the token.
|
||||
"""
|
||||
def verify_session_token_query(token) do
|
||||
query =
|
||||
from token in token_and_context_query(token, "session"),
|
||||
join: user in assoc(token, :user),
|
||||
where: token.inserted_at > ago(@session_validity_in_days, "day"),
|
||||
select: user
|
||||
|
||||
{:ok, query}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Builds a token with a hashed counter part.
|
||||
|
||||
The non-hashed token is sent to the user email while the
|
||||
hashed part is stored in the database, to avoid reconstruction.
|
||||
The token is valid for a week as long as users don't change
|
||||
their email.
|
||||
"""
|
||||
def build_email_token(user, context) do
|
||||
build_hashed_token(user, context, user.email)
|
||||
end
|
||||
|
||||
defp build_hashed_token(user, context, sent_to) do
|
||||
token = :crypto.strong_rand_bytes(@rand_size)
|
||||
hashed_token = :crypto.hash(@hash_algorithm, token)
|
||||
|
||||
{Base.url_encode64(token, padding: false),
|
||||
%__MODULE__{
|
||||
token: hashed_token,
|
||||
context: context,
|
||||
sent_to: sent_to,
|
||||
user_id: user.id
|
||||
}}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Checks if the token is valid and returns its underlying lookup query.
|
||||
|
||||
The query returns the user found by the token.
|
||||
"""
|
||||
def verify_email_token_query(token, context) do
|
||||
case Base.url_decode64(token, padding: false) do
|
||||
{:ok, decoded_token} ->
|
||||
hashed_token = :crypto.hash(@hash_algorithm, decoded_token)
|
||||
days = days_for_context(context)
|
||||
|
||||
query =
|
||||
from token in token_and_context_query(hashed_token, context),
|
||||
join: user in assoc(token, :user),
|
||||
where: token.inserted_at > ago(^days, "day") and token.sent_to == user.email,
|
||||
select: user
|
||||
|
||||
{:ok, query}
|
||||
|
||||
:error ->
|
||||
:error
|
||||
end
|
||||
end
|
||||
|
||||
defp days_for_context("confirm"), do: @confirm_validity_in_days
|
||||
defp days_for_context("reset_password"), do: @reset_password_validity_in_days
|
||||
|
||||
@doc """
|
||||
Checks if the token is valid and returns its underlying lookup query.
|
||||
|
||||
The query returns the user token record.
|
||||
"""
|
||||
def verify_change_email_token_query(token, context) do
|
||||
case Base.url_decode64(token, padding: false) do
|
||||
{:ok, decoded_token} ->
|
||||
hashed_token = :crypto.hash(@hash_algorithm, decoded_token)
|
||||
|
||||
query =
|
||||
from token in token_and_context_query(hashed_token, context),
|
||||
where: token.inserted_at > ago(@change_email_validity_in_days, "day")
|
||||
|
||||
{:ok, query}
|
||||
|
||||
:error ->
|
||||
:error
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the given token with the given context.
|
||||
"""
|
||||
def token_and_context_query(token, context) do
|
||||
from __MODULE__, where: [token: ^token, context: ^context]
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets all tokens for the given user for the given contexts.
|
||||
"""
|
||||
def user_and_contexts_query(user, :all) do
|
||||
from t in __MODULE__, where: t.user_id == ^user.id
|
||||
end
|
||||
|
||||
def user_and_contexts_query(user, [_ | _] = contexts) do
|
||||
from t in __MODULE__, where: t.user_id == ^user.id and t.context in ^contexts
|
||||
end
|
||||
end
|
57
lib/cannery/application.ex
Normal file
57
lib/cannery/application.ex
Normal file
@ -0,0 +1,57 @@
|
||||
defmodule Cannery.Application do
|
||||
# See https://hexdocs.pm/elixir/Application.html
|
||||
# for more information on OTP Applications
|
||||
@moduledoc false
|
||||
|
||||
use Application
|
||||
alias Cannery.Logger
|
||||
|
||||
@impl true
|
||||
def start(_type, _args) do
|
||||
children = [
|
||||
# Start the Ecto repository
|
||||
Cannery.Repo,
|
||||
# Start the Telemetry supervisor
|
||||
CanneryWeb.Telemetry,
|
||||
# Start the PubSub system
|
||||
{Phoenix.PubSub, name: Cannery.PubSub},
|
||||
# Start the Endpoint (http/https)
|
||||
CanneryWeb.Endpoint,
|
||||
# Add Oban
|
||||
{Oban, oban_config()},
|
||||
Cannery.Repo.Migrator
|
||||
# Start a worker by calling: Cannery.Worker.start_link(arg)
|
||||
# {Cannery.Worker, arg}
|
||||
]
|
||||
|
||||
# Oban events logging https://hexdocs.pm/oban/Oban.html#module-reporting-errors
|
||||
:ok =
|
||||
:telemetry.attach_many(
|
||||
"oban-logger",
|
||||
[
|
||||
[:oban, :job, :exception],
|
||||
[:oban, :job, :start],
|
||||
[:oban, :job, :stop]
|
||||
],
|
||||
&Logger.handle_event/4,
|
||||
[]
|
||||
)
|
||||
|
||||
# See https://hexdocs.pm/elixir/Supervisor.html
|
||||
# for other strategies and supported options
|
||||
opts = [strategy: :one_for_one, name: Cannery.Supervisor]
|
||||
Supervisor.start_link(children, opts)
|
||||
end
|
||||
|
||||
# Tell Phoenix to update the endpoint configuration
|
||||
# whenever the application is updated.
|
||||
@impl true
|
||||
def config_change(changed, _new, removed) do
|
||||
CanneryWeb.Endpoint.config_change(changed, removed)
|
||||
:ok
|
||||
end
|
||||
|
||||
defp oban_config do
|
||||
Application.fetch_env!(:cannery, Oban)
|
||||
end
|
||||
end
|
63
lib/cannery/logger.ex
Normal file
63
lib/cannery/logger.ex
Normal file
@ -0,0 +1,63 @@
|
||||
defmodule Cannery.Logger do
|
||||
@moduledoc """
|
||||
Custom logger for telemetry events
|
||||
|
||||
Oban implementation taken from
|
||||
https://hexdocs.pm/oban/Oban.html#module-reporting-errors
|
||||
"""
|
||||
|
||||
require Logger
|
||||
|
||||
def handle_event([:oban, :job, :exception], measure, %{stacktrace: stacktrace} = meta, _config) do
|
||||
data =
|
||||
get_oban_job_data(meta, measure)
|
||||
|> Map.put(:stacktrace, Exception.format_stacktrace(stacktrace))
|
||||
|> pretty_encode()
|
||||
|
||||
Logger.error(meta.reason, data: data)
|
||||
end
|
||||
|
||||
def handle_event([:oban, :job, :start], measure, meta, _config) do
|
||||
data = get_oban_job_data(meta, measure) |> pretty_encode()
|
||||
Logger.info("Started oban job", data: data)
|
||||
end
|
||||
|
||||
def handle_event([:oban, :job, :stop], measure, meta, _config) do
|
||||
data = get_oban_job_data(meta, measure) |> pretty_encode()
|
||||
Logger.info("Finished oban job", data: data)
|
||||
end
|
||||
|
||||
def handle_event([:oban, :job, unhandled_event], measure, meta, _config) do
|
||||
data =
|
||||
get_oban_job_data(meta, measure)
|
||||
|> Map.put(:event, unhandled_event)
|
||||
|> pretty_encode()
|
||||
|
||||
Logger.warning("Unhandled oban job event", data: data)
|
||||
end
|
||||
|
||||
def handle_event(unhandled_event, measure, meta, config) do
|
||||
data =
|
||||
pretty_encode(%{
|
||||
event: unhandled_event,
|
||||
meta: meta,
|
||||
measurements: measure,
|
||||
config: config
|
||||
})
|
||||
|
||||
Logger.warning("Unhandled telemetry event", data: data)
|
||||
end
|
||||
|
||||
defp get_oban_job_data(%{job: job}, measure) do
|
||||
%{
|
||||
job: job |> Map.take([:id, :args, :meta, :queue, :worker]),
|
||||
measurements: measure
|
||||
}
|
||||
end
|
||||
|
||||
defp pretty_encode(data) do
|
||||
data
|
||||
|> Jason.encode!()
|
||||
|> Jason.Formatter.pretty_print()
|
||||
end
|
||||
end
|
42
lib/cannery/mailer.ex
Normal file
42
lib/cannery/mailer.ex
Normal file
@ -0,0 +1,42 @@
|
||||
defmodule Cannery.Mailer do
|
||||
@moduledoc """
|
||||
Mailer adapter for emails
|
||||
|
||||
Since emails are loaded as Oban jobs, the `:attrs` map must be serializable to
|
||||
json with Jason, which restricts the use of structs.
|
||||
"""
|
||||
|
||||
use Swoosh.Mailer, otp_app: :cannery
|
||||
alias Cannery.{Accounts.User, EmailWorker}
|
||||
alias Oban.Job
|
||||
|
||||
@doc """
|
||||
Deliver instructions to confirm account.
|
||||
"""
|
||||
@spec deliver_confirmation_instructions(User.t(), String.t()) :: Job.t()
|
||||
def deliver_confirmation_instructions(%User{id: user_id}, url) do
|
||||
%{email: :welcome, user_id: user_id, attrs: %{url: url}}
|
||||
|> EmailWorker.new()
|
||||
|> Oban.insert!()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deliver instructions to reset a user password.
|
||||
"""
|
||||
@spec deliver_reset_password_instructions(User.t(), String.t()) :: Job.t()
|
||||
def deliver_reset_password_instructions(%User{id: user_id}, url) do
|
||||
%{email: :reset_password, user_id: user_id, attrs: %{url: url}}
|
||||
|> EmailWorker.new()
|
||||
|> Oban.insert!()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deliver instructions to update a user email.
|
||||
"""
|
||||
@spec deliver_update_email_instructions(User.t(), String.t()) :: Job.t()
|
||||
def deliver_update_email_instructions(%User{id: user_id}, url) do
|
||||
%{email: :update_email, user_id: user_id, attrs: %{url: url}}
|
||||
|> EmailWorker.new()
|
||||
|> Oban.insert!()
|
||||
end
|
||||
end
|
27
lib/cannery/release.ex
Normal file
27
lib/cannery/release.ex
Normal file
@ -0,0 +1,27 @@
|
||||
defmodule Cannery.Release do
|
||||
@moduledoc """
|
||||
Contains mix tasks that can used in generated releases
|
||||
"""
|
||||
|
||||
@app :cannery
|
||||
|
||||
def rollback(repo, version) do
|
||||
load_app()
|
||||
|
||||
{:ok, _fun_return, _apps} =
|
||||
Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :down, to: version))
|
||||
end
|
||||
|
||||
defp load_app do
|
||||
Application.load(@app)
|
||||
end
|
||||
|
||||
def migrate do
|
||||
load_app()
|
||||
|
||||
for repo <- Application.fetch_env!(@app, :ecto_repos) do
|
||||
{:ok, _fun_return, _apps} =
|
||||
Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :up, all: true))
|
||||
end
|
||||
end
|
||||
end
|
5
lib/cannery/repo.ex
Normal file
5
lib/cannery/repo.ex
Normal file
@ -0,0 +1,5 @@
|
||||
defmodule Cannery.Repo do
|
||||
use Ecto.Repo,
|
||||
otp_app: :cannery,
|
||||
adapter: Ecto.Adapters.Postgres
|
||||
end
|
25
lib/cannery/repo/migrator.ex
Normal file
25
lib/cannery/repo/migrator.ex
Normal file
@ -0,0 +1,25 @@
|
||||
defmodule Cannery.Repo.Migrator do
|
||||
@moduledoc """
|
||||
Genserver to automatically perform all migration on app start
|
||||
"""
|
||||
|
||||
use GenServer
|
||||
require Logger
|
||||
|
||||
def start_link(_opts) do
|
||||
GenServer.start_link(__MODULE__, [], [])
|
||||
end
|
||||
|
||||
def init(_opts) do
|
||||
{:ok, if(automigrate_enabled?(), do: migrate!())}
|
||||
end
|
||||
|
||||
def migrate! do
|
||||
path = Application.app_dir(:cannery, "priv/repo/migrations")
|
||||
Ecto.Migrator.run(Cannery.Repo, path, :up, all: true)
|
||||
end
|
||||
|
||||
defp automigrate_enabled? do
|
||||
Application.get_env(:cannery, Cannery.Application, automigrate: false)[:automigrate]
|
||||
end
|
||||
end
|
Reference in New Issue
Block a user