Compare commits

...
8 Commits
Author SHA1 Message Date
owenrees 49736d186c Add public codes for player URLs and admin endgame search
Player-facing endgame links now use a 10-character Crockford base32 public code instead of the database UUID; admin routes keep the UUID. Existing rows are backfilled by migration, and the admin Show page displays and copies the code.

The admin endgame index gains its own search box: exact database id, exact public code, or a FEN / FEN fragment. A single match opens the endgame; multiple matches list below; nothing found says so.

Closes #44
Closes #45
2026-11-03 22:46:38 +01:00
owenrees 160e8629b7 Add rating window and time-based RD inflation (#41) 2026-11-03 22:20:02 +01:00
owenrees 4a36ffd2e6 Rate users and endgames with Glicko (#40) 2026-11-03 22:04:51 +01:00
owenrees a3fb878383 Record per-user Attempt history (#39) 2026-11-03 21:50:55 +01:00
owenrees eea8e48685 Make the play screen current-user aware (#38) 2026-11-03 21:41:56 +01:00
owenrees fdaf00e3b4 install Glicko lib 2026-11-03 21:37:17 +01:00
owenrees 36ddcc43ae Document rating vocabulary in GLOSSARY (#37) 2026-11-03 21:36:39 +01:00
owenrees 7cb7298236 Add user accounts, roles, and admin gating
- Scaffold password auth (email or username) with phx.gen.auth; no magic links
- Add role (member/moderator/admin/super_admin) and plan (free/premium) enums
- Gate /admin behind admin-or-above via plug + on_mount; hide the nav link
- Add mix accounts.promote for CLI role changes
- Disable email confirmation by confirming accounts at registration

Closes #3
2026-11-03 15:48:50 +01:00
56 changed files with 4720 additions and 78 deletions
+62
View File
@@ -66,3 +66,65 @@ The five canonical triage roles, each label string equal to its name (`needs-tri
### Domain docs ### Domain docs
Single-context: `GLOSSARY.md` and `docs/adr/` at the repo root. See `docs/agents/domain.md`. Single-context: `GLOSSARY.md` and `docs/adr/` at the repo root. See `docs/agents/domain.md`.
<!-- phoenix-gen-auth-start -->
## Authentication
- **Always** handle authentication flow at the router level with proper redirects
- **Always** be mindful of where to place routes. `phx.gen.auth` creates multiple router plugs and `live_session` scopes:
- A plug `:fetch_current_scope_for_user` that is included in the default browser pipeline
- A plug `:require_authenticated_user` that redirects to the log in page when the user is not authenticated
- A `live_session :current_user` scope - for routes that need the current user but don't require authentication, similar to `:fetch_current_scope_for_user`
- A `live_session :require_authenticated_user` scope - for routes that require authentication, similar to the plug with the same name
- In both cases, a `@current_scope` is assigned to the Plug connection and LiveView socket
- A plug `redirect_if_user_is_authenticated` that redirects to a default path in case the user is authenticated - useful for a registration page that should only be shown to unauthenticated users
- **Always let the user know in which router scopes, `live_session`, and pipeline you are placing the route, AND SAY WHY**
- `phx.gen.auth` assigns the `current_scope` assign - it **does not assign a `current_user` assign**
- Always pass the assign `current_scope` to context modules as first argument. When performing queries, use `current_scope.user` to filter the query results
- To derive/access `current_user` in templates, **always use the `@current_scope.user`**, never use **`@current_user`** in templates or LiveViews
- **Never** duplicate `live_session` names. A `live_session :current_user` can only be defined __once__ in the router, so all routes for the `live_session :current_user` must be grouped in a single block
- Anytime you hit `current_scope` errors or the logged in session isn't displaying the right content, **always double check the router and ensure you are using the correct plug and `live_session` as described below**
### Routes that require authentication
LiveViews that require login should **always be placed inside the __existing__ `live_session :require_authenticated_user` block**:
scope "/", AppWeb do
pipe_through [:browser, :require_authenticated_user]
live_session :require_authenticated_user,
on_mount: [{ChesstrainerWeb.UserAuth, :require_authenticated}] do
# phx.gen.auth generated routes
live "/users/settings", UserLive.Settings, :edit
live "/users/settings/confirm-email/:token", UserLive.Settings, :confirm_email
# our own routes that require logged in user
live "/", MyLiveThatRequiresAuth, :index
end
end
Controller routes must be placed in a scope that sets the `:require_authenticated_user` plug:
scope "/", AppWeb do
pipe_through [:browser, :require_authenticated_user]
get "/", MyControllerThatRequiresAuth, :index
end
### Routes that work with or without authentication
LiveViews that can work with or without authentication, **always use the __existing__ `:current_user` scope**, ie:
scope "/", MyAppWeb do
pipe_through [:browser]
live_session :current_user,
on_mount: [{ChesstrainerWeb.UserAuth, :mount_current_scope}] do
# our own routes that work with or without authentication
live "/", PublicLive
end
end
Controllers automatically have the `current_scope` available if they use the `:browser` pipeline.
<!-- phoenix-gen-auth-end -->
+43 -1
View File
@@ -16,7 +16,8 @@ side correctly against tablebase-optimal defence.
_Avoid_: Endgame (the stored record), exercise _Avoid_: Endgame (the stored record), exercise
**Attempt**: **Attempt**:
One playthrough of a puzzle by a user, ending solved or failed. A recorded playthrough of a puzzle by a user, ending solved or failed; a
per-user record, distinct from an endgame's global attempt and solve counts.
_Avoid_: Run, session, game _Avoid_: Run, session, game
**Theme**: **Theme**:
@@ -30,6 +31,25 @@ pieces each side has, written strongest side first and colour-agnostic
(e.g. "KQ v KR"). Used to group and search endgames by material. (e.g. "KQ v KR"). Used to group and search endgames by material.
_Avoid_: Material signature, hash _Avoid_: Material signature, hash
**Public code**:
The short, stable identifier an endgame is played under in player-facing
links, distinct from its database id and safe to share.
_Avoid_: Slug, UUID, endgame id, token
## Identity & access
**User**:
A person who can sign in to the trainer, identified by a unique email address and a unique username.
_Avoid_: Account, player
**Role**:
A user's authority tier — `member`, `moderator`, `admin` or `super_admin` — deciding access to the admin area and the power to manage other users.
_Avoid_: Permission, access level
**Plan**:
A user's subscription tier — `free` or `premium` — independent of their role.
_Avoid_: Tier, subscription, membership
## Play ## Play
**Winning side**: **Winning side**:
@@ -59,6 +79,28 @@ The decisive zeroing move — a promotion — that ends a conversion-type puzzle
The terminal condition short of mate at which a puzzle counts as solved: The terminal condition short of mate at which a puzzle counts as solved:
promotion (still winning) for conversion puzzles, mate otherwise. promotion (still winning) for conversion puzzles, mate otherwise.
## Ratings
**Rating**:
A user's estimated solving skill, or an endgame's estimated difficulty, on a
scale that lets the two be compared.
_Avoid_: Score, ELO, rank
**Rating deviation**:
The uncertainty around a rating; it widens with inactivity and narrows with
rated results, so a less certain rating moves further per result.
_Avoid_: Error margin, variance
**Rating window**:
The minimum interval before the same user replaying the same endgame can change
either rating again.
_Avoid_: Cooldown (reserved for tablebase rate-limiting)
**Volatility**:
A measure of how erratic a competitor's recent results are, used by some rating
systems; the trainer deliberately does not track it.
_Avoid_: Variance, inconsistency
## Infrastructure ## Infrastructure
**Tablebase**: **Tablebase**:
+25
View File
@@ -7,10 +7,35 @@
# General application configuration # General application configuration
import Config import Config
config :chesstrainer, :scopes,
user: [
default: true,
module: Chesstrainer.Accounts.Scope,
assign_key: :current_scope,
access_path: [:user, :id],
schema_key: :user_id,
schema_type: :binary_id,
schema_table: :users,
test_data_fixture: Chesstrainer.AccountsFixtures,
test_setup_helper: :register_and_log_in_user
]
config :chesstrainer, config :chesstrainer,
ecto_repos: [Chesstrainer.Repo], ecto_repos: [Chesstrainer.Repo],
generators: [timestamp_type: :utc_datetime] generators: [timestamp_type: :utc_datetime]
# Glicko rating system.
#
# `system_constant` is the volatility constraint passed through to the Glicko
# package. `window_days` is the minimum gap before replaying the same
# user/endgame pair may change either rating again. `rd_inflation_c` widens a
# rating deviation by sqrt(c^2 * days) while that side is inactive, capped at
# the Glicko maximum (350).
config :chesstrainer, :ratings,
system_constant: 0.8,
window_days: 7,
rd_inflation_c: 10.0
# Configure the endpoint # Configure the endpoint
config :chesstrainer, ChesstrainerWeb.Endpoint, config :chesstrainer, ChesstrainerWeb.Endpoint,
url: [host: "localhost"], url: [host: "localhost"],
+3
View File
@@ -1,5 +1,8 @@
import Config import Config
# Only in tests, remove the complexity from the password hashing algorithm
config :bcrypt_elixir, :log_rounds, 1
# Point the local Fathom backend at the committed 3-piece fixtures. # Point the local Fathom backend at the committed 3-piece fixtures.
config :chesstrainer, :tablebase_path, Path.expand("../test/fixtures/tablebase", __DIR__) config :chesstrainer, :tablebase_path, Path.expand("../test/fixtures/tablebase", __DIR__)
@@ -0,0 +1,18 @@
# Player-facing endgame URLs use a public code
Player links address an endgame by a short random **public code** rather than
its database UUID. The UUID stays the admin identity: admin routes mount by
id and the Show page displays both. The code is stable for the row's lifetime
and unguessable, so a shared play link neither exposes a primary key nor
invites enumeration. Keys were rejected as the handle because many endgames
share one (that is how the list groups them), and Key-plus-ordinal would break
when endgames are added or removed. A FEN hash was rejected as longer and
derivable without hiding anything new.
## Consequences
- Admin URLs and the admin list keep the UUID, so debugging still lines up
with the database. Admin search accepts either identifier plus a FEN or FEN
fragment.
- A public code is generated on insert and backfilled by migration; it is
never regenerated on update.
+274
View File
@@ -0,0 +1,274 @@
defmodule Chesstrainer.Accounts do
@moduledoc """
The Accounts context.
"""
import Ecto.Query, warn: false
alias Chesstrainer.Repo
alias Chesstrainer.Accounts.{User, UserToken, UserNotifier}
## 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
"""
def get_user_by_email(email) when is_binary(email) do
Repo.get_by(User, email: email)
end
@doc """
Gets a user by email or username.
Email and username are both `citext`, so the lookup ignores case.
## Examples
iex> get_user_by_login("foo@example.com")
%User{}
iex> get_user_by_login("unknown")
nil
"""
def get_user_by_login(login) when is_binary(login) do
login = String.trim(login)
from(u in User, where: u.email == ^login or u.username == ^login, limit: 1)
|> Repo.one()
end
@doc """
Gets a user by email or username and password.
## Examples
iex> get_user_by_login_and_password("foo@example.com", "correct_password")
%User{}
iex> get_user_by_login_and_password("foo@example.com", "invalid_password")
nil
"""
def get_user_by_login_and_password(login, password)
when is_binary(login) and is_binary(password) do
user = get_user_by_login(login)
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!(123)
%User{}
iex> get_user!(456)
** (Ecto.NoResultsError)
"""
def get_user!(id), do: Repo.get!(User, id)
## User registration
@doc """
Registers a user.
## Examples
iex> register_user(%{field: value})
{:ok, %User{}}
iex> register_user(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def register_user(attrs) do
%User{}
|> User.registration_changeset(attrs)
# Accounts are usable straight away; email confirmation is intentionally off
# because no production mailer adapter is configured yet.
|> Ecto.Changeset.put_change(:confirmed_at, DateTime.utc_now(:second))
|> Repo.insert()
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking user registration changes.
See `Chesstrainer.Accounts.User.registration_changeset/3`.
"""
def change_user_registration(user, attrs \\ %{}, opts \\ []) do
User.registration_changeset(user, attrs, opts)
end
@doc """
Updates a user's authority role.
This is the only supported path for changing roles; registration never casts
`role`, so a user cannot promote themselves.
"""
def update_user_role(%User{} = user, role) do
user
|> User.role_changeset(%{role: role})
|> Repo.update()
end
## Settings
@doc """
Checks whether the user is in sudo mode.
The user 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?(user, minutes \\ -20)
def sudo_mode?(%User{authenticated_at: ts}, minutes) when is_struct(ts, DateTime) do
DateTime.after?(ts, DateTime.utc_now() |> DateTime.add(minutes, :minute))
end
def sudo_mode?(_user, _minutes), do: false
@doc """
Returns an `%Ecto.Changeset{}` for changing the user email.
See `Chesstrainer.Accounts.User.email_changeset/3` for a list of supported options.
## Examples
iex> change_user_email(user)
%Ecto.Changeset{data: %User{}}
"""
def change_user_email(user, attrs \\ %{}, opts \\ []) do
User.email_changeset(user, attrs, opts)
end
@doc """
Updates the user email using the given token.
If the token matches, the user email is updated and the token is deleted.
"""
def update_user_email(user, token) do
context = "change:#{user.email}"
Repo.transact(fn ->
with {:ok, query} <- UserToken.verify_change_email_token_query(token, context),
%UserToken{sent_to: email} <- Repo.one(query),
{:ok, user} <- Repo.update(User.email_changeset(user, %{email: email})),
{_count, _result} <-
Repo.delete_all(from(UserToken, where: [user_id: ^user.id, context: ^context])) do
{:ok, user}
else
_ -> {:error, :transaction_aborted}
end
end)
end
@doc """
Returns an `%Ecto.Changeset{}` for changing the user password.
See `Chesstrainer.Accounts.User.password_changeset/3` for a list of supported options.
## Examples
iex> change_user_password(user)
%Ecto.Changeset{data: %User{}}
"""
def change_user_password(user, attrs \\ %{}, opts \\ []) do
User.password_changeset(user, attrs, opts)
end
@doc """
Updates the user password.
Returns a tuple with the updated user, as well as a list of expired tokens.
## Examples
iex> update_user_password(user, %{password: ...})
{:ok, {%User{}, [...]}}
iex> update_user_password(user, %{password: "too short"})
{:error, %Ecto.Changeset{}}
"""
def update_user_password(user, attrs) do
user
|> User.password_changeset(attrs)
|> update_user_and_delete_all_tokens()
end
## Session
@doc """
Generates a session token.
"""
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.
If the token is valid `{user, token_inserted_at}` is returned, otherwise `nil` is returned.
"""
def get_user_by_session_token(token) do
{:ok, query} = UserToken.verify_session_token_query(token)
Repo.one(query)
end
@doc ~S"""
Delivers the update email instructions to the given user.
## Examples
iex> deliver_user_update_email_instructions(user, current_email, &url(~p"/users/settings/confirm-email/#{&1}"))
{:ok, %{to: ..., body: ...}}
"""
def deliver_user_update_email_instructions(%User{} = 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)
UserNotifier.deliver_update_email_instructions(user, update_email_url_fun.(encoded_token))
end
@doc """
Deletes the signed token with the given context.
"""
def delete_user_session_token(token) do
Repo.delete_all(from(UserToken, where: [token: ^token, context: "session"]))
:ok
end
## Token helper
defp update_user_and_delete_all_tokens(changeset) do
Repo.transact(fn ->
with {:ok, user} <- Repo.update(changeset) do
tokens_to_expire = Repo.all_by(UserToken, user_id: user.id)
Repo.delete_all(from(t in UserToken, where: t.id in ^Enum.map(tokens_to_expire, & &1.id)))
{:ok, {user, tokens_to_expire}}
end
end)
end
end
+37
View File
@@ -0,0 +1,37 @@
defmodule Chesstrainer.Accounts.Role do
@moduledoc """
The ordered authority tiers a user can hold.
A higher rank may do everything a lower rank may, so authorization checks
should ask for the minimum tier they need via `at_least?/2`.
"""
@values [:member, :moderator, :admin, :super_admin]
@ranks %{
member: 0,
moderator: 1,
admin: 2,
super_admin: 3
}
@doc "All roles, ordered from least to most authority."
def values, do: @values
@doc "The numeric rank of a role."
def rank(role) when role in @values, do: Map.fetch!(@ranks, role)
@doc """
Returns true when `role` is at least as authoritative as `minimum`.
A missing role (no user) never satisfies any minimum.
"""
def at_least?(role, minimum) when role in @values and minimum in @values do
rank(role) >= rank(minimum)
end
def at_least?(_role, _minimum), do: false
@doc "Returns true when the role may use the admin area."
def admin?(role), do: at_least?(role, :admin)
end
+33
View File
@@ -0,0 +1,33 @@
defmodule Chesstrainer.Accounts.Scope do
@moduledoc """
Defines the scope of the caller to be used throughout the app.
The `Chesstrainer.Accounts.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 Chesstrainer.Accounts.User
defstruct user: nil
@doc """
Creates a scope for the given user.
Returns nil if no user is given.
"""
def for_user(%User{} = user) do
%__MODULE__{user: user}
end
def for_user(nil), do: nil
end
+190
View File
@@ -0,0 +1,190 @@
defmodule Chesstrainer.Accounts.User do
use Ecto.Schema
import Ecto.Changeset
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "users" do
field :email, :string
field :username, :string
field :password, :string, virtual: true, redact: true
field :hashed_password, :string, redact: true
field :role, Ecto.Enum, values: [:member, :moderator, :admin, :super_admin], default: :member
field :plan, Ecto.Enum, values: [:free, :premium], default: :free
field :rating, :float, default: 1500.0
field :rating_deviation, :float, default: 350.0
field :confirmed_at, :utc_datetime
field :authenticated_at, :utc_datetime, virtual: true
timestamps(type: :utc_datetime)
end
@doc """
A user changeset for registration.
It requires an email, a username and a password, and sets no role or plan:
those are programmatic values that only the promote task may change.
## Options
* `:validate_unique` - Set to false if you don't want to validate the
uniqueness of the email and username, useful when displaying live
validations. Defaults to `true`.
* `:hash_password` - Hashes the password when true. Defaults to `true`.
"""
def registration_changeset(user, attrs, opts \\ []) do
user
|> cast(attrs, [:email, :username, :password])
|> validate_email(opts)
|> validate_username(opts)
|> validate_confirmation(:password, message: "does not match password")
|> validate_password(opts)
end
@doc """
A user changeset for changing the role.
The role is programmatic and must never be cast from user-supplied params.
"""
def role_changeset(user, attrs) do
user
|> cast(attrs, [:role])
|> validate_required([:role])
end
@doc """
A user 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(user, attrs, opts \\ []) do
user
|> 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, Chesstrainer.Repo)
|> unique_constraint(:email)
|> validate_email_changed()
else
changeset
end
end
defp validate_username(changeset, opts) do
changeset =
changeset
|> validate_required([:username])
|> validate_length(:username, min: 3, max: 30)
|> validate_format(:username, ~r/\A[a-zA-Z0-9_]+\z/,
message: "only letters, numbers and underscores"
)
if Keyword.get(opts, :validate_unique, true) do
changeset
|> unsafe_validate_unique(:username, Chesstrainer.Repo)
|> unique_constraint(:username)
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 user 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(user, attrs, opts \\ []) do
user
|> 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(user) do
now = DateTime.utc_now(:second)
change(user, 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.
"""
def valid_password?(%Chesstrainer.Accounts.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?(_, _) do
Bcrypt.no_user_verify()
false
end
end
@@ -0,0 +1,39 @@
defmodule Chesstrainer.Accounts.UserNotifier do
import Swoosh.Email
alias Chesstrainer.Mailer
# Delivers the email using the application mailer.
defp deliver(recipient, subject, body) do
email =
new()
|> to(recipient)
|> from({"Chesstrainer", "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 user email.
"""
def deliver_update_email_instructions(user, url) do
deliver(user.email, "Update email instructions", """
==============================
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
+127
View File
@@ -0,0 +1,127 @@
defmodule Chesstrainer.Accounts.UserToken do
use Ecto.Schema
import Ecto.Query
alias Chesstrainer.Accounts.UserToken
@hash_algorithm :sha256
@rand_size 32
@change_email_validity_in_days 7
@session_validity_in_days 14
@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
field :authenticated_at, :utc_datetime
belongs_to :user, Chesstrainer.Accounts.User
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 user
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(user) do
token = :crypto.strong_rand_bytes(@rand_size)
dt = user.authenticated_at || DateTime.utc_now(:second)
{token, %UserToken{token: token, context: "session", user_id: user.id, authenticated_at: dt}}
end
@doc """
Checks if the token is valid and returns its underlying lookup query.
The query returns the user 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: user in assoc(token, :user),
where: token.inserted_at > ago(@session_validity_in_days, "day"),
select: {%{user | authenticated_at: token.authenticated_at}, token.inserted_at}
{:ok, query}
end
@doc """
Builds a token and its hash to be delivered to the user's email.
The non-hashed token is sent to the user 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 user 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(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),
%UserToken{
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_token found by the token, if any.
This is used to validate requests to change the user
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
defp by_token_and_context_query(token, context) do
from UserToken, where: [token: ^token, context: ^context]
end
end
+63
View File
@@ -0,0 +1,63 @@
defmodule Chesstrainer.Attempts do
@moduledoc """
The Attempts context: a per-user history of finished playthroughs.
"""
import Ecto.Query, warn: false
alias Chesstrainer.Repo
alias Chesstrainer.Accounts.{Scope, User}
alias Chesstrainer.Endgames.Endgame
alias Chesstrainer.Attempts.Attempt
@doc """
Records a finished attempt for the signed-in user in `scope`.
Anonymous scopes record nothing and return `:ignored`.
"""
def record_attempt(nil, _endgame, _outcome), do: :ignored
def record_attempt(%Scope{user: nil}, _endgame, _outcome), do: :ignored
def record_attempt(%Scope{user: %User{} = user}, %Endgame{} = endgame, outcome)
when outcome in [:solved, :failed] do
%Attempt{user_id: user.id, endgame_id: endgame.id}
|> Attempt.changeset(%{outcome: outcome})
|> Repo.insert()
end
@doc """
The timestamp of the most recent rated attempt for a user/endgame pair, or nil.
"""
def last_rated_at(user_id, endgame_id) do
Attempt
|> where([a], a.user_id == ^user_id and a.endgame_id == ^endgame_id)
|> rated()
|> select([a], max(a.rated_at))
|> Repo.one()
end
@doc """
The timestamp of the most recent rated attempt for a user, or nil.
"""
def last_rated_at_for_user(user_id) do
Attempt
|> where([a], a.user_id == ^user_id)
|> rated()
|> select([a], max(a.rated_at))
|> Repo.one()
end
@doc """
The timestamp of the most recent rated attempt on an endgame, or nil.
"""
def last_rated_at_for_endgame(endgame_id) do
Attempt
|> where([a], a.endgame_id == ^endgame_id)
|> rated()
|> select([a], max(a.rated_at))
|> Repo.one()
end
defp rated(query), do: where(query, [a], not is_nil(a.rated_at))
end
+27
View File
@@ -0,0 +1,27 @@
defmodule Chesstrainer.Attempts.Attempt do
@moduledoc """
A per-user playthrough of an endgame, ending solved or failed.
"""
use Ecto.Schema
import Ecto.Changeset
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "attempts" do
field :outcome, Ecto.Enum, values: [:solved, :failed]
field :rated_at, :utc_datetime
belongs_to :user, Chesstrainer.Accounts.User
belongs_to :endgame, Chesstrainer.Endgames.Endgame
timestamps(type: :utc_datetime)
end
@doc false
def changeset(attempt, attrs) do
attempt
|> cast(attrs, [:outcome, :rated_at])
|> validate_required([:outcome])
end
end
+75 -5
View File
@@ -92,6 +92,63 @@ defmodule Chesstrainer.Endgames do
""" """
def get_endgame!(id), do: Repo.get!(Endgame, id) def get_endgame!(id), do: Repo.get!(Endgame, id)
@doc """
Gets a single endgame by its public code, raising if it does not exist.
"""
def get_endgame_by_public_code!(public_code) do
Repo.get_by!(Endgame, public_code: public_code)
end
@doc """
Finds endgames by database id, public code, or FEN.
A full FEN matches exactly (after normalisation); a fragment matches any FEN
containing it. Themes are preloaded. A blank query returns `[]`.
"""
def search(query) do
query = String.trim(query || "")
if query == "" do
[]
else
[search_by_id(query), search_by_public_code(query), search_by_fen(query)]
|> Enum.reject(&is_nil/1)
|> List.flatten()
|> Enum.uniq_by(& &1.id)
end
end
defp search_by_id(query) do
case Ecto.UUID.cast(query) do
{:ok, id} -> Repo.get(Endgame, id) |> preload_themes()
:error -> nil
end
end
defp search_by_public_code(query) do
Repo.get_by(Endgame, public_code: query) |> preload_themes()
end
defp search_by_fen(query) do
pattern = "%" <> escape_like(Chesstrainer.FEN.normalize(query)) <> "%"
Endgame
|> where([e], like(e.fen, ^pattern))
|> preload(:themes)
|> order_by([e], asc: e.key, asc: e.fen)
|> Repo.all()
end
defp preload_themes(nil), do: nil
defp preload_themes(endgame), do: Repo.preload(endgame, :themes)
defp escape_like(value) do
value
|> String.replace("\\", "\\\\")
|> String.replace("%", "\\%")
|> String.replace("_", "\\_")
end
@doc """ @doc """
Creates a endgame. Creates a endgame.
@@ -104,11 +161,24 @@ defmodule Chesstrainer.Endgames do
{:error, %Ecto.Changeset{}} {:error, %Ecto.Changeset{}}
""" """
def create_endgame(attrs, themes \\ []) do def create_endgame(attrs, themes \\ []), do: insert_endgame(attrs, themes, 3)
%Endgame{}
|> Endgame.changeset(attrs) defp insert_endgame(attrs, themes, attempts) do
|> Ecto.Changeset.put_assoc(:themes, themes) result =
|> Repo.insert() %Endgame{}
|> Endgame.changeset(attrs)
|> Ecto.Changeset.put_assoc(:themes, themes)
|> Repo.insert()
case result do
{:error, changeset} when attempts > 1 ->
if Keyword.has_key?(changeset.errors, :public_code),
do: insert_endgame(attrs, themes, attempts - 1),
else: result
other ->
other
end
end end
@doc """ @doc """
+32 -2
View File
@@ -8,17 +8,21 @@ defmodule Chesstrainer.Endgames.Endgame do
alias Chesstrainer.Key alias Chesstrainer.Key
@public_code_alphabet ~c"0123456789abcdefghjkmnpqrstvwxyz"
@public_code_length 10
@primary_key {:id, :binary_id, autogenerate: true} @primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id @foreign_key_type :binary_id
schema "endgames" do schema "endgames" do
field :public_code, :string
field :fen, :string field :fen, :string
field :color, Ecto.Enum, values: [:white, :black] field :color, Ecto.Enum, values: [:white, :black]
field :key, :string field :key, :string
field :message, :string field :message, :string
field :notes, :string field :notes, :string
field :result, Ecto.Enum, values: [:win, :loss, :draw] field :result, Ecto.Enum, values: [:win, :loss, :draw]
field :rating, :integer, default: 1500 field :rating, :float, default: 1500.0
field :rating_deviation, :integer field :rating_deviation, :float, default: 350.0
field :times_attempted, :integer field :times_attempted, :integer
field :times_solved, :integer field :times_solved, :integer
@@ -42,7 +46,33 @@ defmodule Chesstrainer.Endgames.Endgame do
end end
end) end)
|> unique_constraint(:fen, message: "FEN already exists") |> unique_constraint(:fen, message: "FEN already exists")
|> unique_constraint(:public_code)
|> put_key() |> put_key()
|> put_public_code()
end
@doc """
Generates a public code: a short, random identifier for player-facing URLs.
10 characters of Crockford base32 (no `i`, `l`, `o` or `u`) give roughly 50
bits, so collisions are vanishingly rare; the unique index is the backstop.
"""
@spec generate_public_code() :: String.t()
def generate_public_code do
@public_code_length
|> :crypto.strong_rand_bytes()
|> :binary.bin_to_list()
|> Enum.map(fn byte ->
Enum.at(@public_code_alphabet, rem(byte, length(@public_code_alphabet)))
end)
|> List.to_string()
end
defp put_public_code(changeset) do
case get_field(changeset, :public_code) do
nil -> put_change(changeset, :public_code, generate_public_code())
_ -> changeset
end
end end
defp put_key(changeset) do defp put_key(changeset) do
+131
View File
@@ -0,0 +1,131 @@
defmodule Chesstrainer.Ratings do
@moduledoc """
Applies Glicko rating updates to a finished attempt.
Both sides are rated: the user as the player and the endgame as the opponent,
then the reverse so the endgame's difficulty tracks its results.
An attempt only changes ratings when the same user/endgame pair has not been
rated inside the rating window. When it does rate, each side's deviation is
widened in proportion to how long that side has been inactive, so a return
after a long gap moves ratings further than a quick return.
"""
alias Chesstrainer.Repo
alias Chesstrainer.Accounts.User
alias Chesstrainer.Endgames.Endgame
alias Chesstrainer.Attempts
alias Chesstrainer.Attempts.Attempt
@default_system_constant 0.8
@default_window_days 7
@default_rd_inflation_c 10.0
@max_rd 350.0
@seconds_per_day 86_400
@doc """
Rates both sides of a finished attempt and stamps it as rated.
A solve scores 1 for the user and 0 for the endgame; a failure scores 0 for
the user and 1 for the endgame. Returns `{:ok, %{user, endgame, attempt}}`, or
`{:skipped, attempt}` when the pair was already rated inside the window.
"""
def rate_attempt(%Attempt{outcome: outcome} = attempt) do
now = DateTime.utc_now(:second)
if rate?(attempt, now) do
user = Repo.get!(User, attempt.user_id)
endgame = Repo.get!(Endgame, attempt.endgame_id)
user_rd =
inflate(
user.rating_deviation,
elapsed_days(now, Attempts.last_rated_at_for_user(user.id))
)
endgame_rd =
inflate(
endgame.rating_deviation,
elapsed_days(now, Attempts.last_rated_at_for_endgame(endgame.id))
)
user_player = player(user.rating, user_rd)
endgame_player = player(endgame.rating, endgame_rd)
score = score_for(outcome)
new_user =
Glicko.new_rating(user_player, [Glicko.Result.new(endgame_player, score)], opts())
new_endgame =
Glicko.new_rating(endgame_player, [Glicko.Result.new(user_player, 1.0 - score)], opts())
persist(user, endgame, attempt, new_user, new_endgame, now)
else
{:skipped, attempt}
end
end
defp rate?(attempt, now) do
case Attempts.last_rated_at(attempt.user_id, attempt.endgame_id) do
nil -> true
last -> DateTime.diff(now, last, :second) >= window_days() * @seconds_per_day
end
end
defp persist(user, endgame, attempt, new_user, new_endgame, now) do
Repo.transaction(fn ->
user =
user
|> Ecto.Changeset.change(
rating: new_user.rating,
rating_deviation: new_user.rating_deviation
)
|> Repo.update!()
endgame =
endgame
|> Ecto.Changeset.change(
rating: new_endgame.rating,
rating_deviation: new_endgame.rating_deviation
)
|> Repo.update!()
attempt =
attempt
|> Ecto.Changeset.change(rated_at: now)
|> Repo.update!()
%{user: user, endgame: endgame, attempt: attempt}
end)
end
defp player(rating, rating_deviation) do
Glicko.Player.new_v1(rating: rating, rating_deviation: rating_deviation)
end
# Widen a deviation by the time since that side last had a rated result,
# capped at the Glicko maximum.
defp inflate(rd, days) when days <= 0.0, do: rd
defp inflate(rd, days) do
c = rd_inflation_c()
min(:math.sqrt(rd * rd + c * c * days), @max_rd)
end
defp elapsed_days(_now, nil), do: 0.0
defp elapsed_days(now, last) do
max(DateTime.diff(now, last, :second), 0) / @seconds_per_day
end
defp score_for(:solved), do: 1.0
defp score_for(:failed), do: 0.0
defp opts, do: [system_constant: system_constant()]
defp config, do: Application.get_env(:chesstrainer, :ratings, [])
defp system_constant, do: Keyword.get(config(), :system_constant, @default_system_constant)
defp window_days, do: Keyword.get(config(), :window_days, @default_window_days)
defp rd_inflation_c, do: Keyword.get(config(), :rd_inflation_c, @default_rd_inflation_c)
end
+27 -6
View File
@@ -5,6 +5,8 @@ defmodule ChesstrainerWeb.Layouts do
""" """
use ChesstrainerWeb, :html use ChesstrainerWeb, :html
alias Chesstrainer.Accounts.Role
# Embed all files in layouts/* within this module. # Embed all files in layouts/* within this module.
# The default root.html.heex file contains the HTML # The default root.html.heex file contains the HTML
# skeleton of your application, namely HTML headers # skeleton of your application, namely HTML headers
@@ -51,6 +53,10 @@ defmodule ChesstrainerWeb.Layouts do
@doc """ @doc """
Renders the application navbar. Renders the application navbar.
""" """
attr :current_scope, :map,
default: nil,
doc: "the current [scope](https://phoenix.hexdocs.pm/scopes.html)"
def navbar(assigns) do def navbar(assigns) do
~H""" ~H"""
<header class="navbar px-4 sm:px-6 lg:px-8"> <header class="navbar px-4 sm:px-6 lg:px-8">
@@ -65,17 +71,32 @@ defmodule ChesstrainerWeb.Layouts do
<li> <li>
<a href="/endgames" class="btn btn-ghost">Endgames</a> <a href="/endgames" class="btn btn-ghost">Endgames</a>
</li> </li>
<li> <li :if={@current_scope && Role.admin?(@current_scope.user.role)}>
<a href="/admin/endgames" class="btn btn-ghost">Admin</a> <a href="/admin/endgames" class="btn btn-ghost">Admin</a>
</li> </li>
<li> <li>
<.theme_toggle /> <.theme_toggle />
</li> </li>
<li> <%= if @current_scope do %>
<a href="/" class="btn btn-primary"> <li>
Login / Signup <span class="text-sm">{@current_scope.user.username}</span>
</a> </li>
</li> <li>
<.link navigate={~p"/users/settings"} class="btn btn-ghost">Settings</.link>
</li>
<li>
<.link href={~p"/users/log-out"} method="delete" class="btn btn-ghost">
Log out
</.link>
</li>
<% else %>
<li>
<.link navigate={~p"/users/register"} class="btn btn-ghost">Register</.link>
</li>
<li>
<.link navigate={~p"/users/log-in"} class="btn btn-primary">Log in</.link>
</li>
<% end %>
</ul> </ul>
</div> </div>
</header> </header>
@@ -40,7 +40,7 @@
</script> </script>
</head> </head>
<body> <body>
<Layouts.navbar /> <Layouts.navbar current_scope={@current_scope} />
{@inner_content} {@inner_content}
</body> </body>
</html> </html>
@@ -0,0 +1,48 @@
defmodule ChesstrainerWeb.UserSessionController do
use ChesstrainerWeb, :controller
alias Chesstrainer.Accounts
alias ChesstrainerWeb.UserAuth
def create(conn, %{"user" => user_params}) do
%{"email" => login, "password" => password} = user_params
case Accounts.get_user_by_login_and_password(login, password) do
nil ->
# In order to prevent user enumeration attacks, don't disclose whether
# the email or username is registered.
conn
|> put_flash(:error, "Invalid email, username or password")
|> put_flash(:email, String.slice(login, 0, 160))
|> redirect(to: ~p"/users/log-in")
user ->
conn
|> put_flash(:info, "Welcome back!")
|> UserAuth.log_in_user(user, user_params)
end
end
def update_password(conn, %{"user" => user_params}) do
user = conn.assigns.current_scope.user
true = Accounts.sudo_mode?(user)
{:ok, {_user, expired_tokens}} = Accounts.update_user_password(user, user_params)
# disconnect all existing LiveViews with old sessions
UserAuth.disconnect_sessions(expired_tokens)
%{"email" => login, "password" => password} = user_params
user = Accounts.get_user_by_login_and_password(login, password)
conn
|> put_session(:user_return_to, ~p"/users/settings")
|> put_flash(:info, "Password updated successfully!")
|> UserAuth.log_in_user(user, user_params)
end
def delete(conn, _params) do
conn
|> put_flash(:info, "Logged out successfully.")
|> UserAuth.log_out_user()
end
end
+13 -2
View File
@@ -73,7 +73,12 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
<.form for={@form} id="endgame-form" phx-change="validate" phx-submit="save"> <.form for={@form} id="endgame-form" phx-change="validate" phx-submit="save">
<.input field={@form[:fen]} type="text" label="Fen" disabled={@live_action == :edit} /> <.input field={@form[:fen]} type="text" label="Fen" disabled={@live_action == :edit} />
<.input field={@form[:color]} type="text" label="Color" disabled /> <.input field={@form[:color]} type="text" label="Color" disabled />
<.input field={@form[:rating]} type="number" label="Rating" /> <.input
field={@form[:rating]}
type="number"
value={rating_display(@form[:rating])}
label="Rating"
/>
<.input field={@form[:message]} type="textarea" label="Message" /> <.input field={@form[:message]} type="textarea" label="Message" />
<.input field={@form[:notes]} type="textarea" label="Notes" /> <.input field={@form[:notes]} type="textarea" label="Notes" />
<.input <.input
@@ -244,6 +249,12 @@ defmodule ChesstrainerWeb.EndgameLive.Form do
end end
end end
# Ratings are stored as floats (Glicko); the admin form presents them as whole numbers.
defp rating_display(%Phoenix.HTML.FormField{value: value}) when is_float(value),
do: round(value)
defp rating_display(%Phoenix.HTML.FormField{value: value}), do: value
defp return_path("index", _endgame), do: ~p"/admin/endgames" defp return_path("index", _endgame), do: ~p"/admin/endgames"
defp return_path("show", endgame), do: ~p"/admin/endgames/#{endgame}" defp return_path("show", endgame), do: ~p"/admin/endgames/#{endgame.id}"
end end
+113 -10
View File
@@ -18,7 +18,63 @@ defmodule ChesstrainerWeb.EndgameLive.Index do
</:actions> </:actions>
</.header> </.header>
<.form
for={@search_form}
id="endgame-search-form"
phx-submit="endgame_search"
class="mb-6 flex items-end gap-2"
>
<div class="flex-1">
<.input
field={@search_form[:query]}
type="text"
label="Find by ID or FEN"
autocomplete="off"
placeholder="Public code, database id, or FEN…"
class="input input-bordered w-full"
/>
</div>
<.button variant="primary">Find</.button>
</.form>
<div :if={@search_query} id="endgame-search-results" class="space-y-3">
<div class="flex items-center justify-between">
<p class="text-sm text-base-content/70">Results for “{@search_query}”</p>
<button type="button" id="clear-endgame-search" phx-click="clear_search" class="link">
Clear
</button>
</div>
<p :if={@search_results == []} class="text-base-content/70">
No endgame matches “{@search_query}”.
</p>
<table :if={@search_results != []} class="table table-zebra">
<thead>
<tr>
<th>Key</th>
<th>Color</th>
<th>Result</th>
<th>Rating</th>
<th><span class="sr-only">Actions</span></th>
</tr>
</thead>
<tbody>
<tr :for={endgame <- @search_results} id={"search-result-" <> endgame.id}>
<td>{endgame.key}</td>
<td>{endgame.color}</td>
<td>{endgame.result}</td>
<td>{round(endgame.rating)}</td>
<td class="w-0 font-semibold">
<.link navigate={~p"/admin/endgames/#{endgame.id}"}>Show</.link>
</td>
</tr>
</tbody>
</table>
</div>
<.filter_bar <.filter_bar
:if={!@search_query}
selected_themes={@selected_themes} selected_themes={@selected_themes}
theme_query={@theme_query} theme_query={@theme_query}
theme_results={@theme_results} theme_results={@theme_results}
@@ -26,7 +82,7 @@ defmodule ChesstrainerWeb.EndgameLive.Index do
selected_key={@selected_key} selected_key={@selected_key}
/> />
<.grouped_list :if={@groups != []} groups={@groups}> <.grouped_list :if={!@search_query and @groups != []} groups={@groups}>
<:header> <:header>
<tr> <tr>
<th>Key</th> <th>Key</th>
@@ -40,13 +96,22 @@ defmodule ChesstrainerWeb.EndgameLive.Index do
<:row :let={endgame}> <:row :let={endgame}>
<tr id={"endgame-" <> endgame.id}> <tr id={"endgame-" <> endgame.id}>
<td phx-click={JS.navigate(~p"/admin/endgames/#{endgame}")} class="hover:cursor-pointer"> <td
phx-click={JS.navigate(~p"/admin/endgames/#{endgame.id}")}
class="hover:cursor-pointer"
>
{endgame.key} {endgame.key}
</td> </td>
<td phx-click={JS.navigate(~p"/admin/endgames/#{endgame}")} class="hover:cursor-pointer"> <td
phx-click={JS.navigate(~p"/admin/endgames/#{endgame.id}")}
class="hover:cursor-pointer"
>
{endgame.color} {endgame.color}
</td> </td>
<td phx-click={JS.navigate(~p"/admin/endgames/#{endgame}")} class="hover:cursor-pointer"> <td
phx-click={JS.navigate(~p"/admin/endgames/#{endgame.id}")}
class="hover:cursor-pointer"
>
{endgame.result} {endgame.result}
</td> </td>
<td> <td>
@@ -57,14 +122,17 @@ defmodule ChesstrainerWeb.EndgameLive.Index do
</span> </span>
<span :if={endgame.themes == []} class="text-base-content/50">None</span> <span :if={endgame.themes == []} class="text-base-content/50">None</span>
</td> </td>
<td phx-click={JS.navigate(~p"/admin/endgames/#{endgame}")} class="hover:cursor-pointer"> <td
{endgame.rating} phx-click={JS.navigate(~p"/admin/endgames/#{endgame.id}")}
class="hover:cursor-pointer"
>
{round(endgame.rating)}
</td> </td>
<td class="w-0 font-semibold"> <td class="w-0 font-semibold">
<div class="flex gap-4"> <div class="flex gap-4">
<.link navigate={~p"/admin/endgames/#{endgame}"}>Show</.link> <.link navigate={~p"/admin/endgames/#{endgame.id}"}>Show</.link>
<.link navigate={~p"/endgames/#{endgame}/play"}>Play</.link> <.link navigate={~p"/endgames/#{endgame.public_code}/play"}>Play</.link>
<.link navigate={~p"/admin/endgames/#{endgame}/edit"}>Edit</.link> <.link navigate={~p"/admin/endgames/#{endgame.id}/edit"}>Edit</.link>
<.link <.link
phx-click={JS.push("delete", value: %{id: endgame.id})} phx-click={JS.push("delete", value: %{id: endgame.id})}
data-confirm="Are you sure?" data-confirm="Are you sure?"
@@ -77,7 +145,7 @@ defmodule ChesstrainerWeb.EndgameLive.Index do
</:row> </:row>
</.grouped_list> </.grouped_list>
<p :if={@groups == []} class="text-base-content/70"> <p :if={!@search_query and @groups == []} class="text-base-content/70">
No endgames match these filters. No endgames match these filters.
</p> </p>
</Layouts.app> </Layouts.app>
@@ -89,10 +157,37 @@ defmodule ChesstrainerWeb.EndgameLive.Index do
{:ok, {:ok,
socket socket
|> assign(:page_title, "Listing Endgames") |> assign(:page_title, "Listing Endgames")
|> assign(:search_form, to_form(%{"query" => ""}))
|> assign(:search_query, nil)
|> assign(:search_results, [])
|> init_state()} |> init_state()}
end end
@impl true @impl true
def handle_event("endgame_search", %{"query" => query}, socket) do
query = String.trim(query)
case {query, Endgames.search(query)} do
{"", _results} ->
{:noreply, clear_search(socket)}
{_query, [endgame]} ->
{:noreply, push_navigate(socket, to: ~p"/admin/endgames/#{endgame.id}")}
{query, results} ->
{:noreply,
assign(socket,
search_form: to_form(%{"query" => query}),
search_query: query,
search_results: results
)}
end
end
def handle_event("clear_search", _params, socket) do
{:noreply, clear_search(socket)}
end
def handle_event("delete", %{"id" => id}, socket) do def handle_event("delete", %{"id" => id}, socket) do
endgame = Endgames.get_endgame!(id) endgame = Endgames.get_endgame!(id)
{:ok, _} = Endgames.delete_endgame(endgame) {:ok, _} = Endgames.delete_endgame(endgame)
@@ -103,4 +198,12 @@ defmodule ChesstrainerWeb.EndgameLive.Index do
def handle_event(event, params, socket) do def handle_event(event, params, socket) do
handle_filter_event(event, params, socket) handle_filter_event(event, params, socket)
end end
defp clear_search(socket) do
assign(socket,
search_form: to_form(%{"query" => ""}),
search_query: nil,
search_results: []
)
end
end end
+43 -5
View File
@@ -1,8 +1,10 @@
defmodule ChesstrainerWeb.EndgameLive.Play do defmodule ChesstrainerWeb.EndgameLive.Play do
use ChesstrainerWeb, :live_view use ChesstrainerWeb, :live_view
alias Chesstrainer.Attempts
alias Chesstrainer.Endgames alias Chesstrainer.Endgames
alias Chesstrainer.Endgames.Tablebase alias Chesstrainer.Endgames.Tablebase
alias Chesstrainer.Ratings
@impl true @impl true
def render(assigns) do def render(assigns) do
@@ -11,8 +13,12 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
<.header> <.header>
Play endgame {@endgame.key} Play endgame {@endgame.key}
<:subtitle> <:subtitle>
{@endgame.color |> Atom.to_string() |> String.capitalize()} to move · Rating: {@endgame.rating} · Attempts: {@endgame.times_attempted || {@endgame.color |> Atom.to_string() |> String.capitalize()} to move · Rating: {round(
0} · Solved: {@endgame.times_solved || 0} @endgame.rating
)} · Attempts: {@endgame.times_attempted ||
0} · Solved: {@endgame.times_solved || 0}<span :if={@user_rating}> · Your rating: {round(
@user_rating
)}</span>
<p class="text-xs text-gray-500 flex items-center mt-1"> <p class="text-xs text-gray-500 flex items-center mt-1">
<span>FEN: {@endgame.fen}</span> <span>FEN: {@endgame.fen}</span>
<button <button
@@ -172,13 +178,14 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
end end
@impl true @impl true
def mount(%{"id" => id}, _session, socket) do def mount(%{"public_code" => public_code}, _session, socket) do
endgame = Endgames.get_endgame!(id) endgame = Endgames.get_endgame_by_public_code!(public_code)
socket = socket =
socket socket
|> assign(:page_title, "Play endgame") |> assign(:page_title, "Play endgame")
|> assign(:endgame, endgame) |> assign(:endgame, endgame)
|> assign(:user_rating, user_rating(socket.assigns.current_scope))
|> assign(:fen, endgame.fen) |> assign(:fen, endgame.fen)
|> assign(:tablebase, nil) |> assign(:tablebase, nil)
|> assign(:status, :loading) |> assign(:status, :loading)
@@ -658,15 +665,21 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
defp solve_attempt(socket) do defp solve_attempt(socket) do
{:ok, endgame} = Endgames.record_solve(socket.assigns.endgame) {:ok, endgame} = Endgames.record_solve(socket.assigns.endgame)
socket =
socket
|> assign(:endgame, endgame)
|> record_attempt(:solved)
{:noreply, {:noreply,
socket socket
|> assign(:status, :solved) |> assign(:status, :solved)
|> assign(:endgame, endgame)
|> assign(:awaiting_reply, false) |> assign(:awaiting_reply, false)
|> assign(:best_move, nil)} |> assign(:best_move, nil)}
end end
defp fail_attempt(socket) do defp fail_attempt(socket) do
socket = record_attempt(socket, :failed)
{:noreply, {:noreply,
socket socket
|> assign(:status, :failed) |> assign(:status, :failed)
@@ -674,6 +687,31 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
|> assign(:best_move, best_move_text(socket.assigns.tablebase))} |> assign(:best_move, best_move_text(socket.assigns.tablebase))}
end end
defp record_attempt(socket, outcome) do
case Attempts.record_attempt(socket.assigns.current_scope, socket.assigns.endgame, outcome) do
{:ok, attempt} ->
case Ratings.rate_attempt(attempt) do
{:ok, %{user: user, endgame: endgame}} ->
socket
|> assign(:endgame, endgame)
|> assign(:user_rating, user.rating)
{:skipped, _attempt} ->
put_flash(
socket,
:info,
"Replay recorded. Your rating is unchanged because you played this recently."
)
end
_ ->
socket
end
end
defp user_rating(%{user: %{rating: rating}}), do: rating
defp user_rating(_), do: nil
defp best_move_text(tablebase) do defp best_move_text(tablebase) do
san = san =
tablebase tablebase
@@ -32,15 +32,24 @@ defmodule ChesstrainerWeb.EndgameLive.PlayerIndex do
</:header> </:header>
<:row :let={endgame}> <:row :let={endgame}>
<tr id={"endgame-" <> endgame.id}> <tr id={"endgame-" <> endgame.public_code}>
<td phx-click={JS.navigate(~p"/endgames/#{endgame}/play")} class="hover:cursor-pointer"> <td
phx-click={JS.navigate(~p"/endgames/#{endgame.public_code}/play")}
class="hover:cursor-pointer"
>
{endgame.color} {endgame.color}
</td> </td>
<td phx-click={JS.navigate(~p"/endgames/#{endgame}/play")} class="hover:cursor-pointer"> <td
phx-click={JS.navigate(~p"/endgames/#{endgame.public_code}/play")}
class="hover:cursor-pointer"
>
{endgame.result} {endgame.result}
</td> </td>
<td phx-click={JS.navigate(~p"/endgames/#{endgame}/play")} class="hover:cursor-pointer"> <td
{endgame.rating} phx-click={JS.navigate(~p"/endgames/#{endgame.public_code}/play")}
class="hover:cursor-pointer"
>
{round(endgame.rating)}
</td> </td>
<td> <td>
<span :for={theme <- endgame.themes} class="badge badge-sm"> <span :for={theme <- endgame.themes} class="badge badge-sm">
@@ -51,7 +60,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayerIndex do
<span :if={endgame.themes == []} class="text-base-content/50">None</span> <span :if={endgame.themes == []} class="text-base-content/50">None</span>
</td> </td>
<td class="w-0 font-semibold"> <td class="w-0 font-semibold">
<.link navigate={~p"/endgames/#{endgame}/play"}>Play</.link> <.link navigate={~p"/endgames/#{endgame.public_code}/play"}>Play</.link>
</td> </td>
</tr> </tr>
</:row> </:row>
+26 -3
View File
@@ -33,10 +33,10 @@ defmodule ChesstrainerWeb.EndgameLive.Show do
<.button navigate={~p"/admin/endgames"}> <.button navigate={~p"/admin/endgames"}>
<.icon name="hero-arrow-left" /> <.icon name="hero-arrow-left" />
</.button> </.button>
<.button navigate={~p"/endgames/#{@endgame}/play"}> <.button navigate={~p"/endgames/#{@endgame.public_code}/play"}>
<.icon name="hero-play" /> Play (opens trainer) <.icon name="hero-play" /> Play (opens trainer)
</.button> </.button>
<.button variant="primary" navigate={~p"/admin/endgames/#{@endgame}/edit?return_to=show"}> <.button variant="primary" navigate={~p"/admin/endgames/#{@endgame.id}/edit?return_to=show"}>
<.icon name="hero-pencil-square" /> Edit endgame <.icon name="hero-pencil-square" /> Edit endgame
</.button> </.button>
</:actions> </:actions>
@@ -47,8 +47,21 @@ defmodule ChesstrainerWeb.EndgameLive.Show do
<.list> <.list>
<:item title="Fen">{@endgame.fen}</:item> <:item title="Fen">{@endgame.fen}</:item>
<:item title="Key">{@endgame.key}</:item> <:item title="Key">{@endgame.key}</:item>
<:item title="Public code">
<span id="public-code" class="select-all">{@endgame.public_code}</span>
<button
id="copy-public-code"
type="button"
phx-hook=".CopyPublicCode"
data-code={@endgame.public_code}
class="ml-2 inline-flex cursor-pointer items-center"
title="Copy public code"
>
<.icon name="hero-document-duplicate" class="w-3.5 h-3.5" />
</button>
</:item>
<:item title="Color">{@endgame.color}</:item> <:item title="Color">{@endgame.color}</:item>
<:item title="Rating">{@endgame.rating}</:item> <:item title="Rating">{round(@endgame.rating)}</:item>
<:item title="Message">{@endgame.message}</:item> <:item title="Message">{@endgame.message}</:item>
<:item title="Notes">{@endgame.notes}</:item> <:item title="Notes">{@endgame.notes}</:item>
<:item title="Result">{@endgame.result}</:item> <:item title="Result">{@endgame.result}</:item>
@@ -56,6 +69,16 @@ defmodule ChesstrainerWeb.EndgameLive.Show do
<:item title="Attempted">{@endgame.times_attempted}</:item> <:item title="Attempted">{@endgame.times_attempted}</:item>
<:item title="Solved">{@endgame.times_solved}</:item> <:item title="Solved">{@endgame.times_solved}</:item>
</.list> </.list>
<script :type={Phoenix.LiveView.ColocatedHook} name=".CopyPublicCode">
export default {
mounted() {
this.el.addEventListener("click", () => {
navigator.clipboard.writeText(this.el.dataset.code)
})
}
}
</script>
</Layouts.app> </Layouts.app>
""" """
end end
@@ -0,0 +1,77 @@
defmodule ChesstrainerWeb.UserLive.Login do
use ChesstrainerWeb, :live_view
@impl true
def render(assigns) do
~H"""
<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"/users/register"}
class="font-semibold text-brand hover:underline"
phx-no-format
>Sign up</.link> for an account now.
<% end %>
</:subtitle>
</.header>
</div>
<.form
:let={f}
for={@form}
id="login_form_password"
action={~p"/users/log-in"}
phx-submit="submit_password"
phx-trigger-action={@trigger_submit}
>
<.input
readonly={!!@current_scope}
field={f[:email]}
type="text"
label="Email or username"
autocomplete="username"
spellcheck="false"
required
/>
<.input
field={@form[:password]}
type="password"
label="Password"
autocomplete="current-password"
spellcheck="false"
/>
<.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>
"""
end
@impl true
def mount(_params, _session, socket) do
email =
Phoenix.Flash.get(socket.assigns.flash, :email) ||
get_in(socket.assigns, [:current_scope, Access.key(:user), Access.key(:email)])
form = to_form(%{"email" => email}, as: "user")
{:ok, assign(socket, form: form, trigger_submit: false)}
end
@impl true
def handle_event("submit_password", _params, socket) do
{:noreply, assign(socket, :trigger_submit, true)}
end
end
@@ -0,0 +1,104 @@
defmodule ChesstrainerWeb.UserLive.Registration do
use ChesstrainerWeb, :live_view
alias Chesstrainer.Accounts
alias Chesstrainer.Accounts.User
@impl true
def render(assigns) do
~H"""
<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"/users/log-in"} class="font-semibold text-brand hover:underline">
Log in
</.link>
to your account now.
</:subtitle>
</.header>
</div>
<.form for={@form} id="registration_form" phx-submit="save" phx-change="validate">
<.input
field={@form[:username]}
type="text"
label="Username"
autocomplete="username"
spellcheck="false"
required
phx-mounted={JS.focus()}
/>
<.input
field={@form[:email]}
type="email"
label="Email"
autocomplete="email"
spellcheck="false"
required
/>
<.input
field={@form[:password]}
type="password"
label="Password"
autocomplete="new-password"
spellcheck="false"
required
/>
<.input
field={@form[:password_confirmation]}
type="password"
label="Confirm password"
autocomplete="new-password"
spellcheck="false"
required
/>
<.button phx-disable-with="Creating account..." class="btn btn-primary w-full">
Create an account
</.button>
</.form>
</div>
</Layouts.app>
"""
end
@impl true
def mount(_params, _session, %{assigns: %{current_scope: %{user: user}}} = socket)
when not is_nil(user) do
{:ok, redirect(socket, to: ChesstrainerWeb.UserAuth.signed_in_path(socket))}
end
def mount(_params, _session, socket) do
changeset = Accounts.change_user_registration(%User{}, %{}, validate_unique: false)
{:ok, assign_form(socket, changeset), temporary_assigns: [form: nil]}
end
@impl true
def handle_event("save", %{"user" => user_params}, socket) do
case Accounts.register_user(user_params) do
{:ok, _user} ->
{:noreply,
socket
|> put_flash(:info, "Account created successfully. Please log in.")
|> push_navigate(to: ~p"/users/log-in")}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign_form(socket, changeset)}
end
end
def handle_event("validate", %{"user" => user_params}, socket) do
changeset = Accounts.change_user_registration(%User{}, user_params, validate_unique: false)
{:noreply, assign_form(socket, Map.put(changeset, :action, :validate))}
end
defp assign_form(socket, %Ecto.Changeset{} = changeset) do
form = to_form(changeset, as: "user")
assign(socket, form: form)
end
end
@@ -0,0 +1,160 @@
defmodule ChesstrainerWeb.UserLive.Settings do
use ChesstrainerWeb, :live_view
on_mount {ChesstrainerWeb.UserAuth, :require_sudo_mode}
alias Chesstrainer.Accounts
@impl true
def render(assigns) do
~H"""
<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 for={@email_form} id="email_form" phx-submit="update_email" phx-change="validate_email">
<.input
field={@email_form[:email]}
type="email"
label="Email"
autocomplete="username"
spellcheck="false"
required
/>
<.button variant="primary" phx-disable-with="Changing...">Change Email</.button>
</.form>
<div class="divider" />
<.form
for={@password_form}
id="password_form"
action={~p"/users/update-password"}
method="post"
phx-change="validate_password"
phx-submit="update_password"
phx-trigger-action={@trigger_submit}
>
<input
name={@password_form[:email].name}
type="hidden"
id="hidden_user_email"
spellcheck="false"
value={@current_email}
/>
<.input
field={@password_form[:password]}
type="password"
label="New password"
autocomplete="new-password"
spellcheck="false"
required
/>
<.input
field={@password_form[:password_confirmation]}
type="password"
label="Confirm new password"
autocomplete="new-password"
spellcheck="false"
/>
<.button variant="primary" phx-disable-with="Saving...">
Save Password
</.button>
</.form>
</Layouts.app>
"""
end
@impl true
def mount(%{"token" => token}, _session, socket) do
socket =
case Accounts.update_user_email(socket.assigns.current_scope.user, token) do
{:ok, _user} ->
put_flash(socket, :info, "Email changed successfully.")
{:error, _} ->
put_flash(socket, :error, "Email change link is invalid or it has expired.")
end
{:ok, push_navigate(socket, to: ~p"/users/settings")}
end
def mount(_params, _session, socket) do
user = socket.assigns.current_scope.user
email_changeset = Accounts.change_user_email(user, %{}, validate_unique: false)
password_changeset = Accounts.change_user_password(user, %{}, hash_password: false)
socket =
socket
|> assign(:current_email, user.email)
|> assign(:email_form, to_form(email_changeset))
|> assign(:password_form, to_form(password_changeset))
|> assign(:trigger_submit, false)
{:ok, socket}
end
@impl true
def handle_event("validate_email", params, socket) do
%{"user" => user_params} = params
email_form =
socket.assigns.current_scope.user
|> Accounts.change_user_email(user_params, validate_unique: false)
|> Map.put(:action, :validate)
|> to_form()
{:noreply, assign(socket, email_form: email_form)}
end
def handle_event("update_email", params, socket) do
%{"user" => user_params} = params
user = socket.assigns.current_scope.user
true = Accounts.sudo_mode?(user)
case Accounts.change_user_email(user, user_params) do
%{valid?: true} = changeset ->
Accounts.deliver_user_update_email_instructions(
Ecto.Changeset.apply_action!(changeset, :insert),
user.email,
&url(~p"/users/settings/confirm-email/#{&1}")
)
info = "A link to confirm your email change has been sent to the new address."
{:noreply, socket |> put_flash(:info, info)}
changeset ->
{:noreply, assign(socket, :email_form, to_form(changeset, action: :insert))}
end
end
def handle_event("validate_password", params, socket) do
%{"user" => user_params} = params
password_form =
socket.assigns.current_scope.user
|> Accounts.change_user_password(user_params, hash_password: false)
|> Map.put(:action, :validate)
|> to_form()
{:noreply, assign(socket, password_form: password_form)}
end
def handle_event("update_password", params, socket) do
%{"user" => user_params} = params
user = socket.assigns.current_scope.user
true = Accounts.sudo_mode?(user)
case Accounts.change_user_password(user, user_params) do
%{valid?: true} = changeset ->
{:noreply, assign(socket, trigger_submit: true, password_form: to_form(changeset))}
changeset ->
{:noreply, assign(socket, password_form: to_form(changeset, action: :insert))}
end
end
end
+34 -3
View File
@@ -1,6 +1,8 @@
defmodule ChesstrainerWeb.Router do defmodule ChesstrainerWeb.Router do
use ChesstrainerWeb, :router use ChesstrainerWeb, :router
import ChesstrainerWeb.UserAuth
pipeline :browser do pipeline :browser do
plug :accepts, ["html"] plug :accepts, ["html"]
plug :fetch_session plug :fetch_session
@@ -8,6 +10,7 @@ defmodule ChesstrainerWeb.Router do
plug :put_root_layout, html: {ChesstrainerWeb.Layouts, :root} plug :put_root_layout, html: {ChesstrainerWeb.Layouts, :root}
plug :protect_from_forgery plug :protect_from_forgery
plug :put_secure_browser_headers plug :put_secure_browser_headers
plug :fetch_current_scope_for_user
end end
pipeline :api do pipeline :api do
@@ -22,13 +25,13 @@ defmodule ChesstrainerWeb.Router do
live "/chess-test", ChessTestLive live "/chess-test", ChessTestLive
live "/endgames", EndgameLive.PlayerIndex, :index live "/endgames", EndgameLive.PlayerIndex, :index
live "/endgames/:id/play", EndgameLive.Play, :play
end end
scope "/admin", ChesstrainerWeb do scope "/admin", ChesstrainerWeb do
pipe_through :browser pipe_through [:browser, :require_admin_user]
live_session :endgames do live_session :endgames,
on_mount: [{ChesstrainerWeb.UserAuth, :require_admin}] do
live "/endgames", EndgameLive.Index, :index live "/endgames", EndgameLive.Index, :index
live "/endgames/new", EndgameLive.Form, :new live "/endgames/new", EndgameLive.Form, :new
live "/endgames/:id", EndgameLive.Show, :show live "/endgames/:id", EndgameLive.Show, :show
@@ -57,4 +60,32 @@ defmodule ChesstrainerWeb.Router do
forward "/mailbox", Plug.Swoosh.MailboxPreview forward "/mailbox", Plug.Swoosh.MailboxPreview
end end
end end
## Authentication routes
scope "/", ChesstrainerWeb do
pipe_through [:browser, :require_authenticated_user]
live_session :require_authenticated_user,
on_mount: [{ChesstrainerWeb.UserAuth, :require_authenticated}] do
live "/users/settings", UserLive.Settings, :edit
live "/users/settings/confirm-email/:token", UserLive.Settings, :confirm_email
end
post "/users/update-password", UserSessionController, :update_password
end
scope "/", ChesstrainerWeb do
pipe_through [:browser]
live_session :current_user,
on_mount: [{ChesstrainerWeb.UserAuth, :mount_current_scope}] do
live "/endgames/:public_code/play", EndgameLive.Play, :play
live "/users/register", UserLive.Registration, :new
live "/users/log-in", UserLive.Login, :new
end
post "/users/log-in", UserSessionController, :create
delete "/users/log-out", UserSessionController, :delete
end
end end
+339
View File
@@ -0,0 +1,339 @@
defmodule ChesstrainerWeb.UserAuth do
use ChesstrainerWeb, :verified_routes
import Plug.Conn
import Phoenix.Controller
alias Chesstrainer.Accounts
alias Chesstrainer.Accounts.Role
alias Chesstrainer.Accounts.Scope
# Make the remember me cookie valid for 14 days. This should match
# the session validity setting in UserToken.
@max_cookie_age_in_days 14
@remember_me_cookie "_chesstrainer_web_user_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 user in.
Redirects to the session's `:user_return_to` path
or falls back to the `signed_in_path/1`.
"""
def log_in_user(conn, user, params \\ %{}) do
user_return_to = get_session(conn, :user_return_to)
conn
|> create_or_extend_session(user, params)
|> redirect(to: user_return_to || signed_in_path(conn))
end
@doc """
Logs the user out.
It clears all session data for safety. See renew_session.
"""
def log_out_user(conn) do
user_token = get_session(conn, :user_token)
user_token && Accounts.delete_user_session_token(user_token)
if live_socket_id = get_session(conn, :live_socket_id) do
ChesstrainerWeb.Endpoint.broadcast(live_socket_id, "disconnect", %{})
end
conn
|> renew_session(nil)
|> delete_resp_cookie(@remember_me_cookie, @remember_me_options)
|> redirect(to: ~p"/")
end
@doc """
Authenticates the user 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_user(conn, _opts) do
with {token, conn} <- ensure_user_token(conn),
{user, token_inserted_at} <- Accounts.get_user_by_session_token(token) do
conn
|> assign(:current_scope, Scope.for_user(user))
|> maybe_reissue_user_session_token(user, token_inserted_at)
else
nil -> assign(conn, :current_scope, Scope.for_user(nil))
end
end
defp ensure_user_token(conn) do
if token = get_session(conn, :user_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(:user_remember_me, true)}
else
nil
end
end
end
# Reissue the session token if it is older than the configured reissue age.
defp maybe_reissue_user_session_token(conn, user, 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, user, %{})
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, user, params) do
token = Accounts.generate_user_session_token(user)
remember_me = get_session(conn, :user_remember_me)
conn
|> renew_session(user)
|> put_token_in_session(token)
|> maybe_write_remember_me_cookie(token, params, remember_me)
end
# Do not renew session if the user is already logged in
# to prevent CSRF errors or data being lost in tabs that are still open
defp renew_session(conn, user) when conn.assigns.current_scope.user.id == user.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, _user) 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, _user) 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(:user_remember_me, true)
|> put_resp_cookie(@remember_me_cookie, token, @remember_me_options)
end
defp put_token_in_session(conn, token) do
conn
|> put_session(:user_token, token)
|> put_session(:live_socket_id, user_session_topic(token))
end
@doc """
Disconnects existing sockets for the given tokens.
"""
def disconnect_sessions(tokens) do
Enum.each(tokens, fn %{token: token} ->
ChesstrainerWeb.Endpoint.broadcast(user_session_topic(token), "disconnect", %{})
end)
end
defp user_session_topic(token), do: "users_sessions:#{Base.url_encode64(token)}"
@doc """
Handles mounting and authenticating the current_scope in LiveViews.
## `on_mount` arguments
* `:mount_current_scope` - Assigns current_scope
to socket assigns based on user_token, or nil if
there's no user_token or no matching user.
* `:require_authenticated` - Authenticates the user from the session,
and assigns the current_scope to socket assigns based
on user_token.
Redirects to login page if there's no logged user.
## Examples
Use the `on_mount` lifecycle macro in LiveViews to mount or authenticate
the `current_scope`:
defmodule ChesstrainerWeb.PageLive do
use ChesstrainerWeb, :live_view
on_mount {ChesstrainerWeb.UserAuth, :mount_current_scope}
...
end
Or use the `live_session` of your router to invoke the on_mount callback:
live_session :authenticated, on_mount: [{ChesstrainerWeb.UserAuth, :require_authenticated}] do
live "/profile", ProfileLive, :index
end
"""
def on_mount(:mount_current_scope, _params, session, socket) do
{:cont, mount_current_scope(socket, session)}
end
def on_mount(:require_authenticated, _params, session, socket) do
socket = mount_current_scope(socket, session)
if socket.assigns.current_scope && socket.assigns.current_scope.user do
{:cont, socket}
else
socket =
socket
|> Phoenix.LiveView.put_flash(:error, "You must log in to access this page.")
|> Phoenix.LiveView.redirect(to: ~p"/users/log-in")
{:halt, socket}
end
end
def on_mount(:require_admin, _params, session, socket) do
socket = mount_current_scope(socket, session)
cond do
is_nil(socket.assigns.current_scope) ->
socket =
socket
|> Phoenix.LiveView.put_flash(:error, "You must log in to access this page.")
|> Phoenix.LiveView.redirect(to: ~p"/users/log-in")
{:halt, socket}
Role.admin?(socket.assigns.current_scope.user.role) ->
{:cont, socket}
true ->
socket =
socket
|> Phoenix.LiveView.put_flash(:error, "You are not authorized to access this page.")
|> Phoenix.LiveView.redirect(to: ~p"/")
{:halt, socket}
end
end
def on_mount(:require_sudo_mode, _params, session, socket) do
socket = mount_current_scope(socket, session)
if Accounts.sudo_mode?(socket.assigns.current_scope.user, -10) do
{:cont, socket}
else
socket =
socket
|> Phoenix.LiveView.put_flash(:error, "You must re-authenticate to access this page.")
|> Phoenix.LiveView.redirect(to: ~p"/users/log-in")
{:halt, socket}
end
end
defp mount_current_scope(socket, session) do
Phoenix.Component.assign_new(socket, :current_scope, fn ->
{user, _} =
if user_token = session["user_token"] do
Accounts.get_user_by_session_token(user_token)
end || {nil, nil}
Scope.for_user(user)
end)
end
@doc "Returns the path to redirect to after log in."
# the user was already logged in, redirect to settings
def signed_in_path(%Plug.Conn{assigns: %{current_scope: %Scope{user: %Accounts.User{}}}}) do
~p"/users/settings"
end
def signed_in_path(_), do: ~p"/"
@doc """
Plug for routes that require the user to be authenticated.
"""
def require_authenticated_user(conn, _opts) do
if conn.assigns.current_scope && conn.assigns.current_scope.user do
conn
else
conn
|> put_flash(:error, "You must log in to access this page.")
|> maybe_store_return_to()
|> redirect(to: ~p"/users/log-in")
|> halt()
end
end
@doc """
Plug for routes that require an admin-or-above role.
Unauthenticated visitors are sent to log in; authenticated users without the
rank are sent home with a flash.
"""
def require_admin_user(conn, _opts) do
cond do
is_nil(conn.assigns.current_scope) ->
conn
|> put_flash(:error, "You must log in to access this page.")
|> maybe_store_return_to()
|> redirect(to: ~p"/users/log-in")
|> halt()
Role.admin?(conn.assigns.current_scope.user.role) ->
conn
true ->
conn
|> put_flash(:error, "You are not authorized to access this page.")
|> redirect(to: ~p"/")
|> halt()
end
end
defp maybe_store_return_to(%{method: "GET"} = conn) do
put_session(conn, :user_return_to, current_path(conn))
end
defp maybe_store_return_to(conn), do: conn
end
+56
View File
@@ -0,0 +1,56 @@
defmodule Mix.Tasks.Accounts.Promote do
use Mix.Task
@shortdoc "Sets a user's authority role"
@moduledoc """
Sets a user's authority role.
mix accounts.promote <email-or-username> <role>
Roles, from least to most authority: `member`, `moderator`, `admin`,
`super_admin`.
Role changes are deliberately CLI-only for now; there is no admin UI.
"""
@impl Mix.Task
def run(args) do
Mix.Task.run("app.start")
case args do
[login, role] ->
set_role(login, parse_role(role))
_ ->
Mix.raise("Usage: mix accounts.promote <email-or-username> <role>")
end
end
defp set_role(login, role) do
case Chesstrainer.Accounts.get_user_by_login(login) do
nil ->
Mix.raise("No user found with email or username #{inspect(login)}")
user ->
case Chesstrainer.Accounts.update_user_role(user, role) do
{:ok, updated} ->
Mix.shell().info("Set #{updated.username} (#{updated.email}) role to #{updated.role}")
{:error, changeset} ->
Mix.raise("Could not update role: #{inspect(changeset.errors)}")
end
end
end
defp parse_role(role) do
case Enum.find(Chesstrainer.Accounts.Role.values(), &(Atom.to_string(&1) == role)) do
nil ->
valid = Chesstrainer.Accounts.Role.values() |> Enum.map_join(", ", &Atom.to_string/1)
Mix.raise("Unknown role #{inspect(role)}. Use one of: #{valid}")
role ->
role
end
end
end
+4 -1
View File
@@ -10,6 +10,7 @@ defmodule Chesstrainer.MixProject do
start_permanent: Mix.env() == :prod, start_permanent: Mix.env() == :prod,
aliases: aliases(), aliases: aliases(),
deps: deps(), deps: deps(),
dialyzer: [plt_add_apps: [:mix]],
compilers: [:phoenix_live_view] ++ Mix.compilers(), compilers: [:phoenix_live_view] ++ Mix.compilers(),
listeners: [Phoenix.CodeReloader] listeners: [Phoenix.CodeReloader]
] ]
@@ -40,6 +41,7 @@ defmodule Chesstrainer.MixProject do
# Type `mix help deps` for examples and options. # Type `mix help deps` for examples and options.
defp deps do defp deps do
[ [
{:bcrypt_elixir, "~> 3.0"},
{:phoenix, "~> 1.8.8"}, {:phoenix, "~> 1.8.8"},
{:phoenix_ecto, "~> 4.5"}, {:phoenix_ecto, "~> 4.5"},
{:ecto_sql, "~> 3.13"}, {:ecto_sql, "~> 3.13"},
@@ -68,7 +70,8 @@ defmodule Chesstrainer.MixProject do
{:bandit, "~> 1.5"}, {:bandit, "~> 1.5"},
{:chex, git: "https://github.com/therealowenrees/chex.git", tag: "v0.2.0-alpha.2"}, {:chex, git: "https://github.com/therealowenrees/chex.git", tag: "v0.2.0-alpha.2"},
{:rustler, "~> 0.38", runtime: false}, {:rustler, "~> 0.38", runtime: false},
{:dialyxir, "~> 1.4", only: [:dev, :test], runtime: false} {:dialyxir, "~> 1.4", only: [:dev, :test], runtime: false},
{:glicko, "~> 0.8.1"}
] ]
end end
+3
View File
@@ -1,7 +1,9 @@
%{ %{
"bandit": {:hex, :bandit, "1.12.0", "6c5214daa2469644ac4ab0113b98abc24f75e348378e6a974c6343b3e5da22ef", [:mix], [{:hpax, "~> 1.0", [hex: :hpax, repo: "hexpm", optional: false]}, {:plug, "~> 1.18", [hex: :plug, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}, {:thousand_island, "~> 1.5", [hex: :thousand_island, repo: "hexpm", optional: false]}, {:websock, "~> 0.5", [hex: :websock, repo: "hexpm", optional: false]}], "hexpm", "45dac82dc86f45cf4a196dee9cc5a8b791d9c9469d996055f055e6ee36c66e20"}, "bandit": {:hex, :bandit, "1.12.0", "6c5214daa2469644ac4ab0113b98abc24f75e348378e6a974c6343b3e5da22ef", [:mix], [{:hpax, "~> 1.0", [hex: :hpax, repo: "hexpm", optional: false]}, {:plug, "~> 1.18", [hex: :plug, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}, {:thousand_island, "~> 1.5", [hex: :thousand_island, repo: "hexpm", optional: false]}, {:websock, "~> 0.5", [hex: :websock, repo: "hexpm", optional: false]}], "hexpm", "45dac82dc86f45cf4a196dee9cc5a8b791d9c9469d996055f055e6ee36c66e20"},
"bcrypt_elixir": {:hex, :bcrypt_elixir, "3.3.2", "d50091e3c9492d73e17fc1e1619a9b09d6a5ef99160eb4d736926fd475a16ca3", [:make, :mix], [{:comeonin, "~> 5.3", [hex: :comeonin, repo: "hexpm", optional: false]}, {:elixir_make, "~> 0.6", [hex: :elixir_make, repo: "hexpm", optional: false]}], "hexpm", "471be5151874ae7931911057d1467d908955f93554f7a6cd1b7d804cac8cef53"},
"cc_precompiler": {:hex, :cc_precompiler, "0.1.11", "8c844d0b9fb98a3edea067f94f616b3f6b29b959b6b3bf25fee94ffe34364768", [:mix], [{:elixir_make, "~> 0.7", [hex: :elixir_make, repo: "hexpm", optional: false]}], "hexpm", "3427232caf0835f94680e5bcf082408a70b48ad68a5f5c0b02a3bea9f3a075b9"}, "cc_precompiler": {:hex, :cc_precompiler, "0.1.11", "8c844d0b9fb98a3edea067f94f616b3f6b29b959b6b3bf25fee94ffe34364768", [:mix], [{:elixir_make, "~> 0.7", [hex: :elixir_make, repo: "hexpm", optional: false]}], "hexpm", "3427232caf0835f94680e5bcf082408a70b48ad68a5f5c0b02a3bea9f3a075b9"},
"chex": {:git, "https://github.com/therealowenrees/chex.git", "655b5c3df6c5297689d7872bbce1e86c6c629d26", [tag: "v0.2.0-alpha.2"]}, "chex": {:git, "https://github.com/therealowenrees/chex.git", "655b5c3df6c5297689d7872bbce1e86c6c629d26", [tag: "v0.2.0-alpha.2"]},
"comeonin": {:hex, :comeonin, "5.5.1", "5113e5f3800799787de08a6e0db307133850e635d34e9fab23c70b6501669510", [:mix], [], "hexpm", "65aac8f19938145377cee73973f192c5645873dcf550a8a6b18187d17c13ccdb"},
"db_connection": {:hex, :db_connection, "2.10.1", "d5465f6bcc125c1b8981c1dbf23c193ca16f446ec0b25832dc174f74f18be510", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "18ed94c6e627b4bf452dbd4df61b69a35a1e768525140bc1917b7a685026a6a3"}, "db_connection": {:hex, :db_connection, "2.10.1", "d5465f6bcc125c1b8981c1dbf23c193ca16f446ec0b25832dc174f74f18be510", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "18ed94c6e627b4bf452dbd4df61b69a35a1e768525140bc1917b7a685026a6a3"},
"decimal": {:hex, :decimal, "3.1.1", "430d87b04011ce6cbd4fd205be758311a81f87d552d40904abd00f015935b1d0", [:mix], [], "hexpm", "c5f25f2ced74a0587d03e6023f595db8e924c9d3922c8c8ffd9edfc4498cf1f6"}, "decimal": {:hex, :decimal, "3.1.1", "430d87b04011ce6cbd4fd205be758311a81f87d552d40904abd00f015935b1d0", [:mix], [], "hexpm", "c5f25f2ced74a0587d03e6023f595db8e924c9d3922c8c8ffd9edfc4498cf1f6"},
"dialyxir": {:hex, :dialyxir, "1.4.8", "7ef671a8aff9948b091d8c30f09467fbb16e77305cda451bce48109a0f5e021c", [:mix], [{:erlex, ">= 0.2.8", [hex: :erlex, repo: "hexpm", optional: false]}], "hexpm", "cbd5a851571e5dfeb32aaf2e840bfa98b7864cb3071bf2ef5d95d1276b12e072"}, "dialyxir": {:hex, :dialyxir, "1.4.8", "7ef671a8aff9948b091d8c30f09467fbb16e77305cda451bce48109a0f5e021c", [:mix], [{:erlex, ">= 0.2.8", [hex: :erlex, repo: "hexpm", optional: false]}], "hexpm", "cbd5a851571e5dfeb32aaf2e840bfa98b7864cb3071bf2ef5d95d1276b12e072"},
@@ -16,6 +18,7 @@
"finch": {:hex, :finch, "0.23.0", "e3f9287ac25a8832f848b144c2b57346aac65b205e2e0629a52adfe6507fd837", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mint, "~> 1.8", [hex: :mint, repo: "hexpm", optional: false]}, {:nimble_options, "~> 0.4 or ~> 1.0", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 1.1", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "80e58d3f936f57e3fdf404f83a3642897ae6d9fb642934e46da4d8fe761b99d5"}, "finch": {:hex, :finch, "0.23.0", "e3f9287ac25a8832f848b144c2b57346aac65b205e2e0629a52adfe6507fd837", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mint, "~> 1.8", [hex: :mint, repo: "hexpm", optional: false]}, {:nimble_options, "~> 0.4 or ~> 1.0", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 1.1", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "80e58d3f936f57e3fdf404f83a3642897ae6d9fb642934e46da4d8fe761b99d5"},
"fine": {:hex, :fine, "0.1.6", "4bf7151493443c454aac9f2fa2f34f5fefd0346a83fb5586a016c4a135c63247", [:mix], [], "hexpm", "5638eb4495488e885ebec167fa57973e5c35e1a50c344eb7666c90ec1c4e3b12"}, "fine": {:hex, :fine, "0.1.6", "4bf7151493443c454aac9f2fa2f34f5fefd0346a83fb5586a016c4a135c63247", [:mix], [], "hexpm", "5638eb4495488e885ebec167fa57973e5c35e1a50c344eb7666c90ec1c4e3b12"},
"gettext": {:hex, :gettext, "1.0.2", "5457e1fd3f4abe47b0e13ff85086aabae760497a3497909b8473e0acee57673b", [:mix], [{:expo, "~> 0.5.1 or ~> 1.0", [hex: :expo, repo: "hexpm", optional: false]}], "hexpm", "eab805501886802071ad290714515c8c4a17196ea76e5afc9d06ca85fb1bfeb3"}, "gettext": {:hex, :gettext, "1.0.2", "5457e1fd3f4abe47b0e13ff85086aabae760497a3497909b8473e0acee57673b", [:mix], [{:expo, "~> 0.5.1 or ~> 1.0", [hex: :expo, repo: "hexpm", optional: false]}], "hexpm", "eab805501886802071ad290714515c8c4a17196ea76e5afc9d06ca85fb1bfeb3"},
"glicko": {:hex, :glicko, "0.8.1", "3f038a9b1022116d19e33f03b95641d8a199882d718592f9b03bbdc63d55215c", [:mix], [], "hexpm", "86dc0c86f3ef442d8c0b977d377a8aed50bc732ebf4582eb1bf19b87d7bd5b1c"},
"heroicons": {:git, "https://github.com/tailwindlabs/heroicons.git", "0435d4ca364a608cc75e2f8683d374e55abbae26", [tag: "v2.2.0", sparse: "optimized", depth: 1]}, "heroicons": {:git, "https://github.com/tailwindlabs/heroicons.git", "0435d4ca364a608cc75e2f8683d374e55abbae26", [tag: "v2.2.0", sparse: "optimized", depth: 1]},
"hpax": {:hex, :hpax, "1.0.3", "ed67ef51ad4df91e75cc6a1494f851850c0bd98ebc0be6e81b026e765ee535aa", [:mix], [], "hexpm", "8eab6e1cfa8d5918c2ce4ba43588e894af35dbd8e91e6e55c817bca5847df34a"}, "hpax": {:hex, :hpax, "1.0.3", "ed67ef51ad4df91e75cc6a1494f851850c0bd98ebc0be6e81b026e765ee535aa", [:mix], [], "hexpm", "8eab6e1cfa8d5918c2ce4ba43588e894af35dbd8e91e6e55c817bca5847df34a"},
"idna": {:hex, :idna, "7.1.0", "1067a13043538129602d2f2ce6899d8713125c7d19734aa557ce2e3ea55bd4f1", [:rebar3], [], "hexpm", "6ae959a025bf36df61a8cab8508d9654891b5426a84c44d82deaffd6ddf8c71f"}, "idna": {:hex, :idna, "7.1.0", "1067a13043538129602d2f2ce6899d8713125c7d19734aa557ce2e3ea55bd4f1", [:rebar3], [], "hexpm", "6ae959a025bf36df61a8cab8508d9654891b5426a84c44d82deaffd6ddf8c71f"},
@@ -0,0 +1,36 @@
defmodule Chesstrainer.Repo.Migrations.CreateUsersAuthTables do
use Ecto.Migration
def change do
execute "CREATE EXTENSION IF NOT EXISTS citext", ""
create table(:users, primary_key: false) do
add :id, :binary_id, primary_key: true
add :email, :citext, null: false
add :username, :citext, null: false
add :hashed_password, :string
add :role, :string, null: false, default: "member"
add :plan, :string, null: false, default: "free"
add :confirmed_at, :utc_datetime
timestamps(type: :utc_datetime)
end
create unique_index(:users, [:email])
create unique_index(:users, [:username])
create table(:users_tokens, primary_key: false) do
add :id, :binary_id, primary_key: true
add :user_id, references(:users, type: :binary_id, on_delete: :delete_all), null: false
add :token, :binary, null: false
add :context, :string, null: false
add :sent_to, :string
add :authenticated_at, :utc_datetime
timestamps(type: :utc_datetime, updated_at: false)
end
create index(:users_tokens, [:user_id])
create unique_index(:users_tokens, [:context, :token])
end
end
@@ -0,0 +1,25 @@
defmodule Chesstrainer.Repo.Migrations.CreateAttempts do
use Ecto.Migration
def change do
create table(:attempts, primary_key: false) do
add :id, :binary_id, primary_key: true
add :user_id, references(:users, type: :binary_id, on_delete: :delete_all), null: false
add :endgame_id, references(:endgames, type: :binary_id, on_delete: :delete_all),
null: false
add :outcome, :string, null: false
add :rated_at, :utc_datetime
timestamps(type: :utc_datetime)
end
# Independent foreign-key indexes so cascade deletes stay cheap.
create index(:attempts, [:user_id])
create index(:attempts, [:endgame_id])
# Rating-window lookup: the latest rated attempt for a user/endgame pair.
create index(:attempts, [:user_id, :endgame_id, :rated_at], where: "rated_at IS NOT NULL")
end
end
@@ -0,0 +1,15 @@
defmodule Chesstrainer.Repo.Migrations.AddRatingsToUsersAndEndgames do
use Ecto.Migration
def change do
alter table(:endgames) do
modify :rating, :float, default: 1500.0
modify :rating_deviation, :float, default: 350.0
end
alter table(:users) do
add :rating, :float, null: false, default: 1500.0
add :rating_deviation, :float, null: false, default: 350.0
end
end
end
@@ -0,0 +1,47 @@
defmodule Chesstrainer.Repo.Migrations.AddPublicCodeToEndgames do
use Ecto.Migration
@alphabet ~c"0123456789abcdefghjkmnpqrstvwxyz"
@length 10
def up do
alter table(:endgames) do
add :public_code, :string
end
flush()
repo().query!("SELECT id FROM endgames").rows
|> Enum.reduce(MapSet.new(), fn [id], used ->
code = Stream.repeatedly(&generate_code/0) |> Enum.find(&(not MapSet.member?(used, &1)))
repo().query!("UPDATE endgames SET public_code = $1 WHERE id = $2", [code, id])
MapSet.put(used, code)
end)
alter table(:endgames) do
modify :public_code, :string, null: false
end
create unique_index(:endgames, [:public_code])
end
def down do
drop unique_index(:endgames, [:public_code])
alter table(:endgames) do
remove :public_code
end
end
# Inlined rather than calling the schema, so the migration stays frozen even
# if the app's generator changes. `rem(byte, 32)` is unbiased: 256 = 8 * 32.
defp generate_code do
@length
|> :crypto.strong_rand_bytes()
|> :binary.bin_to_list()
|> Enum.map(fn byte -> Enum.at(@alphabet, rem(byte, length(@alphabet))) end)
|> List.to_string()
end
end
+1
View File
@@ -34,6 +34,7 @@ Repo.insert_all(
endgame endgame
|> Map.put(:fen, fen) |> Map.put(:fen, fen)
|> Map.put(:id, Ecto.UUID.generate()) |> Map.put(:id, Ecto.UUID.generate())
|> Map.put(:public_code, Endgame.generate_public_code())
|> Map.put(:key, key) |> Map.put(:key, key)
|> Map.merge(%{inserted_at: now, updated_at: now}) |> Map.merge(%{inserted_at: now, updated_at: now})
end), end),
+36
View File
@@ -0,0 +1,36 @@
defmodule Chesstrainer.Accounts.RoleTest do
use ExUnit.Case, async: true
alias Chesstrainer.Accounts.Role
test "values/0 returns roles from least to most authority" do
assert Role.values() == [:member, :moderator, :admin, :super_admin]
end
test "rank/1 orders roles" do
assert Role.rank(:member) < Role.rank(:moderator)
assert Role.rank(:moderator) < Role.rank(:admin)
assert Role.rank(:admin) < Role.rank(:super_admin)
end
test "at_least?/2 compares ranks" do
assert Role.at_least?(:admin, :admin)
assert Role.at_least?(:super_admin, :admin)
assert Role.at_least?(:moderator, :member)
refute Role.at_least?(:moderator, :admin)
refute Role.at_least?(:member, :moderator)
end
test "at_least?/2 is false when there is no valid role" do
refute Role.at_least?(nil, :member)
refute Role.at_least?(:unknown, :member)
end
test "admin?/1 is true only for admin and above" do
assert Role.admin?(:admin)
assert Role.admin?(:super_admin)
refute Role.admin?(:moderator)
refute Role.admin?(:member)
refute Role.admin?(nil)
end
end
+449
View File
@@ -0,0 +1,449 @@
defmodule Chesstrainer.AccountsTest do
use Chesstrainer.DataCase
alias Chesstrainer.Accounts
import Chesstrainer.AccountsFixtures
alias Chesstrainer.Accounts.{User, UserToken}
describe "get_user_by_email/1" do
test "does not return the user if the email does not exist" do
refute Accounts.get_user_by_email("unknown@example.com")
end
test "returns the user if the email exists" do
%{id: id} = user = user_fixture()
assert %User{id: ^id} = Accounts.get_user_by_email(user.email)
end
end
describe "get_user_by_login/1" do
test "returns the user by email" do
%{id: id} = user = user_fixture()
assert %User{id: ^id} = Accounts.get_user_by_login(user.email)
end
test "returns the user by username" do
%{id: id} = user = user_fixture()
assert %User{id: ^id} = Accounts.get_user_by_login(user.username)
end
test "ignores case for both email and username" do
user = user_fixture()
assert %User{id: id} = Accounts.get_user_by_login(String.upcase(user.email))
assert user.id == id
assert %User{id: ^id} = Accounts.get_user_by_login(String.upcase(user.username))
end
test "does not return the user if neither identifier exists" do
refute Accounts.get_user_by_login("unknown")
end
end
describe "get_user_by_login_and_password/2" do
test "does not return the user if the login does not exist" do
refute Accounts.get_user_by_login_and_password("unknown@example.com", "hello world!")
end
test "does not return the user if the password is not valid" do
user = user_fixture() |> set_password()
refute Accounts.get_user_by_login_and_password(user.email, "invalid")
end
test "returns the user if the email and password are valid" do
%{id: id} = user = user_fixture() |> set_password()
assert %User{id: ^id} =
Accounts.get_user_by_login_and_password(user.email, valid_user_password())
end
test "returns the user if the username and password are valid" do
%{id: id} = user = user_fixture() |> set_password()
assert %User{id: ^id} =
Accounts.get_user_by_login_and_password(user.username, valid_user_password())
end
end
describe "get_user!/1" do
test "raises if id is invalid" do
assert_raise Ecto.NoResultsError, fn ->
Accounts.get_user!("11111111-1111-1111-1111-111111111111")
end
end
test "returns the user with the given id" do
%{id: id} = user = user_fixture()
assert %User{id: ^id} = Accounts.get_user!(user.id)
end
end
describe "register_user/1" do
test "requires email, username and password to be set" do
{:error, changeset} = Accounts.register_user(%{})
assert %{
email: ["can't be blank"],
username: ["can't be blank"],
password: ["can't be blank"]
} = errors_on(changeset)
end
test "validates email when given" do
{:error, changeset} = Accounts.register_user(valid_user_attributes(email: "not valid"))
assert %{email: ["must have the @ sign and no spaces"]} = errors_on(changeset)
end
test "validates maximum values for email for security" do
too_long = String.duplicate("db", 100)
{:error, changeset} =
Accounts.register_user(valid_user_attributes(email: too_long))
assert "should be at most 160 character(s)" in errors_on(changeset).email
end
test "validates username format" do
{:error, changeset} =
Accounts.register_user(valid_user_attributes(username: "no spaces allowed"))
assert "only letters, numbers and underscores" in errors_on(changeset).username
end
test "validates username length" do
{:error, changeset} =
Accounts.register_user(valid_user_attributes(username: "ab"))
assert "should be at least 3 character(s)" in errors_on(changeset).username
{:error, changeset} =
Accounts.register_user(valid_user_attributes(username: String.duplicate("a", 31)))
assert "should be at most 30 character(s)" in errors_on(changeset).username
end
test "validates password confirmation when given" do
{:error, changeset} =
Accounts.register_user(valid_user_attributes(password_confirmation: "something else"))
assert %{password_confirmation: ["does not match password"]} = errors_on(changeset)
end
test "validates email uniqueness" do
%{email: email} = user_fixture()
{:error, changeset} = Accounts.register_user(valid_user_attributes(email: email))
assert "has already been taken" in errors_on(changeset).email
# Now try with the uppercased email too, to check that email case is ignored.
{:error, changeset} =
Accounts.register_user(valid_user_attributes(email: String.upcase(email)))
assert "has already been taken" in errors_on(changeset).email
end
test "validates username uniqueness, ignoring case" do
%{username: username} = user_fixture()
{:error, changeset} =
Accounts.register_user(valid_user_attributes(username: username))
assert "has already been taken" in errors_on(changeset).username
{:error, changeset} =
Accounts.register_user(valid_user_attributes(username: String.upcase(username)))
assert "has already been taken" in errors_on(changeset).username
end
test "registers users with a password, a confirmed account and default access" do
email = unique_user_email()
username = unique_username()
{:ok, user} =
Accounts.register_user(valid_user_attributes(email: email, username: username))
assert user.email == email
assert user.username == username
assert is_binary(user.hashed_password)
assert is_nil(user.password)
assert user.confirmed_at
assert user.role == :member
assert user.plan == :free
end
end
describe "change_user_registration/3" do
test "returns a user changeset" do
assert %Ecto.Changeset{} = changeset = Accounts.change_user_registration(%User{})
assert Enum.sort(changeset.required) == [:email, :password, :username]
end
test "does not cast the role or plan" do
changeset =
Accounts.change_user_registration(%User{}, %{
email: unique_user_email(),
username: unique_username(),
password: valid_user_password(),
role: :super_admin,
plan: :premium
})
refute Map.has_key?(changeset.changes, :role)
refute Map.has_key?(changeset.changes, :plan)
end
end
describe "update_user_role/2" do
test "changes the user's role" do
user = user_fixture()
assert {:ok, %User{role: :admin}} = Accounts.update_user_role(user, :admin)
end
test "rejects a role that is not in the enum" do
user = user_fixture()
assert {:error, changeset} = Accounts.update_user_role(user, :wizard)
assert %{role: ["is invalid"]} = errors_on(changeset)
end
end
describe "sudo_mode?/2" do
test "validates the authenticated_at time" do
now = DateTime.utc_now()
assert Accounts.sudo_mode?(%User{authenticated_at: DateTime.utc_now()})
assert Accounts.sudo_mode?(%User{authenticated_at: DateTime.add(now, -19, :minute)})
refute Accounts.sudo_mode?(%User{authenticated_at: DateTime.add(now, -21, :minute)})
# minute override
refute Accounts.sudo_mode?(
%User{authenticated_at: DateTime.add(now, -11, :minute)},
-10
)
# not authenticated
refute Accounts.sudo_mode?(%User{})
end
end
describe "change_user_email/3" do
test "returns a user changeset" do
assert %Ecto.Changeset{} = changeset = Accounts.change_user_email(%User{})
assert changeset.required == [:email]
end
end
describe "deliver_user_update_email_instructions/3" do
setup do
%{user: user_fixture()}
end
test "sends token through notification", %{user: user} do
token =
extract_user_token(fn url ->
Accounts.deliver_user_update_email_instructions(user, "current@example.com", url)
end)
{:ok, token} = Base.url_decode64(token, padding: false)
assert user_token = Repo.get_by(UserToken, token: :crypto.hash(:sha256, token))
assert user_token.user_id == user.id
assert user_token.sent_to == user.email
assert user_token.context == "change:current@example.com"
end
end
describe "update_user_email/2" do
setup do
user = user_fixture()
email = unique_user_email()
token =
extract_user_token(fn url ->
Accounts.deliver_user_update_email_instructions(%{user | email: email}, user.email, url)
end)
%{user: user, token: token, email: email}
end
test "updates the email with a valid token", %{user: user, token: token, email: email} do
assert {:ok, %{email: ^email}} = Accounts.update_user_email(user, token)
changed_user = Repo.get!(User, user.id)
assert changed_user.email != user.email
assert changed_user.email == email
refute Repo.get_by(UserToken, user_id: user.id)
end
test "does not update email with invalid token", %{user: user} do
assert Accounts.update_user_email(user, "oops") ==
{:error, :transaction_aborted}
assert Repo.get!(User, user.id).email == user.email
assert Repo.get_by(UserToken, user_id: user.id)
end
test "does not update email if user email changed", %{user: user, token: token} do
assert Accounts.update_user_email(%{user | email: "current@example.com"}, token) ==
{:error, :transaction_aborted}
assert Repo.get!(User, user.id).email == user.email
assert Repo.get_by(UserToken, user_id: user.id)
end
test "does not update email if token expired", %{user: user, token: token} do
{1, nil} = Repo.update_all(UserToken, set: [inserted_at: ~N[2020-01-01 00:00:00]])
assert Accounts.update_user_email(user, token) ==
{:error, :transaction_aborted}
assert Repo.get!(User, user.id).email == user.email
assert Repo.get_by(UserToken, user_id: user.id)
end
end
describe "change_user_password/3" do
test "returns a user changeset" do
assert %Ecto.Changeset{} = changeset = Accounts.change_user_password(%User{})
assert changeset.required == [:password]
end
test "allows fields to be set" do
changeset =
Accounts.change_user_password(
%User{},
%{
"password" => "new valid password"
},
hash_password: false
)
assert changeset.valid?
assert get_change(changeset, :password) == "new valid password"
assert is_nil(get_change(changeset, :hashed_password))
end
end
describe "update_user_password/2" do
setup do
%{user: user_fixture()}
end
test "validates password", %{user: user} do
{:error, changeset} =
Accounts.update_user_password(user, %{
password: "not valid",
password_confirmation: "another"
})
assert %{
password: ["should be at least 12 character(s)"],
password_confirmation: ["does not match password"]
} = errors_on(changeset)
end
test "validates maximum values for password for security", %{user: user} do
too_long = String.duplicate("db", 100)
{:error, changeset} =
Accounts.update_user_password(user, %{password: too_long})
assert "should be at most 72 character(s)" in errors_on(changeset).password
end
test "updates the password", %{user: user} do
{:ok, {user, expired_tokens}} =
Accounts.update_user_password(user, %{
password: "new valid password"
})
assert expired_tokens == []
assert is_nil(user.password)
assert Accounts.get_user_by_login_and_password(user.email, "new valid password")
end
test "deletes all tokens for the given user", %{user: user} do
_ = Accounts.generate_user_session_token(user)
{:ok, {_, _}} =
Accounts.update_user_password(user, %{
password: "new valid password"
})
refute Repo.get_by(UserToken, user_id: user.id)
end
end
describe "generate_user_session_token/1" do
setup do
%{user: user_fixture()}
end
test "generates a token", %{user: user} do
token = Accounts.generate_user_session_token(user)
assert user_token = Repo.get_by(UserToken, token: token)
assert user_token.context == "session"
assert user_token.authenticated_at != nil
# Creating the same token for another user should fail
assert_raise Ecto.ConstraintError, fn ->
Repo.insert!(%UserToken{
token: user_token.token,
user_id: user_fixture().id,
context: "session"
})
end
end
test "duplicates the authenticated_at of given user in new token", %{user: user} do
user = %{user | authenticated_at: DateTime.add(DateTime.utc_now(:second), -3600)}
token = Accounts.generate_user_session_token(user)
assert user_token = Repo.get_by(UserToken, token: token)
assert user_token.authenticated_at == user.authenticated_at
assert DateTime.compare(user_token.inserted_at, user.authenticated_at) == :gt
end
end
describe "get_user_by_session_token/1" do
setup do
user = user_fixture()
token = Accounts.generate_user_session_token(user)
%{user: user, token: token}
end
test "returns user by token", %{user: user, token: token} do
assert {session_user, token_inserted_at} = Accounts.get_user_by_session_token(token)
assert session_user.id == user.id
assert session_user.authenticated_at != nil
assert token_inserted_at != nil
end
test "does not return user for invalid token" do
refute Accounts.get_user_by_session_token("oops")
end
test "does not return user for expired token", %{token: token} do
dt = ~N[2020-01-01 00:00:00]
{1, nil} = Repo.update_all(UserToken, set: [inserted_at: dt, authenticated_at: dt])
refute Accounts.get_user_by_session_token(token)
end
end
describe "delete_user_session_token/1" do
test "deletes the token" do
user = user_fixture()
token = Accounts.generate_user_session_token(user)
assert Accounts.delete_user_session_token(token) == :ok
refute Accounts.get_user_by_session_token(token)
end
end
describe "inspect/2 for the User module" do
test "does not include password" do
refute inspect(%User{password: "123456"}) =~ "password: \"123456\""
end
end
end
+75
View File
@@ -0,0 +1,75 @@
defmodule Chesstrainer.AttemptsTest do
use Chesstrainer.DataCase, async: true
import Chesstrainer.AccountsFixtures
import Chesstrainer.EndgamesFixtures
alias Chesstrainer.Accounts.Scope
alias Chesstrainer.Attempts
alias Chesstrainer.Attempts.Attempt
alias Chesstrainer.Endgames
describe "record_attempt/3" do
test "records a solved attempt for a signed-in user" do
user = user_fixture()
endgame = endgame_fixture()
assert {:ok, %Attempt{} = attempt} =
Attempts.record_attempt(Scope.for_user(user), endgame, :solved)
assert attempt.user_id == user.id
assert attempt.endgame_id == endgame.id
assert attempt.outcome == :solved
assert is_nil(attempt.rated_at)
end
test "records a failed attempt for a signed-in user" do
user = user_fixture()
endgame = endgame_fixture()
assert {:ok, %Attempt{outcome: :failed}} =
Attempts.record_attempt(Scope.for_user(user), endgame, :failed)
end
test "records nothing for an anonymous scope" do
endgame = endgame_fixture()
assert :ignored = Attempts.record_attempt(nil, endgame, :solved)
assert Repo.aggregate(Attempt, :count) == 0
end
end
describe "cascade" do
test "deleting a user removes their attempts" do
user = user_fixture()
endgame = endgame_fixture()
{:ok, _attempt} = Attempts.record_attempt(Scope.for_user(user), endgame, :solved)
Repo.delete!(user)
assert Repo.aggregate(Attempt, :count) == 0
end
test "deleting an endgame removes attempts against it" do
user = user_fixture()
endgame = endgame_fixture()
{:ok, _attempt} = Attempts.record_attempt(Scope.for_user(user), endgame, :solved)
assert {:ok, _} = Endgames.delete_endgame(endgame)
assert Repo.aggregate(Attempt, :count) == 0
end
end
describe "rating-window index" do
test "rated rows are indexed by user, endgame and rated_at" do
%{rows: [[indexdef]]} =
Repo.query!(
"SELECT indexdef FROM pg_indexes " <>
"WHERE tablename = 'attempts' AND indexname = 'attempts_user_id_endgame_id_rated_at_index'"
)
assert indexdef =~ "WHERE (rated_at IS NOT NULL)"
end
end
end
+76
View File
@@ -174,6 +174,28 @@ defmodule Chesstrainer.EndgamesTest do
end end
end end
describe "public code" do
test "create_endgame/1 assigns a 10-character lowercase Crockford code" do
endgame = create_endgame!(@kr)
assert String.length(endgame.public_code) == 10
assert endgame.public_code =~ ~r/^[0-9abcdefghjkmnpqrstvwxyz]{10}$/
end
test "create_endgame/1 gives each endgame a distinct code" do
one = create_endgame!(@kr)
two = create_endgame!(@kr_other)
refute one.public_code == two.public_code
end
test "get_endgame_by_public_code!/1 finds the endgame" do
endgame = create_endgame!(@kr)
assert Endgames.get_endgame_by_public_code!(endgame.public_code).id == endgame.id
end
end
describe "rating default" do describe "rating default" do
test "a new endgame changeset defaults rating to 1500" do test "a new endgame changeset defaults rating to 1500" do
changeset = Endgames.change_endgame(%Endgame{}) changeset = Endgames.change_endgame(%Endgame{})
@@ -182,6 +204,60 @@ defmodule Chesstrainer.EndgamesTest do
end end
end end
describe "search/1" do
test "finds an endgame by its public code" do
endgame = create_endgame!(@kr)
create_endgame!(@kq)
assert [found] = Endgames.search(endgame.public_code)
assert found.id == endgame.id
end
test "finds an endgame by its database id" do
endgame = create_endgame!(@kr)
assert [found] = Endgames.search(endgame.id)
assert found.id == endgame.id
end
test "finds an endgame by an exactly matching FEN, ignoring surrounding whitespace" do
endgame = create_endgame!(@kr)
assert [found] = Endgames.search(" #{@kr} ")
assert found.id == endgame.id
end
test "normalizes a fullmove 0 FEN before matching" do
endgame = create_endgame!("8/8/3k4/8/8/3K1R2/8/8 w - - 0 0")
assert [found] = Endgames.search("8/8/3k4/8/8/3K1R2/8/8 w - - 0 0")
assert found.id == endgame.id
end
test "finds endgames containing a FEN fragment" do
kr = create_endgame!(@kr)
kq = create_endgame!(@kq)
assert Enum.sort(Enum.map(Endgames.search("3k4"), & &1.id)) == Enum.sort([kr.id, kq.id])
end
test "preloads themes" do
{:ok, lucena} = Themes.create_theme(%{name: "Lucena", category: :endgame})
create_endgame!(@kr, [lucena])
assert [found] = Endgames.search(@kr)
assert Enum.map(found.themes, & &1.name) == ["Lucena"]
end
test "returns no results for an unknown search or a blank query" do
create_endgame!(@kr)
assert Endgames.search("8/8/8/8/8/8/8/8 w - - 0 1") == []
assert Endgames.search("not an identifier") == []
assert Endgames.search(" ") == []
end
end
describe "listing and filtering" do describe "listing and filtering" do
test "list_keys/0 returns the distinct keys sorted" do test "list_keys/0 returns the distinct keys sorted" do
create_endgame!(@kr) create_endgame!(@kr)
+136
View File
@@ -0,0 +1,136 @@
defmodule Chesstrainer.RatingsTest do
use Chesstrainer.DataCase, async: true
import Chesstrainer.AccountsFixtures
import Chesstrainer.EndgamesFixtures
alias Chesstrainer.Accounts.Scope
alias Chesstrainer.Accounts.User
alias Chesstrainer.Attempts
alias Chesstrainer.Attempts.Attempt
alias Chesstrainer.Endgames.Endgame
alias Chesstrainer.Ratings
describe "rate_attempt/1" do
test "a solve raises the user's rating and lowers the endgame's" do
user = user_fixture()
endgame = endgame_fixture(rating: 1800)
{:ok, attempt} = Attempts.record_attempt(Scope.for_user(user), endgame, :solved)
assert {:ok, %{user: rated_user, endgame: rated_endgame, attempt: rated_attempt}} =
Ratings.rate_attempt(attempt)
assert rated_user.rating > 1500.0
assert rated_endgame.rating < 1800.0
assert is_float(rated_user.rating)
assert is_float(rated_user.rating_deviation)
assert is_float(rated_endgame.rating)
assert is_float(rated_endgame.rating_deviation)
refute is_nil(rated_attempt.rated_at)
end
test "a fail lowers the user's rating and raises the endgame's" do
user = user_fixture()
endgame = endgame_fixture(rating: 1800)
{:ok, attempt} = Attempts.record_attempt(Scope.for_user(user), endgame, :failed)
assert {:ok, %{user: rated_user, endgame: rated_endgame}} = Ratings.rate_attempt(attempt)
assert rated_user.rating < 1500.0
assert rated_endgame.rating > 1800.0
end
test "persists both ratings and stamps the attempt as rated" do
user = user_fixture()
endgame = endgame_fixture(rating: 1800)
{:ok, attempt} = Attempts.record_attempt(Scope.for_user(user), endgame, :solved)
{:ok, _} = Ratings.rate_attempt(attempt)
assert Repo.get!(User, user.id).rating > 1500.0
assert Repo.get!(Endgame, endgame.id).rating < 1800.0
assert Repo.get!(Attempt, attempt.id).rated_at
end
end
describe "rating window" do
test "skips a replay inside the window and leaves the attempt unrated" do
user = user_fixture()
endgame = endgame_fixture(rating: 1800)
{:ok, first} = Attempts.record_attempt(Scope.for_user(user), endgame, :solved)
{:ok, _} = Ratings.rate_attempt(first)
rated_user = Repo.get!(User, user.id)
rated_endgame = Repo.get!(Endgame, endgame.id)
{:ok, replay} = Attempts.record_attempt(Scope.for_user(user), endgame, :solved)
assert {:skipped, %Attempt{rated_at: nil}} = Ratings.rate_attempt(replay)
assert Repo.get!(User, user.id).rating == rated_user.rating
assert Repo.get!(Endgame, endgame.id).rating == rated_endgame.rating
assert Repo.get!(Attempt, replay.id).rated_at == nil
end
test "rates a replay after the window" do
user = user_fixture()
endgame = endgame_fixture(rating: 1800)
{:ok, first} = Attempts.record_attempt(Scope.for_user(user), endgame, :solved)
{:ok, _} = Ratings.rate_attempt(first)
backdate!(first, 8)
{:ok, replay} = Attempts.record_attempt(Scope.for_user(user), endgame, :solved)
assert {:ok, %{attempt: %Attempt{rated_at: rated_at}}} = Ratings.rate_attempt(replay)
refute is_nil(rated_at)
end
end
describe "inactivity" do
test "a longer absence produces a larger rating change" do
short =
rating_delta_after_gap(
8,
"4k3/8/8/8/8/8/1K6/8 w - - 0 1",
"4k3/8/8/8/8/8/2K5/8 w - - 0 1"
)
long =
rating_delta_after_gap(
90,
"4k3/8/8/8/8/8/3K4/8 w - - 0 1",
"4k3/8/8/8/8/8/4K3/8 w - - 0 1"
)
assert long > short
end
end
defp rating_delta_after_gap(days, prior_fen, target_fen) do
{:ok, user} =
user_fixture()
|> Ecto.Changeset.change(rating: 1500.0, rating_deviation: 100.0)
|> Repo.update()
# A prior rated result on another endgame `days` ago, without changing the
# user's rating, so only the inactivity inflation differs between runs.
prior_endgame = endgame_fixture(fen: prior_fen)
{:ok, prior} = Attempts.record_attempt(Scope.for_user(user), prior_endgame, :solved)
backdate!(prior, days)
target = endgame_fixture(fen: target_fen, rating: 1500.0)
{:ok, attempt} = Attempts.record_attempt(Scope.for_user(user), target, :solved)
{:ok, %{user: rated}} = Ratings.rate_attempt(attempt)
rated.rating - 1500.0
end
defp backdate!(attempt, days) do
attempt
|> Ecto.Changeset.change(
rated_at: DateTime.add(DateTime.utc_now(:second), -days * 86_400, :second)
)
|> Repo.update!()
end
end
@@ -0,0 +1,81 @@
defmodule ChesstrainerWeb.AdminGatingTest do
use ChesstrainerWeb.ConnCase, async: true
import Chesstrainer.AccountsFixtures
alias Chesstrainer.Accounts
test "unauthenticated visitors are redirected to log in", %{conn: conn} do
conn = get(conn, ~p"/admin/endgames")
assert redirected_to(conn) == ~p"/users/log-in"
assert Phoenix.Flash.get(conn.assigns.flash, :error) ==
"You must log in to access this page."
end
test "members are redirected home", %{conn: conn} do
conn =
conn
|> log_in_user(user_fixture())
|> get(~p"/admin/endgames")
assert redirected_to(conn) == ~p"/"
assert Phoenix.Flash.get(conn.assigns.flash, :error) ==
"You are not authorized to access this page."
end
test "moderators are redirected home", %{conn: conn} do
{:ok, user} = Accounts.update_user_role(user_fixture(), :moderator)
conn =
conn
|> log_in_user(user)
|> get(~p"/admin/endgames")
assert redirected_to(conn) == ~p"/"
end
test "admins are admitted", %{conn: conn} do
{:ok, user} = Accounts.update_user_role(user_fixture(), :admin)
conn =
conn
|> log_in_user(user)
|> get(~p"/admin/endgames")
assert html_response(conn, 200)
end
test "super admins are admitted", %{conn: conn} do
{:ok, user} = Accounts.update_user_role(user_fixture(), :super_admin)
conn =
conn
|> log_in_user(user)
|> get(~p"/admin/endgames")
assert html_response(conn, 200)
end
test "the navbar hides the Admin link from members", %{conn: conn} do
conn =
conn
|> log_in_user(user_fixture())
|> get(~p"/")
refute html_response(conn, 200) =~ ~p"/admin/endgames"
end
test "the navbar shows the Admin link to admins", %{conn: conn} do
{:ok, user} = Accounts.update_user_role(user_fixture(), :admin)
conn =
conn
|> log_in_user(user)
|> get(~p"/")
assert html_response(conn, 200) =~ ~p"/admin/endgames"
end
end
@@ -0,0 +1,95 @@
defmodule ChesstrainerWeb.UserSessionControllerTest do
use ChesstrainerWeb.ConnCase, async: true
import Chesstrainer.AccountsFixtures
setup do
%{user: user_fixture()}
end
describe "POST /users/log-in - email or username and password" do
test "logs the user in with their email", %{conn: conn, user: user} do
conn =
post(conn, ~p"/users/log-in", %{
"user" => %{"email" => user.email, "password" => valid_user_password()}
})
assert get_session(conn, :user_token)
assert redirected_to(conn) == ~p"/"
# Now do a logged in request and assert on the menu
conn = get(conn, ~p"/")
response = html_response(conn, 200)
assert response =~ user.username
assert response =~ ~p"/users/settings"
assert response =~ ~p"/users/log-out"
end
test "logs the user in with their username", %{conn: conn, user: user} do
conn =
post(conn, ~p"/users/log-in", %{
"user" => %{"email" => user.username, "password" => valid_user_password()}
})
assert get_session(conn, :user_token)
assert redirected_to(conn) == ~p"/"
end
test "logs the user in with remember me", %{conn: conn, user: user} do
conn =
post(conn, ~p"/users/log-in", %{
"user" => %{
"email" => user.email,
"password" => valid_user_password(),
"remember_me" => "true"
}
})
assert conn.resp_cookies["_chesstrainer_web_user_remember_me"]
assert redirected_to(conn) == ~p"/"
end
test "logs the user in with return to", %{conn: conn, user: user} do
conn =
conn
|> init_test_session(user_return_to: "/foo/bar")
|> post(~p"/users/log-in", %{
"user" => %{
"email" => user.email,
"password" => valid_user_password()
}
})
assert redirected_to(conn) == "/foo/bar"
assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "Welcome back!"
end
test "redirects to login page with invalid credentials", %{conn: conn, user: user} do
conn =
post(conn, ~p"/users/log-in", %{
"user" => %{"email" => user.email, "password" => "invalid_password"}
})
assert Phoenix.Flash.get(conn.assigns.flash, :error) ==
"Invalid email, username or password"
assert redirected_to(conn) == ~p"/users/log-in"
end
end
describe "DELETE /users/log-out" do
test "logs the user out", %{conn: conn, user: user} do
conn = conn |> log_in_user(user) |> delete(~p"/users/log-out")
assert redirected_to(conn) == ~p"/"
refute get_session(conn, :user_token)
assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "Logged out successfully"
end
test "succeeds even if the user is not logged in", %{conn: conn} do
conn = delete(conn, ~p"/users/log-out")
assert redirected_to(conn) == ~p"/"
refute get_session(conn, :user_token)
assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "Logged out successfully"
end
end
end
@@ -10,6 +10,8 @@ defmodule ChesstrainerWeb.EndgameLive.FormTest do
@fen "8/8/3k4/8/8/3K1R2/8/8 w - - 0 1" @fen "8/8/3k4/8/8/3K1R2/8/8 w - - 0 1"
setup :register_and_log_in_admin
describe "rating default" do describe "rating default" do
test "new endgame form pre-fills rating with 1500", %{conn: conn} do test "new endgame form pre-fills rating with 1500", %{conn: conn} do
{:ok, view, _html} = live(conn, ~p"/admin/endgames/new") {:ok, view, _html} = live(conn, ~p"/admin/endgames/new")
@@ -36,7 +38,7 @@ defmodule ChesstrainerWeb.EndgameLive.FormTest do
attrs = %{fen: @fen, color: :white, result: :win, rating: 1625} attrs = %{fen: @fen, color: :white, result: :win, rating: 1625}
{:ok, endgame} = Endgames.create_endgame(attrs) {:ok, endgame} = Endgames.create_endgame(attrs)
{:ok, view, _html} = live(conn, ~p"/admin/endgames/#{endgame}/edit") {:ok, view, _html} = live(conn, ~p"/admin/endgames/#{endgame.id}/edit")
html = view |> element("#endgame-form input[name='endgame[rating]']") |> render() html = view |> element("#endgame-form input[name='endgame[rating]']") |> render()
@@ -101,7 +103,7 @@ defmodule ChesstrainerWeb.EndgameLive.FormTest do
attrs = %{fen: @fen, color: :white, result: :win, rating: 1500} attrs = %{fen: @fen, color: :white, result: :win, rating: 1500}
{:ok, endgame} = Endgames.create_endgame(attrs, [theme]) {:ok, endgame} = Endgames.create_endgame(attrs, [theme])
{:ok, view, _html} = live(conn, ~p"/admin/endgames/#{endgame}/edit") {:ok, view, _html} = live(conn, ~p"/admin/endgames/#{endgame.id}/edit")
assert render(view) =~ "Lucena" assert render(view) =~ "Lucena"
@@ -7,6 +7,8 @@ defmodule ChesstrainerWeb.EndgameLive.IndexTest do
alias Chesstrainer.Endgames alias Chesstrainer.Endgames
setup :register_and_log_in_admin
test "groups endgames by Key with a count", %{conn: conn} do test "groups endgames by Key with a count", %{conn: conn} do
endgame_fixture() endgame_fixture()
endgame_fixture() endgame_fixture()
@@ -41,16 +43,68 @@ defmodule ChesstrainerWeb.EndgameLive.IndexTest do
{:ok, view, html} = live(conn, ~p"/admin/endgames") {:ok, view, html} = live(conn, ~p"/admin/endgames")
# collapsed: the endgame row (and its themes) are not rendered yet # collapsed: the endgame row (and its themes) are not rendered yet
refute html =~ ~p"/endgames/#{endgame}/play" refute html =~ ~p"/endgames/#{endgame.public_code}/play"
refute html =~ "Lucena" refute html =~ "Lucena"
view |> element("#key-group-K-v-K button") |> render_click() view |> element("#key-group-K-v-K button") |> render_click()
html = render(view) html = render(view)
assert html =~ ~p"/endgames/#{endgame}/play" assert html =~ ~p"/endgames/#{endgame.public_code}/play"
assert html =~ "Lucena" assert html =~ "Lucena"
end end
describe "search" do
test "opens the endgame found by public code", %{conn: conn} do
endgame = endgame_fixture()
{:ok, view, _html} = live(conn, ~p"/admin/endgames")
assert {:error, {:live_redirect, %{to: path}}} =
view
|> form("#endgame-search-form", %{query: endgame.public_code})
|> render_submit()
assert path == "/admin/endgames/#{endgame.id}"
end
test "opens the endgame found by database id", %{conn: conn} do
endgame = endgame_fixture()
{:ok, view, _html} = live(conn, ~p"/admin/endgames")
assert {:error, {:live_redirect, %{to: path}}} =
view |> form("#endgame-search-form", %{query: endgame.id}) |> render_submit()
assert path == "/admin/endgames/#{endgame.id}"
end
test "lists every endgame containing a FEN fragment", %{conn: conn} do
kr = endgame_fixture(fen: "8/8/3k4/8/8/3K1R2/8/8 w - - 0 1")
kq = endgame_fixture(fen: "8/8/3k4/8/8/3K1Q2/8/8 w - - 0 1")
{:ok, view, _html} = live(conn, ~p"/admin/endgames")
html = view |> form("#endgame-search-form", %{query: "3k4"}) |> render_submit()
assert html =~ ~s{/admin/endgames/#{kr.id}}
assert html =~ ~s{/admin/endgames/#{kq.id}}
end
test "reports when nothing matches, and clears back to the grouped list", %{conn: conn} do
endgame_fixture()
{:ok, view, _html} = live(conn, ~p"/admin/endgames")
html = view |> form("#endgame-search-form", %{query: "no such endgame"}) |> render_submit()
assert html =~ "No endgame matches"
view |> element("#clear-endgame-search") |> render_click()
assert has_element?(view, "#key-group-K-v-K")
refute render(view) =~ "No endgame matches"
end
end
test "filters by theme", %{conn: conn} do test "filters by theme", %{conn: conn} do
lucena = theme_fixture(%{name: "Lucena"}) lucena = theme_fixture(%{name: "Lucena"})
philidor = theme_fixture(%{name: "Philidor"}) philidor = theme_fixture(%{name: "Philidor"})
@@ -4,11 +4,14 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
import Phoenix.LiveViewTest import Phoenix.LiveViewTest
import Chesstrainer.EndgamesFixtures import Chesstrainer.EndgamesFixtures
alias Chesstrainer.Accounts.User
alias Chesstrainer.Attempts.Attempt
alias Chesstrainer.Endgames alias Chesstrainer.Endgames
alias Chesstrainer.Endgames.Tablebase alias Chesstrainer.Endgames.Tablebase
alias Chesstrainer.Endgames.Tablebase.Cache, as: TablebaseCache alias Chesstrainer.Endgames.Tablebase.Cache, as: TablebaseCache
alias Chesstrainer.FEN alias Chesstrainer.FEN
alias Chesstrainer.Ratelimiters alias Chesstrainer.Ratelimiters
alias Chesstrainer.Repo
defp assert_init_board(view, expected_fen, expected_orientation, expected_player_color) do defp assert_init_board(view, expected_fen, expected_orientation, expected_player_color) do
%{proxy: {ref, _topic, _}} = view %{proxy: {ref, _topic, _}} = view
@@ -66,11 +69,12 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
{:ok, key} = Chesstrainer.Key.from_fen(fen) {:ok, key} = Chesstrainer.Key.from_fen(fen)
Chesstrainer.Repo.insert!(%Chesstrainer.Endgames.Endgame{ Chesstrainer.Repo.insert!(%Chesstrainer.Endgames.Endgame{
public_code: Chesstrainer.Endgames.Endgame.generate_public_code(),
fen: fen, fen: fen,
color: :black, color: :black,
key: key, key: key,
result: :win, result: :win,
rating: 1500 rating: 1500.0
}) })
end end
@@ -92,7 +96,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
seed_tablebase(after_reply, category: :win, moves: grading_moves()) seed_tablebase(after_reply, category: :win, moves: grading_moves())
seed_tablebase(after_losing, category: :draw, moves: [losing_reply]) seed_tablebase(after_losing, category: :draw, moves: [losing_reply])
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
%{proxy: {ref, _topic, _}} = view %{proxy: {ref, _topic, _}} = view
assert_receive {^ref, {:push_event, "init_board", _payload}}, 100 assert_receive {^ref, {:push_event, "init_board", _payload}}, 100
@@ -134,7 +138,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
endgame = endgame_fixture(color: :white) endgame = endgame_fixture(color: :white)
seed_tablebase(endgame.fen) seed_tablebase(endgame.fen)
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
assert has_element?(view, "#endgame-board") assert has_element?(view, "#endgame-board")
assert_init_board(view, endgame.fen, "white", "white") assert_init_board(view, endgame.fen, "white", "white")
@@ -144,7 +148,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
endgame = endgame_fixture(color: :black) endgame = endgame_fixture(color: :black)
seed_tablebase(endgame.fen) seed_tablebase(endgame.fen)
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
assert_init_board(view, endgame.fen, "black", "black") assert_init_board(view, endgame.fen, "black", "black")
end end
@@ -160,7 +164,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
seed_tablebase(endgame.fen) seed_tablebase(endgame.fen)
{:ok, _view, html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, _view, html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
assert html =~ "KQ v K" assert html =~ "KQ v K"
assert html =~ "White to move" assert html =~ "White to move"
@@ -173,6 +177,38 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
live(conn, ~p"/endgames/00000000-0000-0000-0000-000000000000/play") live(conn, ~p"/endgames/00000000-0000-0000-0000-000000000000/play")
end end
end end
test "does not resolve by database id", %{conn: conn} do
endgame = endgame_fixture()
assert_raise Ecto.NoResultsError, fn ->
live(conn, "/endgames/#{endgame.id}/play")
end
end
end
describe "current scope" do
test "carries the signed-in user into the play screen", %{conn: conn} do
user = Chesstrainer.AccountsFixtures.user_fixture()
endgame = endgame_fixture()
seed_tablebase(endgame.fen)
{:ok, view, _html} =
conn
|> log_in_user(user)
|> live(~p"/endgames/#{endgame.public_code}/play")
assert :sys.get_state(view.pid).socket.assigns.current_scope.user.id == user.id
end
test "is nil for an anonymous visitor", %{conn: conn} do
endgame = endgame_fixture()
seed_tablebase(endgame.fen)
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
assert :sys.get_state(view.pid).socket.assigns.current_scope == nil
end
end end
describe "tablebase availability" do describe "tablebase availability" do
@@ -184,7 +220,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
Ratelimiters.lichess_add_cooldown() Ratelimiters.lichess_add_cooldown()
on_exit(fn -> Ratelimiters.lichess_reset_cooldown() end) on_exit(fn -> Ratelimiters.lichess_reset_cooldown() end)
{:ok, view, html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
assert html =~ "Tablebase unavailable" assert html =~ "Tablebase unavailable"
@@ -195,7 +231,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
test "blocks an out-of-range endgame as not covered", %{conn: conn} do test "blocks an out-of-range endgame as not covered", %{conn: conn} do
endgame = insert_out_of_range_endgame() endgame = insert_out_of_range_endgame()
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
html = render(view) html = render(view)
assert html =~ "Tablebase unavailable" assert html =~ "Tablebase unavailable"
@@ -208,7 +244,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
endgame = endgame_fixture() endgame = endgame_fixture()
seed_tablebase(endgame.fen) seed_tablebase(endgame.fen)
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
view view
|> render_hook("chess_fen_invalid", %{ |> render_hook("chess_fen_invalid", %{
@@ -227,7 +263,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
endgame = endgame_fixture() endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves()) seed_tablebase(endgame.fen, moves: grading_moves())
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
play_move(view, endgame, "d1", "d7", "Qd7+") play_move(view, endgame, "d1", "d7", "Qd7+")
html = render(view) html = render(view)
@@ -240,7 +276,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
endgame = endgame_fixture() endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves()) seed_tablebase(endgame.fen, moves: grading_moves())
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
play_move(view, endgame, "d1", "d5", "Qd5") play_move(view, endgame, "d1", "d5", "Qd5")
@@ -251,7 +287,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
endgame = endgame_fixture() endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves()) seed_tablebase(endgame.fen, moves: grading_moves())
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
play_move(view, endgame, "d1", "d4", "Qd4") play_move(view, endgame, "d1", "d4", "Qd4")
@@ -262,7 +298,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
endgame = endgame_fixture() endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves()) seed_tablebase(endgame.fen, moves: grading_moves())
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
render_hook(view, "endgame_move_played", %{ render_hook(view, "endgame_move_played", %{
"from" => "d1", "from" => "d1",
@@ -288,7 +324,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
seed_tablebase(fen_after, category: :loss, moves: [reply]) seed_tablebase(fen_after, category: :loss, moves: [reply])
seed_tablebase(fen_after_reply, category: :win, moves: grading_moves()) seed_tablebase(fen_after_reply, category: :win, moves: grading_moves())
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
render_hook(view, "endgame_move_played", %{ render_hook(view, "endgame_move_played", %{
"from" => "d1", "from" => "d1",
@@ -314,7 +350,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
endgame = endgame_fixture() endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves()) seed_tablebase(endgame.fen, moves: grading_moves())
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
play_move(view, endgame, "d1", "d4", "Qd4") play_move(view, endgame, "d1", "d4", "Qd4")
@@ -330,7 +366,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
endgame = endgame_fixture() endgame = endgame_fixture()
seed_tablebase(endgame.fen) seed_tablebase(endgame.fen)
{:ok, _view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, _view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
assert Endgames.get_endgame!(endgame.id).times_attempted == 1 assert Endgames.get_endgame!(endgame.id).times_attempted == 1
end end
@@ -342,7 +378,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
seed_tablebase(endgame.fen, moves: grading_moves()) seed_tablebase(endgame.fen, moves: grading_moves())
seed_tablebase(fen_after, checkmate: true, moves: []) seed_tablebase(fen_after, checkmate: true, moves: [])
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
render_hook(view, "endgame_move_played", %{ render_hook(view, "endgame_move_played", %{
"from" => "d1", "from" => "d1",
@@ -362,7 +398,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
moves = [%Tablebase.Move{uci: "a7a8q", san: "a8=Q", category: :loss, dtz: -1}] moves = [%Tablebase.Move{uci: "a7a8q", san: "a8=Q", category: :loss, dtz: -1}]
seed_tablebase(endgame.fen, moves: moves) seed_tablebase(endgame.fen, moves: moves)
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
render_hook(view, "endgame_move_played", %{ render_hook(view, "endgame_move_played", %{
"from" => "a7", "from" => "a7",
@@ -382,7 +418,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
endgame = endgame_fixture() endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves()) seed_tablebase(endgame.fen, moves: grading_moves())
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
play_move(view, endgame, "d1", "d4", "Qd4") play_move(view, endgame, "d1", "d4", "Qd4")
@@ -393,12 +429,132 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
end end
end end
describe "per-user attempt records" do
setup :register_and_log_in_user
test "records a solved attempt for the signed-in user", %{conn: conn, user: user} do
endgame = endgame_fixture()
fen_after = "8/8/8/8/8/8/8/8 b - - 0 1"
seed_tablebase(endgame.fen, moves: grading_moves())
seed_tablebase(fen_after, checkmate: true, moves: [])
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
render_hook(view, "endgame_move_played", %{
"from" => "d1",
"to" => "d7",
"san" => "Qd7+",
"prev_fen" => endgame.fen,
"fen" => fen_after,
"endgame_id" => endgame.id
})
assert render(view) =~ "Solved!"
assert [attempt] = Repo.all(Attempt)
assert attempt.user_id == user.id
assert attempt.endgame_id == endgame.id
assert attempt.outcome == :solved
end
test "records a failed attempt for the signed-in user", %{conn: conn, user: user} do
endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves())
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
play_move(view, endgame, "d1", "d4", "Qd4")
assert render(view) =~ "Failed"
assert [attempt] = Repo.all(Attempt)
assert attempt.user_id == user.id
assert attempt.outcome == :failed
end
test "rates the user and the endgame on a solve", %{conn: conn, user: user} do
endgame = endgame_fixture(rating: 1800)
fen_after = "8/8/8/8/8/8/8/8 b - - 0 1"
seed_tablebase(endgame.fen, moves: grading_moves())
seed_tablebase(fen_after, checkmate: true, moves: [])
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
render_hook(view, "endgame_move_played", %{
"from" => "d1",
"to" => "d7",
"san" => "Qd7+",
"prev_fen" => endgame.fen,
"fen" => fen_after,
"endgame_id" => endgame.id
})
rated_user = Repo.get!(User, user.id)
assert render(view) =~ "Your rating: #{round(rated_user.rating)}"
assert rated_user.rating > 1500.0
assert Endgames.get_endgame!(endgame.id).rating < 1800.0
end
test "does not re-rate a replay within the window", %{conn: conn, user: user} do
endgame = endgame_fixture(rating: 1800)
fen_after = "8/8/8/8/8/8/8/8 b - - 0 1"
seed_tablebase(endgame.fen, moves: grading_moves())
seed_tablebase(fen_after, checkmate: true, moves: [])
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
play = fn ->
render_hook(view, "endgame_move_played", %{
"from" => "d1",
"to" => "d7",
"san" => "Qd7+",
"prev_fen" => endgame.fen,
"fen" => fen_after,
"endgame_id" => endgame.id
})
end
play.()
rated_user = Repo.get!(User, user.id)
rated_endgame = Endgames.get_endgame!(endgame.id)
render_click(view, "reset")
play.()
html = render(view)
assert html =~ "rating is unchanged"
assert Repo.get!(User, user.id).rating == rated_user.rating
assert Endgames.get_endgame!(endgame.id).rating == rated_endgame.rating
end
end
describe "per-user attempt records without a signed-in user" do
test "records nothing and leaves ratings untouched", %{conn: conn} do
endgame = endgame_fixture(rating: 1800)
seed_tablebase(endgame.fen, moves: grading_moves())
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
play_move(view, endgame, "d1", "d4", "Qd4")
html = render(view)
assert html =~ "Failed"
refute html =~ "Your rating"
assert Repo.aggregate(Attempt, :count) == 0
assert Endgames.get_endgame!(endgame.id).rating == 1800.0
end
end
describe "draw endgames" do describe "draw endgames" do
test "loads and is playable", %{conn: conn} do test "loads and is playable", %{conn: conn} do
endgame = endgame_fixture(result: :draw) endgame = endgame_fixture(result: :draw)
seed_tablebase(endgame.fen, category: :draw, moves: []) seed_tablebase(endgame.fen, category: :draw, moves: [])
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
assert has_element?(view, "#endgame-board") assert has_element?(view, "#endgame-board")
assert render(view) =~ "Make a move" assert render(view) =~ "Make a move"
@@ -412,7 +568,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
seed_tablebase(endgame.fen, category: :draw, moves: draw_moves()) seed_tablebase(endgame.fen, category: :draw, moves: draw_moves())
seed_tablebase(fen_after, category: :draw, moves: [reply]) seed_tablebase(fen_after, category: :draw, moves: [reply])
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
render_hook(view, "endgame_move_played", %{ render_hook(view, "endgame_move_played", %{
"from" => "d1", "from" => "d1",
@@ -434,7 +590,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
endgame = endgame_fixture(result: :draw) endgame = endgame_fixture(result: :draw)
seed_tablebase(endgame.fen, category: :draw, moves: draw_moves()) seed_tablebase(endgame.fen, category: :draw, moves: draw_moves())
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
render_hook(view, "endgame_move_played", %{ render_hook(view, "endgame_move_played", %{
"from" => "d1", "from" => "d1",
@@ -456,7 +612,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
endgame = endgame_fixture(result: :draw) endgame = endgame_fixture(result: :draw)
seed_tablebase(endgame.fen, category: :draw, moves: draw_moves()) seed_tablebase(endgame.fen, category: :draw, moves: draw_moves())
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
render_hook(view, "endgame_move_played", %{ render_hook(view, "endgame_move_played", %{
"from" => "d1", "from" => "d1",
@@ -480,7 +636,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
seed_tablebase(endgame.fen, category: :draw, moves: draw_moves()) seed_tablebase(endgame.fen, category: :draw, moves: draw_moves())
seed_tablebase(fen_after, category: :draw, moves: [reply]) seed_tablebase(fen_after, category: :draw, moves: [reply])
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
render_hook(view, "endgame_move_played", %{ render_hook(view, "endgame_move_played", %{
"from" => "d1", "from" => "d1",
@@ -504,7 +660,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
endgame = endgame_fixture() endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves()) seed_tablebase(endgame.fen, moves: grading_moves())
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
play_move(view, endgame, "d1", "d7", "Qd7+") play_move(view, endgame, "d1", "d7", "Qd7+")
assert render(view) =~ "Qd7+" assert render(view) =~ "Qd7+"
@@ -547,7 +703,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
seed_tablebase(endgame.fen, category: :draw, moves: moves) seed_tablebase(endgame.fen, category: :draw, moves: moves)
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
render_hook(view, "endgame_move_played", %{ render_hook(view, "endgame_move_played", %{
"from" => "d1", "from" => "d1",
@@ -583,7 +739,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
moves = [%Tablebase.Move{uci: "a7a8q", san: "a8=Q", category: :loss, dtz: -1}] moves = [%Tablebase.Move{uci: "a7a8q", san: "a8=Q", category: :loss, dtz: -1}]
seed_tablebase(endgame.fen, moves: moves) seed_tablebase(endgame.fen, moves: moves)
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
render_hook(view, "endgame_move_played", %{ render_hook(view, "endgame_move_played", %{
"from" => "a7", "from" => "a7",
@@ -23,11 +23,22 @@ defmodule ChesstrainerWeb.EndgameLive.PlayerIndexTest do
view |> element("#key-group-K-v-K button") |> render_click() view |> element("#key-group-K-v-K button") |> render_click()
html = render(view) html = render(view)
assert html =~ ~p"/endgames/#{endgame}/play" assert html =~ ~p"/endgames/#{endgame.public_code}/play"
assert html =~ ~p"/endgames/#{other}/play" assert html =~ ~p"/endgames/#{other.public_code}/play"
assert html =~ "Lucena" assert html =~ "Lucena"
end end
test "links to the public code, never the database id", %{conn: conn} do
endgame = endgame_fixture()
{:ok, view, _html} = live(conn, ~p"/endgames")
view |> element("#key-group-K-v-K button") |> render_click()
html = render(view)
assert html =~ ~s{/endgames/#{endgame.public_code}/play}
refute html =~ endgame.id
end
test "filters by theme", %{conn: conn} do test "filters by theme", %{conn: conn} do
lucena = theme_fixture(%{name: "Lucena"}) lucena = theme_fixture(%{name: "Lucena"})
philidor = theme_fixture(%{name: "Philidor"}) philidor = theme_fixture(%{name: "Philidor"})
@@ -49,7 +60,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayerIndexTest do
test "navigating to a play page renders the board", %{conn: conn} do test "navigating to a play page renders the board", %{conn: conn} do
endgame = endgame_fixture() endgame = endgame_fixture()
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play") {:ok, view, _html} = live(conn, ~p"/endgames/#{endgame.public_code}/play")
assert has_element?(view, "#endgame-board") assert has_element?(view, "#endgame-board")
assert has_element?(view, ~s{a[href="/endgames"]}) assert has_element?(view, ~s{a[href="/endgames"]})
@@ -0,0 +1,26 @@
defmodule ChesstrainerWeb.EndgameLive.ShowTest do
use ChesstrainerWeb.ConnCase
import Phoenix.LiveViewTest
import Chesstrainer.EndgamesFixtures
setup :register_and_log_in_admin
test "shows the public code alongside the database id", %{conn: conn} do
endgame = endgame_fixture()
{:ok, view, _html} = live(conn, ~p"/admin/endgames/#{endgame.id}")
assert has_element?(view, "li.list-row", "Public code")
assert has_element?(view, "li.list-row", endgame.public_code)
assert has_element?(view, "h1", endgame.id)
end
test "links to the player surface by public code", %{conn: conn} do
endgame = endgame_fixture()
{:ok, view, _html} = live(conn, ~p"/admin/endgames/#{endgame.id}")
assert has_element?(view, ~s{a[href="/endgames/#{endgame.public_code}/play"]})
end
end
@@ -0,0 +1,98 @@
defmodule ChesstrainerWeb.UserLive.LoginTest do
use ChesstrainerWeb.ConnCase, async: true
import Phoenix.LiveViewTest
import Chesstrainer.AccountsFixtures
describe "login page" do
test "renders login page", %{conn: conn} do
{:ok, _lv, html} = live(conn, ~p"/users/log-in")
assert html =~ "Log in"
assert html =~ "Sign up"
assert html =~ "Email or username"
end
end
describe "user login - password" do
test "redirects if user logs in with email", %{conn: conn} do
user = user_fixture()
{:ok, lv, _html} = live(conn, ~p"/users/log-in")
form =
form(lv, "#login_form_password",
user: %{email: user.email, password: valid_user_password(), remember_me: true}
)
conn = submit_form(form, conn)
assert redirected_to(conn) == ~p"/"
end
test "redirects if user logs in with username", %{conn: conn} do
user = user_fixture()
{:ok, lv, _html} = live(conn, ~p"/users/log-in")
form =
form(lv, "#login_form_password",
user: %{email: user.username, password: valid_user_password(), remember_me: true}
)
conn = submit_form(form, conn)
assert redirected_to(conn) == ~p"/"
end
test "redirects to login page with a flash error if credentials are invalid", %{
conn: conn
} do
{:ok, lv, _html} = live(conn, ~p"/users/log-in")
form =
form(lv, "#login_form_password", user: %{email: "test@email.com", password: "123456"})
render_submit(form, %{user: %{remember_me: true}})
conn = follow_trigger_action(form, conn)
assert Phoenix.Flash.get(conn.assigns.flash, :error) ==
"Invalid email, username or password"
assert redirected_to(conn) == ~p"/users/log-in"
end
end
describe "login navigation" do
test "redirects to registration page when the Register button is clicked", %{conn: conn} do
{:ok, lv, _html} = live(conn, ~p"/users/log-in")
{:ok, _login_live, login_html} =
lv
|> element("main a", "Sign up")
|> render_click()
|> follow_redirect(conn, ~p"/users/register")
assert login_html =~ "Register"
end
end
describe "re-authentication (sudo mode)" do
setup %{conn: conn} do
user = user_fixture()
%{user: user, conn: log_in_user(conn, user)}
end
test "shows login page with email filled in", %{conn: conn, user: user} do
{:ok, _lv, html} = live(conn, ~p"/users/log-in")
assert html =~ "You need to reauthenticate"
refute html =~ "Register"
assert html =~ "Email or username"
assert html =~
~s(<input type="text" name="user[email]" id="login_form_password_email" value="#{user.email}")
end
end
end
@@ -0,0 +1,134 @@
defmodule ChesstrainerWeb.UserLive.RegistrationTest do
use ChesstrainerWeb.ConnCase, async: true
import Phoenix.LiveViewTest
import Chesstrainer.AccountsFixtures
describe "Registration page" do
test "renders registration page", %{conn: conn} do
{:ok, _lv, html} = live(conn, ~p"/users/register")
assert html =~ "Register"
assert html =~ "Log in"
end
test "redirects if already logged in", %{conn: conn} do
result =
conn
|> log_in_user(user_fixture())
|> live(~p"/users/register")
|> follow_redirect(conn, ~p"/")
assert {:ok, _conn} = result
end
test "renders errors for invalid data", %{conn: conn} do
{:ok, lv, _html} = live(conn, ~p"/users/register")
result =
lv
|> element("#registration_form")
|> render_change(user: %{"email" => "with spaces"})
assert result =~ "Register"
assert result =~ "must have the @ sign and no spaces"
end
end
describe "register user" do
test "creates account but does not log in", %{conn: conn} do
{:ok, lv, _html} = live(conn, ~p"/users/register")
email = unique_user_email()
username = unique_username()
form =
form(lv, "#registration_form",
user: %{
"username" => username,
"email" => email,
"password" => valid_user_password(),
"password_confirmation" => valid_user_password()
}
)
{:ok, _lv, html} =
render_submit(form)
|> follow_redirect(conn, ~p"/users/log-in")
assert html =~ "Account created successfully"
end
test "renders errors for duplicated email", %{conn: conn} do
{:ok, lv, _html} = live(conn, ~p"/users/register")
user = user_fixture(%{email: "test@email.com"})
result =
lv
|> form("#registration_form",
user: %{
"username" => unique_username(),
"email" => user.email,
"password" => valid_user_password(),
"password_confirmation" => valid_user_password()
}
)
|> render_submit()
assert result =~ "has already been taken"
end
test "renders errors for duplicated username", %{conn: conn} do
{:ok, lv, _html} = live(conn, ~p"/users/register")
user = user_fixture()
result =
lv
|> form("#registration_form",
user: %{
"username" => user.username,
"email" => unique_user_email(),
"password" => valid_user_password(),
"password_confirmation" => valid_user_password()
}
)
|> render_submit()
assert result =~ "has already been taken"
end
test "renders errors for mismatched passwords", %{conn: conn} do
{:ok, lv, _html} = live(conn, ~p"/users/register")
result =
lv
|> form("#registration_form",
user: %{
"username" => unique_username(),
"email" => unique_user_email(),
"password" => valid_user_password(),
"password_confirmation" => "something else"
}
)
|> render_submit()
assert result =~ "does not match password"
end
end
describe "registration navigation" do
test "redirects to login page when the Log in button is clicked", %{conn: conn} do
{:ok, lv, _html} = live(conn, ~p"/users/register")
{:ok, _login_live, login_html} =
lv
|> element("main a", "Log in")
|> render_click()
|> follow_redirect(conn, ~p"/users/log-in")
assert login_html =~ "Log in"
end
end
end
@@ -0,0 +1,212 @@
defmodule ChesstrainerWeb.UserLive.SettingsTest do
use ChesstrainerWeb.ConnCase, async: true
alias Chesstrainer.Accounts
import Phoenix.LiveViewTest
import Chesstrainer.AccountsFixtures
describe "Settings page" do
test "renders settings page", %{conn: conn} do
{:ok, _lv, html} =
conn
|> log_in_user(user_fixture())
|> live(~p"/users/settings")
assert html =~ "Change Email"
assert html =~ "Save Password"
end
test "redirects if user is not logged in", %{conn: conn} do
assert {:error, redirect} = live(conn, ~p"/users/settings")
assert {:redirect, %{to: path, flash: flash}} = redirect
assert path == ~p"/users/log-in"
assert %{"error" => "You must log in to access this page."} = flash
end
test "redirects if user is not in sudo mode", %{conn: conn} do
{:ok, conn} =
conn
|> log_in_user(user_fixture(),
token_authenticated_at: DateTime.add(DateTime.utc_now(:second), -11, :minute)
)
|> live(~p"/users/settings")
|> follow_redirect(conn, ~p"/users/log-in")
assert conn.resp_body =~ "You must re-authenticate to access this page."
end
end
describe "update email form" do
setup %{conn: conn} do
user = user_fixture()
%{conn: log_in_user(conn, user), user: user}
end
test "updates the user email", %{conn: conn, user: user} do
new_email = unique_user_email()
{:ok, lv, _html} = live(conn, ~p"/users/settings")
result =
lv
|> form("#email_form", %{
"user" => %{"email" => new_email}
})
|> render_submit()
assert result =~ "A link to confirm your email"
assert Accounts.get_user_by_email(user.email)
end
test "renders errors with invalid data (phx-change)", %{conn: conn} do
{:ok, lv, _html} = live(conn, ~p"/users/settings")
result =
lv
|> element("#email_form")
|> render_change(%{
"action" => "update_email",
"user" => %{"email" => "with spaces"}
})
assert result =~ "Change Email"
assert result =~ "must have the @ sign and no spaces"
end
test "renders errors with invalid data (phx-submit)", %{conn: conn, user: user} do
{:ok, lv, _html} = live(conn, ~p"/users/settings")
result =
lv
|> form("#email_form", %{
"user" => %{"email" => user.email}
})
|> render_submit()
assert result =~ "Change Email"
assert result =~ "did not change"
end
end
describe "update password form" do
setup %{conn: conn} do
user = user_fixture()
%{conn: log_in_user(conn, user), user: user}
end
test "updates the user password", %{conn: conn, user: user} do
new_password = valid_user_password()
{:ok, lv, _html} = live(conn, ~p"/users/settings")
form =
form(lv, "#password_form", %{
"user" => %{
"email" => user.email,
"password" => new_password,
"password_confirmation" => new_password
}
})
render_submit(form)
new_password_conn = follow_trigger_action(form, conn)
assert redirected_to(new_password_conn) == ~p"/users/settings"
assert get_session(new_password_conn, :user_token) != get_session(conn, :user_token)
assert Phoenix.Flash.get(new_password_conn.assigns.flash, :info) =~
"Password updated successfully"
assert Accounts.get_user_by_login_and_password(user.email, new_password)
end
test "renders errors with invalid data (phx-change)", %{conn: conn} do
{:ok, lv, _html} = live(conn, ~p"/users/settings")
result =
lv
|> element("#password_form")
|> render_change(%{
"user" => %{
"password" => "too short",
"password_confirmation" => "does not match"
}
})
assert result =~ "Save Password"
assert result =~ "should be at least 12 character(s)"
assert result =~ "does not match password"
end
test "renders errors with invalid data (phx-submit)", %{conn: conn} do
{:ok, lv, _html} = live(conn, ~p"/users/settings")
result =
lv
|> form("#password_form", %{
"user" => %{
"password" => "too short",
"password_confirmation" => "does not match"
}
})
|> render_submit()
assert result =~ "Save Password"
assert result =~ "should be at least 12 character(s)"
assert result =~ "does not match password"
end
end
describe "confirm email" do
setup %{conn: conn} do
user = user_fixture()
email = unique_user_email()
token =
extract_user_token(fn url ->
Accounts.deliver_user_update_email_instructions(%{user | email: email}, user.email, url)
end)
%{conn: log_in_user(conn, user), token: token, email: email, user: user}
end
test "updates the user email once", %{conn: conn, user: user, token: token, email: email} do
{:error, redirect} = live(conn, ~p"/users/settings/confirm-email/#{token}")
assert {:live_redirect, %{to: path, flash: flash}} = redirect
assert path == ~p"/users/settings"
assert %{"info" => message} = flash
assert message == "Email changed successfully."
refute Accounts.get_user_by_email(user.email)
assert Accounts.get_user_by_email(email)
# use confirm token again
{:error, redirect} = live(conn, ~p"/users/settings/confirm-email/#{token}")
assert {:live_redirect, %{to: path, flash: flash}} = redirect
assert path == ~p"/users/settings"
assert %{"error" => message} = flash
assert message == "Email change link is invalid or it has expired."
end
test "does not update email with invalid token", %{conn: conn, user: user} do
{:error, redirect} = live(conn, ~p"/users/settings/confirm-email/oops")
assert {:live_redirect, %{to: path, flash: flash}} = redirect
assert path == ~p"/users/settings"
assert %{"error" => message} = flash
assert message == "Email change link is invalid or it has expired."
assert Accounts.get_user_by_email(user.email)
end
test "redirects if user is not logged in", %{token: token} do
conn = build_conn()
{:error, redirect} = live(conn, ~p"/users/settings/confirm-email/#{token}")
assert {:redirect, %{to: path, flash: flash}} = redirect
assert path == ~p"/users/log-in"
assert %{"error" => message} = flash
assert message == "You must log in to access this page."
end
end
end
+497
View File
@@ -0,0 +1,497 @@
defmodule ChesstrainerWeb.UserAuthTest do
use ChesstrainerWeb.ConnCase, async: true
alias Phoenix.LiveView
alias Chesstrainer.Accounts
alias Chesstrainer.Accounts.Scope
alias ChesstrainerWeb.UserAuth
import Chesstrainer.AccountsFixtures
@remember_me_cookie "_chesstrainer_web_user_remember_me"
@remember_me_cookie_max_age 60 * 60 * 24 * 14
setup %{conn: conn} do
conn =
conn
|> Map.replace!(:secret_key_base, ChesstrainerWeb.Endpoint.config(:secret_key_base))
|> init_test_session(%{})
%{user: %{user_fixture() | authenticated_at: DateTime.utc_now(:second)}, conn: conn}
end
describe "log_in_user/3" do
test "stores the user token in the session", %{conn: conn, user: user} do
conn = UserAuth.log_in_user(conn, user)
assert token = get_session(conn, :user_token)
assert get_session(conn, :live_socket_id) == "users_sessions:#{Base.url_encode64(token)}"
assert redirected_to(conn) == ~p"/"
assert Accounts.get_user_by_session_token(token)
end
test "clears everything previously stored in the session", %{conn: conn, user: user} do
conn = conn |> put_session(:to_be_removed, "value") |> UserAuth.log_in_user(user)
refute get_session(conn, :to_be_removed)
end
test "keeps session when re-authenticating", %{conn: conn, user: user} do
conn =
conn
|> assign(:current_scope, Scope.for_user(user))
|> put_session(:to_be_removed, "value")
|> UserAuth.log_in_user(user)
assert get_session(conn, :to_be_removed)
end
test "clears session when user does not match when re-authenticating", %{
conn: conn,
user: user
} do
other_user = user_fixture()
conn =
conn
|> assign(:current_scope, Scope.for_user(other_user))
|> put_session(:to_be_removed, "value")
|> UserAuth.log_in_user(user)
refute get_session(conn, :to_be_removed)
end
test "redirects to the configured path", %{conn: conn, user: user} do
conn = conn |> put_session(:user_return_to, "/hello") |> UserAuth.log_in_user(user)
assert redirected_to(conn) == "/hello"
end
test "writes a cookie if remember_me is configured", %{conn: conn, user: user} do
conn = conn |> fetch_cookies() |> UserAuth.log_in_user(user, %{"remember_me" => "true"})
assert get_session(conn, :user_token) == conn.cookies[@remember_me_cookie]
assert get_session(conn, :user_remember_me) == true
assert %{value: signed_token, max_age: max_age} = conn.resp_cookies[@remember_me_cookie]
assert signed_token != get_session(conn, :user_token)
assert max_age == @remember_me_cookie_max_age
end
test "redirects to settings when user is already logged in", %{conn: conn, user: user} do
conn =
conn
|> assign(:current_scope, Scope.for_user(user))
|> UserAuth.log_in_user(user)
assert redirected_to(conn) == ~p"/users/settings"
end
test "writes a cookie if remember_me was set in previous session", %{conn: conn, user: user} do
conn = conn |> fetch_cookies() |> UserAuth.log_in_user(user, %{"remember_me" => "true"})
assert get_session(conn, :user_token) == conn.cookies[@remember_me_cookie]
assert get_session(conn, :user_remember_me) == true
conn =
conn
|> recycle()
|> Map.replace!(:secret_key_base, ChesstrainerWeb.Endpoint.config(:secret_key_base))
|> fetch_cookies()
|> init_test_session(%{user_remember_me: true})
# the conn is already logged in and has the remember_me cookie set,
# now we log in again and even without explicitly setting remember_me,
# the cookie should be set again
conn = conn |> UserAuth.log_in_user(user, %{})
assert %{value: signed_token, max_age: max_age} = conn.resp_cookies[@remember_me_cookie]
assert signed_token != get_session(conn, :user_token)
assert max_age == @remember_me_cookie_max_age
assert get_session(conn, :user_remember_me) == true
end
end
describe "logout_user/1" do
test "erases session and cookies", %{conn: conn, user: user} do
user_token = Accounts.generate_user_session_token(user)
conn =
conn
|> put_session(:user_token, user_token)
|> put_req_cookie(@remember_me_cookie, user_token)
|> fetch_cookies()
|> UserAuth.log_out_user()
refute get_session(conn, :user_token)
refute conn.cookies[@remember_me_cookie]
assert %{max_age: 0} = conn.resp_cookies[@remember_me_cookie]
assert redirected_to(conn) == ~p"/"
refute Accounts.get_user_by_session_token(user_token)
end
test "broadcasts to the given live_socket_id", %{conn: conn} do
live_socket_id = "users_sessions:abcdef-token"
ChesstrainerWeb.Endpoint.subscribe(live_socket_id)
conn
|> put_session(:live_socket_id, live_socket_id)
|> UserAuth.log_out_user()
assert_receive %Phoenix.Socket.Broadcast{event: "disconnect", topic: ^live_socket_id}
end
test "works even if user is already logged out", %{conn: conn} do
conn = conn |> fetch_cookies() |> UserAuth.log_out_user()
refute get_session(conn, :user_token)
assert %{max_age: 0} = conn.resp_cookies[@remember_me_cookie]
assert redirected_to(conn) == ~p"/"
end
end
describe "fetch_current_scope_for_user/2" do
test "authenticates user from session", %{conn: conn, user: user} do
user_token = Accounts.generate_user_session_token(user)
conn =
conn |> put_session(:user_token, user_token) |> UserAuth.fetch_current_scope_for_user([])
assert conn.assigns.current_scope.user.id == user.id
assert conn.assigns.current_scope.user.authenticated_at == user.authenticated_at
assert get_session(conn, :user_token) == user_token
end
test "authenticates user from cookies", %{conn: conn, user: user} do
logged_in_conn =
conn |> fetch_cookies() |> UserAuth.log_in_user(user, %{"remember_me" => "true"})
user_token = logged_in_conn.cookies[@remember_me_cookie]
%{value: signed_token} = logged_in_conn.resp_cookies[@remember_me_cookie]
conn =
conn
|> put_req_cookie(@remember_me_cookie, signed_token)
|> UserAuth.fetch_current_scope_for_user([])
assert conn.assigns.current_scope.user.id == user.id
assert conn.assigns.current_scope.user.authenticated_at == user.authenticated_at
assert get_session(conn, :user_token) == user_token
assert get_session(conn, :user_remember_me)
assert get_session(conn, :live_socket_id) ==
"users_sessions:#{Base.url_encode64(user_token)}"
end
test "does not authenticate if data is missing", %{conn: conn, user: user} do
_ = Accounts.generate_user_session_token(user)
conn = UserAuth.fetch_current_scope_for_user(conn, [])
refute get_session(conn, :user_token)
refute conn.assigns.current_scope
end
test "reissues a new token after a few days and refreshes cookie", %{conn: conn, user: user} do
logged_in_conn =
conn |> fetch_cookies() |> UserAuth.log_in_user(user, %{"remember_me" => "true"})
token = logged_in_conn.cookies[@remember_me_cookie]
%{value: signed_token} = logged_in_conn.resp_cookies[@remember_me_cookie]
offset_user_token(token, -10, :day)
{user, _} = Accounts.get_user_by_session_token(token)
conn =
conn
|> put_session(:user_token, token)
|> put_session(:user_remember_me, true)
|> put_req_cookie(@remember_me_cookie, signed_token)
|> UserAuth.fetch_current_scope_for_user([])
assert conn.assigns.current_scope.user.id == user.id
assert conn.assigns.current_scope.user.authenticated_at == user.authenticated_at
assert new_token = get_session(conn, :user_token)
assert new_token != token
assert %{value: new_signed_token, max_age: max_age} = conn.resp_cookies[@remember_me_cookie]
assert new_signed_token != signed_token
assert max_age == @remember_me_cookie_max_age
end
end
describe "on_mount :mount_current_scope" do
setup %{conn: conn} do
%{conn: UserAuth.fetch_current_scope_for_user(conn, [])}
end
test "assigns current_scope based on a valid user_token", %{conn: conn, user: user} do
user_token = Accounts.generate_user_session_token(user)
session = conn |> put_session(:user_token, user_token) |> get_session()
{:cont, updated_socket} =
UserAuth.on_mount(:mount_current_scope, %{}, session, %LiveView.Socket{})
assert updated_socket.assigns.current_scope.user.id == user.id
end
test "assigns nil to current_scope assign if there isn't a valid user_token", %{conn: conn} do
user_token = "invalid_token"
session = conn |> put_session(:user_token, user_token) |> get_session()
{:cont, updated_socket} =
UserAuth.on_mount(:mount_current_scope, %{}, session, %LiveView.Socket{})
assert updated_socket.assigns.current_scope == nil
end
test "assigns nil to current_scope assign if there isn't a user_token", %{conn: conn} do
session = conn |> get_session()
{:cont, updated_socket} =
UserAuth.on_mount(:mount_current_scope, %{}, session, %LiveView.Socket{})
assert updated_socket.assigns.current_scope == nil
end
end
describe "on_mount :require_authenticated" do
test "authenticates current_scope based on a valid user_token", %{conn: conn, user: user} do
user_token = Accounts.generate_user_session_token(user)
session = conn |> put_session(:user_token, user_token) |> get_session()
{:cont, updated_socket} =
UserAuth.on_mount(:require_authenticated, %{}, session, %LiveView.Socket{})
assert updated_socket.assigns.current_scope.user.id == user.id
end
test "redirects to login page if there isn't a valid user_token", %{conn: conn} do
user_token = "invalid_token"
session = conn |> put_session(:user_token, user_token) |> get_session()
socket = %LiveView.Socket{
endpoint: ChesstrainerWeb.Endpoint,
assigns: %{__changed__: %{}, flash: %{}}
}
{:halt, updated_socket} = UserAuth.on_mount(:require_authenticated, %{}, session, socket)
assert updated_socket.assigns.current_scope == nil
end
test "redirects to login page if there isn't a user_token", %{conn: conn} do
session = conn |> get_session()
socket = %LiveView.Socket{
endpoint: ChesstrainerWeb.Endpoint,
assigns: %{__changed__: %{}, flash: %{}}
}
{:halt, updated_socket} = UserAuth.on_mount(:require_authenticated, %{}, session, socket)
assert updated_socket.assigns.current_scope == nil
end
end
describe "on_mount :require_sudo_mode" do
test "allows users that have authenticated in the last 10 minutes", %{conn: conn, user: user} do
user_token = Accounts.generate_user_session_token(user)
session = conn |> put_session(:user_token, user_token) |> get_session()
socket = %LiveView.Socket{
endpoint: ChesstrainerWeb.Endpoint,
assigns: %{__changed__: %{}, flash: %{}}
}
assert {:cont, _updated_socket} =
UserAuth.on_mount(:require_sudo_mode, %{}, session, socket)
end
test "redirects when authentication is too old", %{conn: conn, user: user} do
eleven_minutes_ago = DateTime.utc_now(:second) |> DateTime.add(-11, :minute)
user = %{user | authenticated_at: eleven_minutes_ago}
user_token = Accounts.generate_user_session_token(user)
{user, token_inserted_at} = Accounts.get_user_by_session_token(user_token)
assert DateTime.compare(token_inserted_at, user.authenticated_at) == :gt
session = conn |> put_session(:user_token, user_token) |> get_session()
socket = %LiveView.Socket{
endpoint: ChesstrainerWeb.Endpoint,
assigns: %{__changed__: %{}, flash: %{}}
}
assert {:halt, _updated_socket} =
UserAuth.on_mount(:require_sudo_mode, %{}, session, socket)
end
end
describe "require_authenticated_user/2" do
setup %{conn: conn} do
%{conn: UserAuth.fetch_current_scope_for_user(conn, [])}
end
test "redirects if user is not authenticated", %{conn: conn} do
conn = conn |> fetch_flash() |> UserAuth.require_authenticated_user([])
assert conn.halted
assert redirected_to(conn) == ~p"/users/log-in"
assert Phoenix.Flash.get(conn.assigns.flash, :error) ==
"You must log in to access this page."
end
test "stores the path to redirect to on GET", %{conn: conn} do
halted_conn =
%{conn | path_info: ["foo"], query_string: ""}
|> fetch_flash()
|> UserAuth.require_authenticated_user([])
assert halted_conn.halted
assert get_session(halted_conn, :user_return_to) == "/foo"
halted_conn =
%{conn | path_info: ["foo"], query_string: "bar=baz"}
|> fetch_flash()
|> UserAuth.require_authenticated_user([])
assert halted_conn.halted
assert get_session(halted_conn, :user_return_to) == "/foo?bar=baz"
halted_conn =
%{conn | path_info: ["foo"], query_string: "bar", method: "POST"}
|> fetch_flash()
|> UserAuth.require_authenticated_user([])
assert halted_conn.halted
refute get_session(halted_conn, :user_return_to)
end
test "does not redirect if user is authenticated", %{conn: conn, user: user} do
conn =
conn
|> assign(:current_scope, Scope.for_user(user))
|> UserAuth.require_authenticated_user([])
refute conn.halted
refute conn.status
end
end
describe "on_mount :require_admin" do
setup %{conn: conn} do
%{conn: UserAuth.fetch_current_scope_for_user(conn, [])}
end
test "admits an admin", %{conn: conn} do
{:ok, user} = Accounts.update_user_role(user_fixture(), :admin)
user_token = Accounts.generate_user_session_token(user)
session = conn |> put_session(:user_token, user_token) |> get_session()
assert {:cont, updated_socket} =
UserAuth.on_mount(:require_admin, %{}, session, %LiveView.Socket{
endpoint: ChesstrainerWeb.Endpoint,
assigns: %{__changed__: %{}, flash: %{}}
})
assert updated_socket.assigns.current_scope.user.id == user.id
end
test "admits a super admin", %{conn: conn} do
{:ok, user} = Accounts.update_user_role(user_fixture(), :super_admin)
user_token = Accounts.generate_user_session_token(user)
session = conn |> put_session(:user_token, user_token) |> get_session()
assert {:cont, updated_socket} =
UserAuth.on_mount(:require_admin, %{}, session, %LiveView.Socket{
endpoint: ChesstrainerWeb.Endpoint,
assigns: %{__changed__: %{}, flash: %{}}
})
assert updated_socket.assigns.current_scope.user.id == user.id
end
test "redirects a member home", %{conn: conn} do
user = user_fixture()
user_token = Accounts.generate_user_session_token(user)
session = conn |> put_session(:user_token, user_token) |> get_session()
assert {:halt, updated_socket} =
UserAuth.on_mount(:require_admin, %{}, session, %LiveView.Socket{
endpoint: ChesstrainerWeb.Endpoint,
assigns: %{__changed__: %{}, flash: %{}}
})
assert {:redirect, %{to: "/"}} = updated_socket.redirected
end
test "redirects an unauthenticated visitor to log in", %{conn: conn} do
session = conn |> get_session()
assert {:halt, updated_socket} =
UserAuth.on_mount(:require_admin, %{}, session, %LiveView.Socket{
endpoint: ChesstrainerWeb.Endpoint,
assigns: %{__changed__: %{}, flash: %{}}
})
assert {:redirect, %{to: "/users/log-in"}} = updated_socket.redirected
end
end
describe "require_admin_user/2" do
setup %{conn: conn} do
%{conn: UserAuth.fetch_current_scope_for_user(conn, [])}
end
test "does not halt an admin", %{conn: conn} do
{:ok, user} = Accounts.update_user_role(user_fixture(), :admin)
conn =
conn
|> assign(:current_scope, Scope.for_user(user))
|> fetch_flash()
|> UserAuth.require_admin_user([])
refute conn.halted
refute conn.status
end
test "halts a member and redirects home", %{conn: conn} do
conn =
conn
|> assign(:current_scope, Scope.for_user(user_fixture()))
|> fetch_flash()
|> UserAuth.require_admin_user([])
assert conn.halted
assert redirected_to(conn) == ~p"/"
assert Phoenix.Flash.get(conn.assigns.flash, :error) ==
"You are not authorized to access this page."
end
test "redirects an unauthenticated visitor to log in", %{conn: conn} do
conn =
conn
|> assign(:current_scope, nil)
|> fetch_flash()
|> UserAuth.require_admin_user([])
assert conn.halted
assert redirected_to(conn) == ~p"/users/log-in"
assert Phoenix.Flash.get(conn.assigns.flash, :error) ==
"You must log in to access this page."
end
end
describe "disconnect_sessions/1" do
test "broadcasts disconnect messages for each token" do
tokens = [%{token: "token1"}, %{token: "token2"}]
for %{token: token} <- tokens do
ChesstrainerWeb.Endpoint.subscribe("users_sessions:#{Base.url_encode64(token)}")
end
UserAuth.disconnect_sessions(tokens)
assert_receive %Phoenix.Socket.Broadcast{
event: "disconnect",
topic: "users_sessions:dG9rZW4x"
}
assert_receive %Phoenix.Socket.Broadcast{
event: "disconnect",
topic: "users_sessions:dG9rZW4y"
}
end
end
end
+46
View File
@@ -0,0 +1,46 @@
defmodule Mix.Tasks.Accounts.PromoteTest do
use Chesstrainer.DataCase
import Chesstrainer.AccountsFixtures
import ExUnit.CaptureIO
alias Chesstrainer.Accounts
test "promotes a user by username" do
user = user_fixture()
output =
capture_io(fn -> Mix.Tasks.Accounts.Promote.run([user.username, "admin"]) end)
assert output =~ "role to admin"
assert Accounts.get_user!(user.id).role == :admin
end
test "promotes a user by email" do
user = user_fixture()
capture_io(fn -> Mix.Tasks.Accounts.Promote.run([user.email, "super_admin"]) end)
assert Accounts.get_user!(user.id).role == :super_admin
end
test "raises for an unknown role" do
user = user_fixture()
assert_raise Mix.Error, ~r/Unknown role/, fn ->
Mix.Tasks.Accounts.Promote.run([user.username, "wizard"])
end
end
test "raises when the user does not exist" do
assert_raise Mix.Error, ~r/No user found/, fn ->
Mix.Tasks.Accounts.Promote.run(["nobody@example.com", "admin"])
end
end
test "raises without the expected arguments" do
assert_raise Mix.Error, ~r/Usage/, fn ->
Mix.Tasks.Accounts.Promote.run([])
end
end
end
+65
View File
@@ -35,4 +35,69 @@ defmodule ChesstrainerWeb.ConnCase do
Chesstrainer.DataCase.setup_sandbox(tags) Chesstrainer.DataCase.setup_sandbox(tags)
{:ok, conn: Phoenix.ConnTest.build_conn()} {:ok, conn: Phoenix.ConnTest.build_conn()}
end end
@doc """
Setup helper that registers and logs in users.
setup :register_and_log_in_user
It stores an updated connection and a registered user in the
test context.
"""
def register_and_log_in_user(%{conn: conn} = context) do
user = Chesstrainer.AccountsFixtures.user_fixture()
scope = Chesstrainer.Accounts.Scope.for_user(user)
opts =
context
|> Map.take([:token_authenticated_at])
|> Enum.into([])
%{conn: log_in_user(conn, user, opts), user: user, scope: scope}
end
@doc """
Setup helper that registers and logs in an admin user.
setup :register_and_log_in_admin
It stores an updated connection and an admin user in the test context.
"""
def register_and_log_in_admin(%{conn: conn} = context) do
{:ok, user} =
Chesstrainer.Accounts.update_user_role(
Chesstrainer.AccountsFixtures.user_fixture(),
:admin
)
scope = Chesstrainer.Accounts.Scope.for_user(user)
opts =
context
|> Map.take([:token_authenticated_at])
|> Enum.into([])
%{conn: log_in_user(conn, user, opts), user: user, scope: scope}
end
@doc """
Logs the given `user` into the `conn`.
It returns an updated `conn`.
"""
def log_in_user(conn, user, opts \\ []) do
token = Chesstrainer.Accounts.generate_user_session_token(user)
maybe_set_token_authenticated_at(token, opts[:token_authenticated_at])
conn
|> Phoenix.ConnTest.init_test_session(%{})
|> Plug.Conn.put_session(:user_token, token)
end
defp maybe_set_token_authenticated_at(_token, nil), do: nil
defp maybe_set_token_authenticated_at(token, authenticated_at) do
Chesstrainer.AccountsFixtures.override_token_authenticated_at(token, authenticated_at)
end
end end
@@ -0,0 +1,72 @@
defmodule Chesstrainer.AccountsFixtures do
@moduledoc """
This module defines test helpers for creating
entities via the `Chesstrainer.Accounts` context.
"""
import Ecto.Query
alias Chesstrainer.Accounts
alias Chesstrainer.Accounts.Scope
def unique_user_email, do: "user#{System.unique_integer()}@example.com"
def unique_username, do: "user#{System.unique_integer([:positive])}"
def valid_user_password, do: "hello world!"
def valid_user_attributes(attrs \\ %{}) do
Enum.into(attrs, %{
email: unique_user_email(),
username: unique_username(),
password: valid_user_password()
})
end
def user_fixture(attrs \\ %{}) do
{:ok, user} =
attrs
|> valid_user_attributes()
|> Accounts.register_user()
user
end
def user_scope_fixture do
user = user_fixture()
user_scope_fixture(user)
end
def user_scope_fixture(user) do
Scope.for_user(user)
end
def set_password(user) do
{:ok, {user, _expired_tokens}} =
Accounts.update_user_password(user, %{password: valid_user_password()})
user
end
def extract_user_token(fun) do
{:ok, captured_email} = fun.(&"[TOKEN]#{&1}[TOKEN]")
[_, token | _] = String.split(captured_email.text_body, "[TOKEN]")
token
end
def override_token_authenticated_at(token, authenticated_at) when is_binary(token) do
Chesstrainer.Repo.update_all(
from(t in Accounts.UserToken,
where: t.token == ^token
),
set: [authenticated_at: authenticated_at]
)
end
def offset_user_token(token, amount_to_add, unit) do
dt = DateTime.add(DateTime.utc_now(:second), amount_to_add, unit)
Chesstrainer.Repo.update_all(
from(ut in Accounts.UserToken, where: ut.token == ^token),
set: [inserted_at: dt, authenticated_at: dt]
)
end
end