After "mix phx.gen.auth Admins Admin admins" with added working register and login path.

This commit is contained in:
2026-02-20 13:09:55 +01:00
parent a47931f40e
commit 53d19a3a18
28 changed files with 2830 additions and 0 deletions

View File

@ -0,0 +1,328 @@
defmodule BeetRoundServer.Admins do
@moduledoc """
The Admins context.
"""
import Ecto.Query, warn: false
alias BeetRoundServer.Repo
alias BeetRoundServer.Admins.{Admin, AdminToken, AdminNotifier}
## Database getters
@doc """
Gets a admin by email.
## Examples
iex> get_admin_by_email("foo@example.com")
%Admin{}
iex> get_admin_by_email("unknown@example.com")
nil
"""
def get_admin_by_email(email) when is_binary(email) do
Repo.get_by(Admin, email: email)
end
@doc """
Gets a admin by email and password.
## Examples
iex> get_admin_by_email_and_password("foo@example.com", "correct_password")
%Admin{}
iex> get_admin_by_email_and_password("foo@example.com", "invalid_password")
nil
"""
def get_admin_by_email_and_password(email, password)
when is_binary(email) and is_binary(password) do
admin = Repo.get_by(Admin, email: email)
if Admin.valid_password?(admin, password), do: admin
end
@doc """
Gets a single admin.
Raises `Ecto.NoResultsError` if the Admin does not exist.
## Examples
iex> get_admin!(123)
%Admin{}
iex> get_admin!(456)
** (Ecto.NoResultsError)
"""
def get_admin!(id), do: Repo.get!(Admin, id)
## Admin registration
@doc """
Registers a admin.
## Examples
iex> register_admin(%{field: value})
{:ok, %Admin{}}
iex> register_admin(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def register_admin(attrs) do
%Admin{}
|> Admin.email_changeset(attrs)
|> Admin.password_changeset(attrs)
|> Repo.insert()
end
## Settings
@doc """
Checks whether the admin is in sudo mode.
The admin is in sudo mode when the last authentication was done no further
than 20 minutes ago. The limit can be given as second argument in minutes.
"""
def sudo_mode?(admin, minutes \\ -20)
def sudo_mode?(%Admin{authenticated_at: ts}, minutes) when is_struct(ts, DateTime) do
DateTime.after?(ts, DateTime.utc_now() |> DateTime.add(minutes, :minute))
end
def sudo_mode?(_admin, _minutes), do: false
@doc """
Returns an `%Ecto.Changeset{}` for changing the admin email.
See `BeetRoundServer.Admins.Admin.email_changeset/3` for a list of supported options.
## Examples
iex> change_admin_email(admin)
%Ecto.Changeset{data: %Admin{}}
"""
def change_admin_email(admin, attrs \\ %{}, opts \\ []) do
Admin.email_changeset(admin, attrs, opts)
end
@doc """
Updates the admin email using the given token.
If the token matches, the admin email is updated and the token is deleted.
"""
def update_admin_email(admin, token) do
context = "change:#{admin.email}"
Repo.transact(fn ->
with {:ok, query} <- AdminToken.verify_change_email_token_query(token, context),
%AdminToken{sent_to: email} <- Repo.one(query),
{:ok, admin} <- Repo.update(Admin.email_changeset(admin, %{email: email})),
{_count, _result} <-
Repo.delete_all(from(AdminToken, where: [admin_id: ^admin.id, context: ^context])) do
{:ok, admin}
else
_ -> {:error, :transaction_aborted}
end
end)
end
@doc """
Returns an `%Ecto.Changeset{}` for changing the admin password.
See `BeetRoundServer.Admins.Admin.password_changeset/3` for a list of supported options.
## Examples
iex> change_admin_password(admin)
%Ecto.Changeset{data: %Admin{}}
"""
def change_admin_password(admin, attrs \\ %{}, opts \\ []) do
Admin.password_changeset(admin, attrs, opts)
end
@doc """
Updates the admin password.
Returns a tuple with the updated admin, as well as a list of expired tokens.
## Examples
iex> update_admin_password(admin, %{password: ...})
{:ok, {%Admin{}, [...]}}
iex> update_admin_password(admin, %{password: "too short"})
{:error, %Ecto.Changeset{}}
"""
def update_admin_password(admin, attrs) do
admin
|> Admin.password_changeset(attrs)
|> update_admin_and_delete_all_tokens()
end
## Session
@doc """
Generates a session token.
"""
def generate_admin_session_token(admin) do
{token, admin_token} = AdminToken.build_session_token(admin)
Repo.insert!(admin_token)
token
end
@doc """
Gets the admin with the given signed token.
If the token is valid `{admin, token_inserted_at}` is returned, otherwise `nil` is returned.
"""
def get_admin_by_session_token(token) do
{:ok, query} = AdminToken.verify_session_token_query(token)
Repo.one(query)
end
@doc """
Gets the admin with the given magic link token.
"""
def get_admin_by_magic_link_token(token) do
with {:ok, query} <- AdminToken.verify_magic_link_token_query(token),
{admin, _token} <- Repo.one(query) do
admin
else
_ -> nil
end
end
@doc """
Logs the admin in by magic link.
There are three cases to consider:
1. The admin has already confirmed their email. They are logged in
and the magic link is expired.
2. The admin has not confirmed their email and no password is set.
In this case, the admin gets confirmed, logged in, and all tokens -
including session ones - are expired. In theory, no other tokens
exist but we delete all of them for best security practices.
3. The admin has not confirmed their email but a password is set.
This cannot happen in the default implementation but may be the
source of security pitfalls. See the "Mixing magic link and password registration" section of
`mix help phx.gen.auth`.
"""
def login_admin_by_magic_link(token) do
{:ok, query} = AdminToken.verify_magic_link_token_query(token)
case Repo.one(query) do
# Prevent session fixation attacks by disallowing magic links for unconfirmed users with password
{%Admin{confirmed_at: nil, hashed_password: hash}, _token} when not is_nil(hash) ->
raise """
magic link log in is not allowed for unconfirmed users with a password set!
This cannot happen with the default implementation, which indicates that you
might have adapted the code to a different use case. Please make sure to read the
"Mixing magic link and password registration" section of `mix help phx.gen.auth`.
"""
{%Admin{confirmed_at: nil} = admin, _token} ->
admin
|> Admin.confirm_changeset()
|> update_admin_and_delete_all_tokens()
{admin, token} ->
Repo.delete!(token)
{:ok, {admin, []}}
nil ->
{:error, :not_found}
end
end
@doc ~S"""
Delivers the update email instructions to the given admin.
## Examples
iex> deliver_admin_update_email_instructions(admin, current_email, &url(~p"/admins/settings/confirm-email/#{&1}"))
{:ok, %{to: ..., body: ...}}
"""
def deliver_admin_update_email_instructions(
%Admin{} = admin,
current_email,
update_email_url_fun
)
when is_function(update_email_url_fun, 1) do
{encoded_token, admin_token} = AdminToken.build_email_token(admin, "change:#{current_email}")
Repo.insert!(admin_token)
AdminNotifier.deliver_update_email_instructions(admin, update_email_url_fun.(encoded_token))
end
@doc """
Delivers the magic link login instructions to the given admin.
"""
def deliver_login_instructions(%Admin{} = admin, magic_link_url_fun)
when is_function(magic_link_url_fun, 1) do
{encoded_token, admin_token} = AdminToken.build_email_token(admin, "login")
Repo.insert!(admin_token)
AdminNotifier.deliver_login_instructions(admin, magic_link_url_fun.(encoded_token))
end
@doc """
Deletes the signed token with the given context.
"""
def delete_admin_session_token(token) do
Repo.delete_all(from(AdminToken, where: [token: ^token, context: "session"]))
:ok
end
@doc """
Creates a new api token for an admin.
The token returned must be saved somewhere safe.
This token cannot be recovered from the database.
"""
def create_admin_api_token(admin) do
{encoded_token, admin_token} = AdminToken.build_email_token(admin, "api-token")
Repo.insert!(admin_token)
encoded_token
end
@doc """
Fetches the admin by API token.
"""
def fetch_admin_by_api_token(token) do
with {:ok, query} <- AdminToken.verify_email_token_query(token, "api-token"),
%Admin{} = admin <- Repo.one(query) do
{:ok, admin}
else
_ -> :error
end
end
## Token helper
defp update_admin_and_delete_all_tokens(changeset) do
Repo.transact(fn ->
with {:ok, admin} <- Repo.update(changeset) do
tokens_to_expire = Repo.all_by(AdminToken, admin_id: admin.id)
Repo.delete_all(
from(t in AdminToken, where: t.id in ^Enum.map(tokens_to_expire, & &1.id))
)
{:ok, {admin, tokens_to_expire}}
end
end)
end
end

View File

@ -0,0 +1,134 @@
defmodule BeetRoundServer.Admins.Admin do
use Ecto.Schema
import Ecto.Changeset
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "admins" do
field :email, :string
field :password, :string, virtual: true, redact: true
field :hashed_password, :string, redact: true
field :confirmed_at, :utc_datetime
field :authenticated_at, :utc_datetime, virtual: true
timestamps(type: :utc_datetime)
end
@doc """
A admin changeset for registering or changing the email.
It requires the email to change otherwise an error is added.
## Options
* `:validate_unique` - Set to false if you don't want to validate the
uniqueness of the email, useful when displaying live validations.
Defaults to `true`.
"""
def email_changeset(admin, attrs, opts \\ []) do
admin
|> cast(attrs, [:email])
|> validate_email(opts)
end
defp validate_email(changeset, opts) do
changeset =
changeset
|> validate_required([:email])
|> validate_format(:email, ~r/^[^@,;\s]+@[^@,;\s]+$/,
message: "must have the @ sign and no spaces"
)
|> validate_length(:email, max: 160)
if Keyword.get(opts, :validate_unique, true) do
changeset
|> unsafe_validate_unique(:email, BeetRoundServer.Repo)
|> unique_constraint(:email)
|> validate_email_changed()
else
changeset
end
end
defp validate_email_changed(changeset) do
if get_field(changeset, :email) && get_change(changeset, :email) == nil do
add_error(changeset, :email, "did not change")
else
changeset
end
end
@doc """
A admin changeset for changing the password.
It is important to validate the length of the password, as long passwords may
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`.
"""
def password_changeset(admin, attrs, opts \\ []) do
admin
|> cast(attrs, [:password])
|> validate_confirmation(:password, message: "does not match password")
|> validate_password(opts)
end
defp validate_password(changeset, opts) do
changeset
|> validate_required([:password])
|> validate_length(:password, min: 12, max: 72)
# Examples of additional password validation:
# |> 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
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
# If using Bcrypt, then further validate it is at most 72 bytes long
|> validate_length(:password, max: 72, count: :bytes)
# Hashing could be done with `Ecto.Changeset.prepare_changes/2`, but that
# would keep the database transaction open longer and hurt performance.
|> put_change(:hashed_password, Bcrypt.hash_pwd_salt(password))
|> delete_change(:password)
else
changeset
end
end
@doc """
Confirms the account by setting `confirmed_at`.
"""
def confirm_changeset(admin) do
now = DateTime.utc_now(:second)
change(admin, confirmed_at: now)
end
@doc """
Verifies the password.
If there is no admin or the admin doesn't have a password, we call
`Bcrypt.no_user_verify/0` to avoid timing attacks.
"""
def valid_password?(%BeetRoundServer.Admins.Admin{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?(_, _) do
Bcrypt.no_user_verify()
false
end
end

View File

@ -0,0 +1,84 @@
defmodule BeetRoundServer.Admins.AdminNotifier do
import Swoosh.Email
alias BeetRoundServer.Mailer
alias BeetRoundServer.Admins.Admin
# Delivers the email using the application mailer.
defp deliver(recipient, subject, body) do
email =
new()
|> to(recipient)
|> from({"BeetRoundServer", "contact@example.com"})
|> subject(subject)
|> text_body(body)
with {:ok, _metadata} <- Mailer.deliver(email) do
{:ok, email}
end
end
@doc """
Deliver instructions to update a admin email.
"""
def deliver_update_email_instructions(admin, url) do
deliver(admin.email, "Update email instructions", """
==============================
Hi #{admin.email},
You can change your email by visiting the URL below:
#{url}
If you didn't request this change, please ignore this.
==============================
""")
end
@doc """
Deliver instructions to log in with a magic link.
"""
def deliver_login_instructions(admin, url) do
case admin do
%Admin{confirmed_at: nil} -> deliver_confirmation_instructions(admin, url)
_ -> deliver_magic_link_instructions(admin, url)
end
end
defp deliver_magic_link_instructions(admin, url) do
deliver(admin.email, "Log in instructions", """
==============================
Hi #{admin.email},
You can log into your account by visiting the URL below:
#{url}
If you didn't request this email, please ignore this.
==============================
""")
end
defp deliver_confirmation_instructions(admin, url) do
deliver(admin.email, "Confirmation instructions", """
==============================
Hi #{admin.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
end

View File

@ -0,0 +1,195 @@
defmodule BeetRoundServer.Admins.AdminToken do
use Ecto.Schema
import Ecto.Query
alias BeetRoundServer.Admins.AdminToken
@hash_algorithm :sha256
@rand_size 32
# It is very important to keep the magic link token expiry short,
# since someone with access to the email may take over the account.
@magic_link_validity_in_minutes 15
@change_email_validity_in_days 7
@session_validity_in_days 14
@api_validity_in_days 30
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "admins_tokens" do
field :token, :binary
field :context, :string
field :sent_to, :string
field :authenticated_at, :utc_datetime
belongs_to :admin, BeetRoundServer.Admins.Admin
timestamps(type: :utc_datetime, updated_at: false)
end
@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.
The reason why we store session tokens in the database, even
though Phoenix already provides a session cookie, is because
Phoenix's default session cookies are not persisted, they are
simply signed and potentially encrypted. This means they are
valid indefinitely, unless you change the signing/encryption
salt.
Therefore, storing them allows individual admin
sessions to be expired. The token system can also be extended
to store additional data, such as the device used for logging in.
You could then use this information to display all valid sessions
and devices in the UI and allow users to explicitly expire any
session they deem invalid.
"""
def build_session_token(admin) do
token = :crypto.strong_rand_bytes(@rand_size)
dt = admin.authenticated_at || DateTime.utc_now(:second)
{token,
%AdminToken{token: token, context: "session", admin_id: admin.id, authenticated_at: dt}}
end
@doc """
Checks if the token is valid and returns its underlying lookup query.
The query returns the admin found by the token, if any, along with the token's creation time.
The token is valid if it matches the value in the database and it has
not expired (after @session_validity_in_days).
"""
def verify_session_token_query(token) do
query =
from token in by_token_and_context_query(token, "session"),
join: admin in assoc(token, :admin),
where: token.inserted_at > ago(@session_validity_in_days, "day"),
select: {%{admin | authenticated_at: token.authenticated_at}, token.inserted_at}
{:ok, query}
end
@doc """
Builds a token and its hash to be delivered to the admin's email.
The non-hashed token is sent to the admin email while the
hashed part is stored in the database. The original token cannot be reconstructed,
which means anyone with read-only access to the database cannot directly use
the token in the application to gain access. Furthermore, if the admin changes
their email in the system, the tokens sent to the previous email are no longer
valid.
Users can easily adapt the existing code to provide other types of delivery methods,
for example, by phone numbers.
"""
def build_email_token(admin, context) do
build_hashed_token(admin, context, admin.email)
end
defp build_hashed_token(admin, context, sent_to) do
token = :crypto.strong_rand_bytes(@rand_size)
hashed_token = :crypto.hash(@hash_algorithm, token)
{Base.url_encode64(token, padding: false),
%AdminToken{
token: hashed_token,
context: context,
sent_to: sent_to,
admin_id: admin.id
}}
end
@doc """
Checks if the token is valid and returns its underlying lookup query.
If found, the query returns a tuple of the form `{admin, token}`.
The given token is valid if it matches its hashed counterpart in the
database. This function also checks if the token is being used within
15 minutes. The context of a magic link token is always "login".
"""
def verify_magic_link_token_query(token) do
case Base.url_decode64(token, padding: false) do
{:ok, decoded_token} ->
hashed_token = :crypto.hash(@hash_algorithm, decoded_token)
query =
from token in by_token_and_context_query(hashed_token, "login"),
join: admin in assoc(token, :admin),
where: token.inserted_at > ago(^@magic_link_validity_in_minutes, "minute"),
where: token.sent_to == admin.email,
select: {admin, token}
{:ok, query}
:error ->
:error
end
end
@doc """
Checks if the token is valid and returns its underlying lookup query.
The query returns the admin_token found by the token, if any.
This is used to validate requests to change the admin
email.
The given token is valid if it matches its hashed counterpart in the
database and if it has not expired (after @change_email_validity_in_days).
The context must always start with "change:".
"""
def verify_change_email_token_query(token, "change:" <> _ = 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 by_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 """
Checks if the token is valid and returns its underlying lookup query.
The query returns the admin found by the token, if any.
The given token is valid if it matches its hashed counterpart in the
database and the user email has not changed. This function also checks
if the token is being used within a certain period, depending on the
context. The default contexts supported by this function are either
"confirm", for account confirmation emails, and "reset_password",
for resetting the password. For verifying requests to change the email,
see `verify_change_email_token_query/2`.
"""
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 by_token_and_context_query(hashed_token, context),
join: admin in assoc(token, :admin),
where: token.inserted_at > ago(^days, "day") and token.sent_to == admin.email,
select: admin
{:ok, query}
:error ->
:error
end
end
defp days_for_context("api-token"), do: @api_validity_in_days
defp by_token_and_context_query(token, context) do
from AdminToken, where: [token: ^token, context: ^context]
end
end

View File

@ -0,0 +1,33 @@
defmodule BeetRoundServer.Admins.Scope do
@moduledoc """
Defines the scope of the caller to be used throughout the app.
The `BeetRoundServer.Admins.Scope` allows public interfaces to receive
information about the caller, such as if the call is initiated from an
end-user, and if so, which user. Additionally, such a scope can carry fields
such as "super user" or other privileges for use as authorization, or to
ensure specific code paths can only be access for a given scope.
It is useful for logging as well as for scoping pubsub subscriptions and
broadcasts when a caller subscribes to an interface or performs a particular
action.
Feel free to extend the fields on this struct to fit the needs of
growing application requirements.
"""
alias BeetRoundServer.Admins.Admin
defstruct admin: nil
@doc """
Creates a scope for the given admin.
Returns nil if no admin is given.
"""
def for_admin(%Admin{} = admin) do
%__MODULE__{admin: admin}
end
def for_admin(nil), do: nil
end

View File

@ -0,0 +1,219 @@
defmodule BeetRoundServerWeb.AdminAuth do
use BeetRoundServerWeb, :verified_routes
import Plug.Conn
import Phoenix.Controller
alias BeetRoundServer.Admins
alias BeetRoundServer.Admins.Scope
# Make the remember me cookie valid for 14 days. This should match
# the session validity setting in AdminToken.
@max_cookie_age_in_days 14
@remember_me_cookie "_beet_round_server_web_admin_remember_me"
@remember_me_options [
sign: true,
max_age: @max_cookie_age_in_days * 24 * 60 * 60,
same_site: "Lax"
]
# How old the session token should be before a new one is issued. When a request is made
# with a session token older than this value, then a new session token will be created
# and the session and remember-me cookies (if set) will be updated with the new token.
# Lowering this value will result in more tokens being created by active users. Increasing
# it will result in less time before a session token expires for a user to get issued a new
# token. This can be set to a value greater than `@max_cookie_age_in_days` to disable
# the reissuing of tokens completely.
@session_reissue_age_in_days 7
@doc """
Logs the admin in.
Redirects to the session's `:admin_return_to` path
or falls back to the `signed_in_path/1`.
"""
def log_in_admin(conn, admin, params \\ %{}) do
admin_return_to = get_session(conn, :admin_return_to)
conn
|> create_or_extend_session(admin, params)
|> redirect(to: admin_return_to || signed_in_path(conn))
end
@doc """
Logs the admin out.
It clears all session data for safety. See renew_session.
"""
def log_out_admin(conn) do
admin_token = get_session(conn, :admin_token)
admin_token && Admins.delete_admin_session_token(admin_token)
if live_socket_id = get_session(conn, :live_socket_id) do
BeetRoundServerWeb.Endpoint.broadcast(live_socket_id, "disconnect", %{})
end
conn
|> renew_session(nil)
|> delete_resp_cookie(@remember_me_cookie)
|> redirect(to: ~p"/")
end
@doc """
Authenticates the admin by looking into the session and remember me token.
Will reissue the session token if it is older than the configured age.
"""
def fetch_current_scope_for_admin(conn, _opts) do
with {token, conn} <- ensure_admin_token(conn),
{admin, token_inserted_at} <- Admins.get_admin_by_session_token(token) do
conn
|> assign(:current_scope, Scope.for_admin(admin))
|> maybe_reissue_admin_session_token(admin, token_inserted_at)
else
nil -> assign(conn, :current_scope, Scope.for_admin(nil))
end
end
defp ensure_admin_token(conn) do
if token = get_session(conn, :admin_token) do
{token, conn}
else
conn = fetch_cookies(conn, signed: [@remember_me_cookie])
if token = conn.cookies[@remember_me_cookie] do
{token, conn |> put_token_in_session(token) |> put_session(:admin_remember_me, true)}
else
nil
end
end
end
# Reissue the session token if it is older than the configured reissue age.
defp maybe_reissue_admin_session_token(conn, admin, token_inserted_at) do
token_age = DateTime.diff(DateTime.utc_now(:second), token_inserted_at, :day)
if token_age >= @session_reissue_age_in_days do
create_or_extend_session(conn, admin, %{})
else
conn
end
end
# This function is the one responsible for creating session tokens
# and storing them safely in the session and cookies. It may be called
# either when logging in, during sudo mode, or to renew a session which
# will soon expire.
#
# When the session is created, rather than extended, the renew_session
# function will clear the session to avoid fixation attacks. See the
# renew_session function to customize this behaviour.
defp create_or_extend_session(conn, admin, params) do
token = Admins.generate_admin_session_token(admin)
remember_me = get_session(conn, :admin_remember_me)
conn
|> renew_session(admin)
|> put_token_in_session(token)
|> maybe_write_remember_me_cookie(token, params, remember_me)
end
# Do not renew session if the admin is already logged in
# to prevent CSRF errors or data being lost in tabs that are still open
defp renew_session(conn, admin) when conn.assigns.current_scope.admin.id == admin.id do
conn
end
# This function renews the session ID and erases the whole
# session to avoid fixation attacks. If there is any data
# in the session you may want to preserve after log in/log out,
# you must explicitly fetch the session data before clearing
# and then immediately set it after clearing, for example:
#
# defp renew_session(conn, _admin) do
# delete_csrf_token()
# preferred_locale = get_session(conn, :preferred_locale)
#
# conn
# |> configure_session(renew: true)
# |> clear_session()
# |> put_session(:preferred_locale, preferred_locale)
# end
#
defp renew_session(conn, _admin) do
delete_csrf_token()
conn
|> configure_session(renew: true)
|> clear_session()
end
defp maybe_write_remember_me_cookie(conn, token, %{"remember_me" => "true"}, _),
do: write_remember_me_cookie(conn, token)
defp maybe_write_remember_me_cookie(conn, token, _params, true),
do: write_remember_me_cookie(conn, token)
defp maybe_write_remember_me_cookie(conn, _token, _params, _), do: conn
defp write_remember_me_cookie(conn, token) do
conn
|> put_session(:admin_remember_me, true)
|> put_resp_cookie(@remember_me_cookie, token, @remember_me_options)
end
defp put_token_in_session(conn, token) do
put_session(conn, :admin_token, token)
end
@doc """
Plug for routes that require sudo mode.
"""
def require_sudo_mode(conn, _opts) do
if Admins.sudo_mode?(conn.assigns.current_scope.admin, -10) do
conn
else
conn
|> put_flash(:error, "You must re-authenticate to access this page.")
|> maybe_store_return_to()
|> redirect(to: ~p"/admins/log-in")
|> halt()
end
end
@doc """
Plug for routes that require the admin to not be authenticated.
"""
def redirect_if_admin_is_authenticated(conn, _opts) do
if conn.assigns.current_scope do
conn
|> redirect(to: signed_in_path(conn))
|> halt()
else
conn
end
end
defp signed_in_path(_conn), do: ~p"/"
@doc """
Plug for routes that require the admin to be authenticated.
"""
def require_authenticated_admin(conn, _opts) do
if conn.assigns.current_scope && conn.assigns.current_scope.admin do
conn
else
conn
|> put_flash(:error, "You must log in to access this page.")
|> maybe_store_return_to()
|> redirect(to: ~p"/admins/log-in")
|> halt()
end
end
defp maybe_store_return_to(%{method: "GET"} = conn) do
put_session(conn, :admin_return_to, current_path(conn))
end
defp maybe_store_return_to(conn), do: conn
end

View File

@ -0,0 +1,56 @@
defmodule BeetRoundServerWeb.AdminController do
use BeetRoundServerWeb, :controller
alias BeetRoundServer.Admins
alias BeetRoundServer.Admins.Admin
action_fallback BeetRoundServerWeb.FallbackController
def create(conn, %{"admin" => admin_params}) do
with {:ok, %Admin{} = admin} <- Admins.register_admin(admin_params) do
conn
|> put_status(:created)
|> render(:show, admin: admin)
else
{:error, _changeset} ->
existingAdmin = Admins.get_admin_by_email(admin_params["email"])
if existingAdmin == nil do
conn
|> put_status(:bad_request)
|> render(:error, %{error: "Admin could not be created!", admin: admin_params})
else
admin = %{
mail: existingAdmin.email,
id: existingAdmin.id
}
conn
|> put_status(:conflict)
|> render(:error, %{error: "Admin already exists!", admin: admin})
end
end
end
def show(conn, %{"id" => id}) do
admin = Admins.get_admin!(id)
render(conn, :show, admin: admin)
end
def log_in(conn, %{"admin" => admin_params}) do
case Admins.get_admin_by_email_and_password(admin_params["email"], admin_params["password"]) do
nil ->
IO.puts("Admin couldn't be found!")
conn
|> put_status(:forbidden)
|> render(:error, %{error: "Invalid email or password!", admin: admin_params})
admin ->
encoded_token = Admins.create_admin_api_token(admin)
updated_admin = Map.put(admin, :token, encoded_token)
render(conn, :token, admin: updated_admin)
end
end
end

View File

@ -0,0 +1,47 @@
defmodule BeetRoundServerWeb.AdminJSON do
alias BeetRoundServer.Admins.Admin
@doc """
Renders a list of admins.
"""
def index(%{admins: admins}) do
%{data: for(admin <- admins, do: data(admin))}
end
@doc """
Renders a single admin.
"""
def show(%{admin: admin}) do
%{
data: data(admin)
}
end
def token(%{admin: admin}) do
%{
data: %{
id: admin.id,
email: admin.email,
token: admin.token
}
}
end
def mail_status(%{status: status}) do
%{data: status}
end
def error(%{error: error, admin: admin}) do
%{
error: error,
admin: admin
}
end
defp data(%Admin{} = admin) do
%{
id: admin.id,
email: admin.email
}
end
end

View File

@ -0,0 +1,32 @@
defmodule BeetRoundServerWeb.AdminRegistrationController do
use BeetRoundServerWeb, :controller
alias BeetRoundServer.Admins
alias BeetRoundServer.Admins.Admin
def new(conn, _params) do
changeset = Admins.change_admin_email(%Admin{})
render(conn, :new, changeset: changeset)
end
def create(conn, %{"admin" => admin_params}) do
case Admins.register_admin(admin_params) do
{:ok, admin} ->
{:ok, _} =
Admins.deliver_login_instructions(
admin,
&url(~p"/admins/log-in/#{&1}")
)
conn
|> put_flash(
:info,
"An email was sent to #{admin.email}, please access it to confirm your account."
)
|> redirect(to: ~p"/admins/log-in")
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, :new, changeset: changeset)
end
end
end

View File

@ -0,0 +1,5 @@
defmodule BeetRoundServerWeb.AdminRegistrationHTML do
use BeetRoundServerWeb, :html
embed_templates "admin_registration_html/*"
end

View File

@ -0,0 +1,31 @@
<Layouts.app flash={@flash} current_scope={@current_scope}>
<div class="mx-auto max-w-sm">
<div class="text-center">
<.header>
Register for an account
<:subtitle>
Already registered?
<.link navigate={~p"/admins/log-in"} class="font-semibold text-brand hover:underline">
Log in
</.link>
to your account now.
</:subtitle>
</.header>
</div>
<.form :let={f} for={@changeset} action={~p"/admins/register"}>
<.input
field={f[:email]}
type="email"
label="Email"
autocomplete="email"
required
phx-mounted={JS.focus()}
/>
<.button phx-disable-with="Creating account..." class="btn btn-primary w-full">
Create an account
</.button>
</.form>
</div>
</Layouts.app>

View File

@ -0,0 +1,88 @@
defmodule BeetRoundServerWeb.AdminSessionController do
use BeetRoundServerWeb, :controller
alias BeetRoundServer.Admins
alias BeetRoundServerWeb.AdminAuth
def new(conn, _params) do
email = get_in(conn.assigns, [:current_scope, Access.key(:admin), Access.key(:email)])
form = Phoenix.Component.to_form(%{"email" => email}, as: "admin")
render(conn, :new, form: form)
end
# magic link login
def create(conn, %{"admin" => %{"token" => token} = admin_params} = params) do
info =
case params do
%{"_action" => "confirmed"} -> "Admin confirmed successfully."
_ -> "Welcome back!"
end
case Admins.login_admin_by_magic_link(token) do
{:ok, {admin, _expired_tokens}} ->
conn
|> put_flash(:info, info)
|> AdminAuth.log_in_admin(admin, admin_params)
{:error, :not_found} ->
conn
|> put_flash(:error, "The link is invalid or it has expired.")
|> render(:new, form: Phoenix.Component.to_form(%{}, as: "admin"))
end
end
# email + password login
def create(conn, %{"admin" => %{"email" => email, "password" => password} = admin_params}) do
if admin = Admins.get_admin_by_email_and_password(email, password) do
conn
|> put_flash(:info, "Welcome back!")
|> AdminAuth.log_in_admin(admin, admin_params)
else
form = Phoenix.Component.to_form(admin_params, as: "admin")
# In order to prevent user enumeration attacks, don't disclose whether the email is registered.
conn
|> put_flash(:error, "Invalid email or password")
|> render(:new, form: form)
end
end
# magic link request
def create(conn, %{"admin" => %{"email" => email}}) do
if admin = Admins.get_admin_by_email(email) do
Admins.deliver_login_instructions(
admin,
&url(~p"/admins/log-in/#{&1}")
)
end
info =
"If your email is in our system, you will receive instructions for logging in shortly."
conn
|> put_flash(:info, info)
|> redirect(to: ~p"/admins/log-in")
end
def confirm(conn, %{"token" => token}) do
if admin = Admins.get_admin_by_magic_link_token(token) do
form = Phoenix.Component.to_form(%{"token" => token}, as: "admin")
conn
|> assign(:admin, admin)
|> assign(:form, form)
|> render(:confirm)
else
conn
|> put_flash(:error, "Magic link is invalid or it has expired.")
|> redirect(to: ~p"/admins/log-in")
end
end
def delete(conn, _params) do
conn
|> put_flash(:info, "Logged out successfully.")
|> AdminAuth.log_out_admin()
end
end

View File

@ -0,0 +1,9 @@
defmodule BeetRoundServerWeb.AdminSessionHTML do
use BeetRoundServerWeb, :html
embed_templates "admin_session_html/*"
defp local_mail_adapter? do
Application.get_env(:beet_round_server, BeetRoundServer.Mailer)[:adapter] == Swoosh.Adapters.Local
end
end

View File

@ -0,0 +1,59 @@
<Layouts.app flash={@flash} current_scope={@current_scope}>
<div class="mx-auto max-w-sm">
<div class="text-center">
<.header>Welcome {@admin.email}</.header>
</div>
<.form
:if={!@admin.confirmed_at}
for={@form}
id="confirmation_form"
action={~p"/admins/log-in?_action=confirmed"}
phx-mounted={JS.focus_first()}
>
<input type="hidden" name={@form[:token].name} value={@form[:token].value} />
<.button
name={@form[:remember_me].name}
value="true"
phx-disable-with="Confirming..."
class="btn btn-primary w-full"
>
Confirm and stay logged in
</.button>
<.button phx-disable-with="Confirming..." class="btn btn-primary btn-soft w-full mt-2">
Confirm and log in only this time
</.button>
</.form>
<.form
:if={@admin.confirmed_at}
for={@form}
id="login_form"
action={~p"/admins/log-in"}
phx-mounted={JS.focus_first()}
>
<input type="hidden" name={@form[:token].name} value={@form[:token].value} />
<%= if @current_scope do %>
<.button variant="primary" phx-disable-with="Logging in..." class="btn btn-primary w-full">
Log in
</.button>
<% else %>
<.button
name={@form[:remember_me].name}
value="true"
phx-disable-with="Logging in..."
class="btn btn-primary w-full"
>
Keep me logged in on this device
</.button>
<.button phx-disable-with="Logging in..." class="btn btn-primary btn-soft w-full mt-2">
Log me in only this time
</.button>
<% end %>
</.form>
<p :if={!@admin.confirmed_at} class="alert alert-outline mt-8">
Tip: If you prefer passwords, you can enable them in the admin settings.
</p>
</div>
</Layouts.app>

View File

@ -0,0 +1,70 @@
<Layouts.app flash={@flash} current_scope={@current_scope}>
<div class="mx-auto max-w-sm space-y-4">
<div class="text-center">
<.header>
<p>Log in</p>
<:subtitle>
<%= if @current_scope do %>
You need to reauthenticate to perform sensitive actions on your account.
<% else %>
Don't have an account? <.link
navigate={~p"/admins/register"}
class="font-semibold text-brand hover:underline"
phx-no-format
>Sign up</.link> for an account now.
<% end %>
</:subtitle>
</.header>
</div>
<div :if={local_mail_adapter?()} class="alert alert-info">
<.icon name="hero-information-circle" class="size-6 shrink-0" />
<div>
<p>You are running the local mail adapter.</p>
<p>
To see sent emails, visit <.link href="/dev/mailbox" class="underline">the mailbox page</.link>.
</p>
</div>
</div>
<.form :let={f} for={@form} as={:admin} id="login_form_magic" action={~p"/admins/log-in"}>
<.input
readonly={!!@current_scope}
field={f[:email]}
type="email"
label="Email"
autocomplete="email"
required
phx-mounted={JS.focus()}
/>
<.button class="btn btn-primary w-full">
Log in with email <span aria-hidden="true">→</span>
</.button>
</.form>
<div class="divider">or</div>
<.form :let={f} for={@form} as={:admin} id="login_form_password" action={~p"/admins/log-in"}>
<.input
readonly={!!@current_scope}
field={f[:email]}
type="email"
label="Email"
autocomplete="email"
required
/>
<.input
field={f[:password]}
type="password"
label="Password"
autocomplete="current-password"
/>
<.button class="btn btn-primary w-full" name={@form[:remember_me].name} value="true">
Log in and stay logged in <span aria-hidden="true">→</span>
</.button>
<.button class="btn btn-primary btn-soft w-full mt-2">
Log in only this time
</.button>
</.form>
</div>
</Layouts.app>

View File

@ -0,0 +1,77 @@
defmodule BeetRoundServerWeb.AdminSettingsController do
use BeetRoundServerWeb, :controller
alias BeetRoundServer.Admins
alias BeetRoundServerWeb.AdminAuth
import BeetRoundServerWeb.AdminAuth, only: [require_sudo_mode: 2]
plug :require_sudo_mode
plug :assign_email_and_password_changesets
def edit(conn, _params) do
render(conn, :edit)
end
def update(conn, %{"action" => "update_email"} = params) do
%{"admin" => admin_params} = params
admin = conn.assigns.current_scope.admin
case Admins.change_admin_email(admin, admin_params) do
%{valid?: true} = changeset ->
Admins.deliver_admin_update_email_instructions(
Ecto.Changeset.apply_action!(changeset, :insert),
admin.email,
&url(~p"/admins/settings/confirm-email/#{&1}")
)
conn
|> put_flash(
:info,
"A link to confirm your email change has been sent to the new address."
)
|> redirect(to: ~p"/admins/settings")
changeset ->
render(conn, :edit, email_changeset: %{changeset | action: :insert})
end
end
def update(conn, %{"action" => "update_password"} = params) do
%{"admin" => admin_params} = params
admin = conn.assigns.current_scope.admin
case Admins.update_admin_password(admin, admin_params) do
{:ok, {admin, _}} ->
conn
|> put_flash(:info, "Password updated successfully.")
|> put_session(:admin_return_to, ~p"/admins/settings")
|> AdminAuth.log_in_admin(admin)
{:error, changeset} ->
render(conn, :edit, password_changeset: changeset)
end
end
def confirm_email(conn, %{"token" => token}) do
case Admins.update_admin_email(conn.assigns.current_scope.admin, token) do
{:ok, _admin} ->
conn
|> put_flash(:info, "Email changed successfully.")
|> redirect(to: ~p"/admins/settings")
{:error, _} ->
conn
|> put_flash(:error, "Email change link is invalid or it has expired.")
|> redirect(to: ~p"/admins/settings")
end
end
defp assign_email_and_password_changesets(conn, _opts) do
admin = conn.assigns.current_scope.admin
conn
|> assign(:email_changeset, Admins.change_admin_email(admin))
|> assign(:password_changeset, Admins.change_admin_password(admin))
end
end

View File

@ -0,0 +1,5 @@
defmodule BeetRoundServerWeb.AdminSettingsHTML do
use BeetRoundServerWeb, :html
embed_templates "admin_settings_html/*"
end

View File

@ -0,0 +1,40 @@
<Layouts.app flash={@flash} current_scope={@current_scope}>
<div class="text-center">
<.header>
Account Settings
<:subtitle>Manage your account email address and password settings</:subtitle>
</.header>
</div>
<.form :let={f} for={@email_changeset} action={~p"/admins/settings"} id="update_email">
<input type="hidden" name="action" value="update_email" />
<.input field={f[:email]} type="email" label="Email" autocomplete="email" required />
<.button variant="primary" phx-disable-with="Changing...">Change Email</.button>
</.form>
<div class="divider" />
<.form :let={f} for={@password_changeset} action={~p"/admins/settings"} id="update_password">
<input type="hidden" name="action" value="update_password" />
<.input
field={f[:password]}
type="password"
label="New password"
autocomplete="new-password"
required
/>
<.input
field={f[:password_confirmation]}
type="password"
label="Confirm new password"
autocomplete="new-password"
required
/>
<.button variant="primary" phx-disable-with="Changing...">
Save Password
</.button>
</.form>
</Layouts.app>

View File

@ -1,6 +1,8 @@
defmodule BeetRoundServerWeb.Router do
use BeetRoundServerWeb, :router
import BeetRoundServerWeb.AdminAuth
import BeetRoundServerWeb.UserAuth
pipeline :browser do
@ -10,6 +12,7 @@ defmodule BeetRoundServerWeb.Router do
plug :put_root_layout, html: {BeetRoundServerWeb.Layouts, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
plug :fetch_current_scope_for_admin
plug :fetch_current_scope_for_user
end
@ -23,6 +26,12 @@ defmodule BeetRoundServerWeb.Router do
get "/", PageController, :home
end
scope "/api", BeetRoundServerWeb do
pipe_through :api
post "/log_in", AdminController, :log_in
post "/admin_create", AdminController, :create
end
# Other scopes may use custom stacks.
scope "/api", BeetRoundServerWeb do
pipe_through :api
@ -93,4 +102,30 @@ defmodule BeetRoundServerWeb.Router do
get "/log_in/:token", UserSessionController, :login
end
## Authentication routes
scope "/", BeetRoundServerWeb do
pipe_through [:browser, :redirect_if_admin_is_authenticated]
get "/admins/register", AdminRegistrationController, :new
post "/admins/register", AdminRegistrationController, :create
end
scope "/", BeetRoundServerWeb do
pipe_through [:browser, :require_authenticated_admin]
get "/admins/settings", AdminSettingsController, :edit
put "/admins/settings", AdminSettingsController, :update
get "/admins/settings/confirm-email/:token", AdminSettingsController, :confirm_email
end
scope "/", BeetRoundServerWeb do
pipe_through [:browser]
get "/admins/log-in", AdminSessionController, :new
get "/admins/log-in/:token", AdminSessionController, :confirm
post "/admins/log-in", AdminSessionController, :create
delete "/admins/log-out", AdminSessionController, :delete
end
end