diff --git a/lib/chesstrainer_web/controllers/robots_controller.ex b/lib/chesstrainer_web/controllers/robots_controller.ex
index 62e0062..b3e0b90 100644
--- a/lib/chesstrainer_web/controllers/robots_controller.ex
+++ b/lib/chesstrainer_web/controllers/robots_controller.ex
@@ -9,15 +9,25 @@ defmodule ChesstrainerWeb.RobotsController do
use ChesstrainerWeb, :controller
def index(conn, _params) do
- body = """
- User-agent: *
- Allow: /
+ body =
+ if prelaunch?() do
+ """
+ User-agent: *
+ Disallow: /
+ """
+ else
+ """
+ User-agent: *
+ Allow: /
- Sitemap: #{url(conn, ~p"/sitemap.xml")}
- """
+ Sitemap: #{url(conn, ~p"/sitemap.xml")}
+ """
+ end
conn
|> put_resp_content_type("text/plain")
|> send_resp(200, body)
end
+
+ defp prelaunch?, do: Application.get_env(:chesstrainer, :prelaunch, false)
end
diff --git a/lib/chesstrainer_web/controllers/user_session_controller.ex b/lib/chesstrainer_web/controllers/user_session_controller.ex
index 81ed66e..def9622 100644
--- a/lib/chesstrainer_web/controllers/user_session_controller.ex
+++ b/lib/chesstrainer_web/controllers/user_session_controller.ex
@@ -5,20 +5,28 @@ defmodule ChesstrainerWeb.UserSessionController do
alias ChesstrainerWeb.UserAuth
def create(conn, %{"user" => user_params}) do
+ authenticate(conn, user_params, ~p"/users/log-in", nil)
+ end
+
+ def create_admin(conn, %{"user" => user_params}) do
+ if ChesstrainerWeb.prelaunch?() do
+ authenticate(conn, user_params, ~p"/admin/log-in", ~p"/admin/endgames")
+ else
+ authenticate(conn, user_params, ~p"/users/log-in", nil)
+ end
+ end
+
+ defp authenticate(conn, user_params, failure_path, success_path) 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")
+ invalid_credentials(conn, login, failure_path)
user ->
if user.confirmed_at do
conn
+ |> maybe_put_return_to(success_path)
|> put_flash(:info, "Welcome back!")
|> UserAuth.log_in_user(user, user_params)
else
@@ -30,14 +38,21 @@ defmodule ChesstrainerWeb.UserSessionController do
# In order to prevent user enumeration attacks, report the same error
# as invalid credentials.
- conn
- |> put_flash(:error, "Invalid email, username or password")
- |> put_flash(:email, String.slice(login, 0, 160))
- |> redirect(to: ~p"/users/log-in")
+ invalid_credentials(conn, login, failure_path)
end
end
end
+ defp invalid_credentials(conn, login, path) do
+ conn
+ |> put_flash(:error, "Invalid email, username or password")
+ |> put_flash(:email, String.slice(login, 0, 160))
+ |> redirect(to: path)
+ end
+
+ defp maybe_put_return_to(conn, nil), do: conn
+ defp maybe_put_return_to(conn, path), do: put_session(conn, :user_return_to, path)
+
def update_password(conn, %{"user" => user_params}) do
user = conn.assigns.current_scope.user
true = Accounts.sudo_mode?(user)
diff --git a/lib/chesstrainer_web/live/user_live/login.ex b/lib/chesstrainer_web/live/user_live/login.ex
index c086b26..6429d92 100644
--- a/lib/chesstrainer_web/live/user_live/login.ex
+++ b/lib/chesstrainer_web/live/user_live/login.ex
@@ -11,7 +11,7 @@ defmodule ChesstrainerWeb.UserLive.Login do
<%= 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-primary-text hover:underline"
@@ -25,7 +25,7 @@ defmodule ChesstrainerWeb.UserLive.Login do
:let={f}
for={@form}
id="login_form_password"
- action={~p"/users/log-in"}
+ action={@login_action}
phx-submit="submit_password"
phx-trigger-action={@trigger_submit}
>
@@ -73,8 +73,18 @@ defmodule ChesstrainerWeb.UserLive.Login do
get_in(socket.assigns, [:current_scope, Access.key(:user), Access.key(:email)])
form = to_form(%{"email" => email}, as: "user")
+ prelaunch = ChesstrainerWeb.prelaunch?()
- {:ok, assign(socket, form: form, trigger_submit: false)}
+ login_action =
+ if prelaunch, do: ~p"/admin/log-in", else: ~p"/users/log-in"
+
+ {:ok,
+ assign(socket,
+ form: form,
+ trigger_submit: false,
+ prelaunch: prelaunch,
+ login_action: login_action
+ )}
end
@impl true
diff --git a/lib/chesstrainer_web/live/user_live/registration.ex b/lib/chesstrainer_web/live/user_live/registration.ex
index 059031e..2d942ef 100644
--- a/lib/chesstrainer_web/live/user_live/registration.ex
+++ b/lib/chesstrainer_web/live/user_live/registration.ex
@@ -74,19 +74,40 @@ defmodule ChesstrainerWeb.UserLive.Registration do
end
@impl true
- def mount(_params, _session, %{assigns: %{current_scope: %{user: user}}} = socket)
- when not is_nil(user) do
+ def mount(_params, _session, socket) do
+ if prelaunch?() do
+ {:ok, redirect(socket, to: ~p"/")}
+ else
+ do_mount(socket)
+ end
+ end
+
+ @impl true
+ def handle_event("save", %{"user" => user_params}, socket) do
+ if prelaunch?() do
+ {:noreply, push_navigate(socket, to: ~p"/")}
+ else
+ save_registration(socket, user_params)
+ 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 do_mount(%{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
+ defp do_mount(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
+ defp save_registration(socket, user_params) do
case Accounts.register_user(user_params) do
{:ok, user} ->
if user.mailing_list, do: MailingList.subscribe_user(user)
@@ -110,10 +131,7 @@ defmodule ChesstrainerWeb.UserLive.Registration do
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 prelaunch?, do: Application.get_env(:chesstrainer, :prelaunch, false)
defp assign_form(socket, %Ecto.Changeset{} = changeset) do
form = to_form(changeset, as: "user")
diff --git a/lib/chesstrainer_web/plugs/prelaunch.ex b/lib/chesstrainer_web/plugs/prelaunch.ex
new file mode 100644
index 0000000..94624a7
--- /dev/null
+++ b/lib/chesstrainer_web/plugs/prelaunch.ex
@@ -0,0 +1,57 @@
+defmodule ChesstrainerWeb.Plugs.Prelaunch do
+ @moduledoc """
+ Redirects every non-public route to the home page while the app is gated.
+
+ The allowlist is deliberately small: legal pages, the mailing list, auth
+ entry points, admin, crawler files, health, and the static/LiveView plumbing.
+ Everything else redirects to `/` with `X-Robots-Tag: noindex, nofollow`.
+
+ Set `PRELAUNCH=true` to enable the gate.
+ """
+
+ import Plug.Conn
+
+ @allowed_exact ~w(
+ /
+ /privacy
+ /terms-conditions
+ /health
+ /robots.txt
+ /sitemap.xml
+ /favicon.ico
+ )
+
+ @allowed_prefixes ~w(
+ /mailing-list
+ /users/log-out
+ /users/confirm
+ /users/reset-password
+ /users/settings
+ /admin
+ /live
+ /assets
+ /fonts
+ /images
+ /dev
+ )
+
+ def init(opts), do: opts
+
+ def call(conn, _opts) do
+ if enabled?() and not allowed?(conn.request_path) do
+ conn
+ |> put_resp_header("x-robots-tag", "noindex, nofollow")
+ |> Phoenix.Controller.redirect(to: "/")
+ |> halt()
+ else
+ conn
+ end
+ end
+
+ defp enabled?, do: Application.get_env(:chesstrainer, :prelaunch, false)
+
+ defp allowed?(path) do
+ path in @allowed_exact or
+ Enum.any?(@allowed_prefixes, &String.starts_with?(path, &1))
+ end
+end
diff --git a/lib/chesstrainer_web/router.ex b/lib/chesstrainer_web/router.ex
index abe16de..54d8deb 100644
--- a/lib/chesstrainer_web/router.ex
+++ b/lib/chesstrainer_web/router.ex
@@ -10,6 +10,7 @@ defmodule ChesstrainerWeb.Router do
plug :put_root_layout, html: {ChesstrainerWeb.Layouts, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
+ plug ChesstrainerWeb.Plugs.Prelaunch
plug :fetch_current_scope_for_user
end
@@ -34,13 +35,17 @@ defmodule ChesstrainerWeb.Router do
get "/terms-conditions", PageController, :terms_conditions
post "/mailing-list", MailingListController, :create
get "/mailing-list/confirm/:token", MailingListController, :confirm
+ post "/admin/log-in", UserSessionController, :create_admin
end
scope "/admin", ChesstrainerWeb do
pipe_through [:browser, :noindex, :require_admin_user]
live_session :endgames,
- on_mount: [{ChesstrainerWeb.UserAuth, :require_admin}] do
+ on_mount: [
+ {ChesstrainerWeb.UserAuth, :enforce_prelaunch},
+ {ChesstrainerWeb.UserAuth, :require_admin}
+ ] do
live "/endgames", EndgameLive.Index, :index
live "/endgames/new", EndgameLive.Form, :new
live "/endgames/:id", EndgameLive.Show, :show
@@ -76,7 +81,10 @@ defmodule ChesstrainerWeb.Router do
pipe_through [:browser, :require_authenticated_user]
live_session :require_authenticated_user,
- on_mount: [{ChesstrainerWeb.UserAuth, :require_authenticated}] do
+ on_mount: [
+ {ChesstrainerWeb.UserAuth, :enforce_prelaunch},
+ {ChesstrainerWeb.UserAuth, :require_authenticated}
+ ] do
live "/endgames", EndgameLive.PlayerIndex, :index
live "/train", EndgameLive.Train, :train
live "/users/profile", UserLive.Profile, :account
@@ -95,11 +103,15 @@ defmodule ChesstrainerWeb.Router do
pipe_through [:browser]
live_session :current_user,
- on_mount: [{ChesstrainerWeb.UserAuth, :mount_current_scope}] do
+ on_mount: [
+ {ChesstrainerWeb.UserAuth, :enforce_prelaunch},
+ {ChesstrainerWeb.UserAuth, :mount_current_scope}
+ ] do
live "/guest-train", EndgameLive.GuestTrain, :play
live "/endgames/:public_code/play", EndgameLive.Play, :play
live "/users/register", UserLive.Registration, :new
live "/users/log-in", UserLive.Login, :new
+ live "/admin/log-in", UserLive.Login, :new
live "/users/reset-password", UserLive.ResetPassword, :new
live "/users/reset-password/:token", UserLive.ResetPassword, :edit
end
@@ -115,6 +127,7 @@ defmodule ChesstrainerWeb.Router do
scope "/", ChesstrainerWeb do
pipe_through :seo
+ get "/health", HealthController, :index
get "/robots.txt", RobotsController, :index
get "/sitemap.xml", SitemapController, :index
end
diff --git a/lib/chesstrainer_web/user_auth.ex b/lib/chesstrainer_web/user_auth.ex
index dbc3a28..7e104c9 100644
--- a/lib/chesstrainer_web/user_auth.ex
+++ b/lib/chesstrainer_web/user_auth.ex
@@ -212,6 +212,24 @@ defmodule ChesstrainerWeb.UserAuth do
live "/profile", ProfileLive, :index
end
"""
+ @prelaunch_allowed_views [
+ ChesstrainerWeb.UserLive.Login,
+ ChesstrainerWeb.UserLive.ResetPassword,
+ ChesstrainerWeb.UserLive.Profile,
+ ChesstrainerWeb.EndgameLive.Index,
+ ChesstrainerWeb.EndgameLive.Form,
+ ChesstrainerWeb.EndgameLive.Show
+ ]
+
+ def on_mount(:enforce_prelaunch, _params, _session, socket) do
+ if Application.get_env(:chesstrainer, :prelaunch, false) and
+ socket.view not in @prelaunch_allowed_views do
+ {:halt, Phoenix.LiveView.redirect(socket, to: ~p"/")}
+ else
+ {:cont, socket}
+ end
+ end
+
def on_mount(:mount_current_scope, _params, session, socket) do
{:cont, mount_current_scope(socket, session)}
end
diff --git a/mise.toml b/mise.toml
new file mode 100644
index 0000000..561e857
--- /dev/null
+++ b/mise.toml
@@ -0,0 +1,4 @@
+[tools]
+erlang = "28.5"
+elixir = "1.19.5-otp-28"
+rust = "1.98.1"
diff --git a/test/chesstrainer_web/controllers/mailing_list_controller_test.exs b/test/chesstrainer_web/controllers/mailing_list_controller_test.exs
index b2a1de7..0d4463d 100644
--- a/test/chesstrainer_web/controllers/mailing_list_controller_test.exs
+++ b/test/chesstrainer_web/controllers/mailing_list_controller_test.exs
@@ -1,5 +1,5 @@
defmodule ChesstrainerWeb.MailingListControllerTest do
- use ChesstrainerWeb.ConnCase, async: true
+ use ChesstrainerWeb.ConnCase, async: false
alias Chesstrainer.MailingList
alias Chesstrainer.MailingList.Subscriber
@@ -169,6 +169,22 @@ defmodule ChesstrainerWeb.MailingListControllerTest do
assert redirected_to(conn) == "/#mailing-list"
assert Phoenix.Flash.get(conn.assigns.flash, :error) =~ "valid email address"
end
+
+ test "rejects signups when the mailing list is disabled", %{conn: conn} do
+ previous = Application.get_env(:chesstrainer, :mailing_list_enabled)
+ on_exit(fn -> restore_env(:mailing_list_enabled, previous) end)
+ Application.put_env(:chesstrainer, :mailing_list_enabled, false)
+
+ conn =
+ post(conn, ~p"/mailing-list",
+ subscriber: %{email: "player@example.com", form_token: form_token()}
+ )
+
+ assert redirected_to(conn) == "/#mailing-list"
+ assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "isn't open yet"
+ refute_received {:email, _email}
+ assert Repo.aggregate(Subscriber, :count) == 0
+ end
end
describe "GET /mailing-list/confirm/:token" do
@@ -227,4 +243,7 @@ defmodule ChesstrainerWeb.MailingListControllerTest do
defp form_token do
MailingListFormToken.sign(System.system_time(:second) - 5)
end
+
+ defp restore_env(key, nil), do: Application.delete_env(:chesstrainer, key)
+ defp restore_env(key, value), do: Application.put_env(:chesstrainer, key, value)
end
diff --git a/test/chesstrainer_web/controllers/page_controller_test.exs b/test/chesstrainer_web/controllers/page_controller_test.exs
index e72c266..bbd96c5 100644
--- a/test/chesstrainer_web/controllers/page_controller_test.exs
+++ b/test/chesstrainer_web/controllers/page_controller_test.exs
@@ -180,6 +180,29 @@ defmodule ChesstrainerWeb.PageControllerTest do
assert LazyHTML.text(LazyHTML.query(document, ".rating-note strong")) == "0"
end
+ test "renders the coming soon page while prelaunch is on", %{conn: conn} do
+ previous = Application.get_env(:chesstrainer, :prelaunch)
+ on_exit(fn -> restore_env(:prelaunch, previous) end)
+ Application.put_env(:chesstrainer, :prelaunch, true)
+
+ html = conn |> get(~p"/") |> html_response(200)
+
+ assert html =~ "coming soon"
+ assert html =~ "Master the"
+ refute html =~ "Try today"
+ end
+
+ test "hides the mailing list when it is disabled", %{conn: conn} do
+ previous = Application.get_env(:chesstrainer, :mailing_list_enabled)
+ on_exit(fn -> restore_env(:mailing_list_enabled, previous) end)
+ Application.put_env(:chesstrainer, :mailing_list_enabled, false)
+
+ html = conn |> get(~p"/") |> html_response(200)
+
+ refute html =~ ~s(id="mailing-list-form")
+ refute html =~ "Join the list"
+ end
+
test "renders the mailing list signup form", %{conn: conn} do
html = conn |> get(~p"/") |> html_response(200)
document = LazyHTML.from_document(html)
@@ -305,4 +328,7 @@ defmodule ChesstrainerWeb.PageControllerTest do
assert html =~ "Browse puzzles"
assert html =~ ~s(href="/endgames")
end
+
+ defp restore_env(key, nil), do: Application.delete_env(:chesstrainer, key)
+ defp restore_env(key, value), do: Application.put_env(:chesstrainer, key, value)
end
diff --git a/test/chesstrainer_web/controllers/robots_controller_test.exs b/test/chesstrainer_web/controllers/robots_controller_test.exs
index 0f0adfe..c8eb6b0 100644
--- a/test/chesstrainer_web/controllers/robots_controller_test.exs
+++ b/test/chesstrainer_web/controllers/robots_controller_test.exs
@@ -1,5 +1,5 @@
defmodule ChesstrainerWeb.RobotsControllerTest do
- use ChesstrainerWeb.ConnCase, async: true
+ use ChesstrainerWeb.ConnCase, async: false
alias ChesstrainerWeb.Endpoint
@@ -18,5 +18,20 @@ defmodule ChesstrainerWeb.RobotsControllerTest do
assert [content_type] = get_resp_header(conn, "content-type")
assert content_type =~ "text/plain"
end
+
+ test "disallows crawlers while prelaunch is on", %{conn: conn} do
+ previous = Application.get_env(:chesstrainer, :prelaunch)
+ on_exit(fn -> restore_env(:prelaunch, previous) end)
+ Application.put_env(:chesstrainer, :prelaunch, true)
+
+ body = conn |> get(~p"/robots.txt") |> response(200)
+
+ assert body =~ "User-agent: *"
+ assert body =~ "Disallow: /"
+ refute body =~ "Allow: /"
+ end
end
+
+ defp restore_env(key, nil), do: Application.delete_env(:chesstrainer, key)
+ defp restore_env(key, value), do: Application.put_env(:chesstrainer, key, value)
end
diff --git a/test/chesstrainer_web/plugs/prelaunch_test.exs b/test/chesstrainer_web/plugs/prelaunch_test.exs
new file mode 100644
index 0000000..43acc04
--- /dev/null
+++ b/test/chesstrainer_web/plugs/prelaunch_test.exs
@@ -0,0 +1,85 @@
+defmodule ChesstrainerWeb.Plugs.PrelaunchTest do
+ use ChesstrainerWeb.ConnCase, async: false
+
+ import Chesstrainer.AccountsFixtures
+ import Phoenix.LiveViewTest
+
+ alias Chesstrainer.Accounts.User
+ alias Chesstrainer.Repo
+
+ setup do
+ previous = Application.get_env(:chesstrainer, :prelaunch)
+ on_exit(fn -> restore_env(:prelaunch, previous) end)
+ Application.put_env(:chesstrainer, :prelaunch, true)
+ :ok
+ end
+
+ test "allows the public pages, legal pages, health, and admin login", %{conn: conn} do
+ assert conn |> get(~p"/") |> html_response(200)
+ assert conn |> get(~p"/privacy") |> html_response(200)
+ assert conn |> get(~p"/terms-conditions") |> html_response(200)
+ assert conn |> get(~p"/health") |> response(200)
+ assert conn |> get(~p"/admin/log-in") |> html_response(200)
+ end
+
+ test "hides public auth links and start training", %{conn: conn} do
+ html = conn |> get(~p"/") |> html_response(200)
+
+ refute html =~ ">Log in<"
+ refute html =~ ">Register<"
+ refute html =~ "Start training"
+ end
+
+ test "the hidden admin login uses the admin form action", %{conn: conn} do
+ html = conn |> get(~p"/admin/log-in") |> html_response(200)
+
+ assert html =~ ~s(action="/admin/log-in")
+ refute html =~ "Sign up"
+ end
+
+ test "pauses the public login route", %{conn: conn} do
+ assert conn |> get(~p"/users/log-in") |> redirected_to() == "/"
+ end
+
+ test "admin login redirects to the admin area", %{conn: conn} do
+ user =
+ user_fixture()
+ |> Ecto.Changeset.change(role: :admin)
+ |> Repo.update!()
+
+ conn =
+ post(conn, ~p"/admin/log-in",
+ user: %{email: user.email, password: "hello world!", remember_me: "true"}
+ )
+
+ assert redirected_to(conn) == "/admin/endgames"
+ end
+
+ test "redirects blocked routes to the home page", %{conn: conn} do
+ conn = get(conn, ~p"/train")
+
+ assert redirected_to(conn) == "/"
+ assert get_resp_header(conn, "x-robots-tag") == ["noindex, nofollow"]
+ end
+
+ test "redirects registration and unknown pages", %{conn: conn} do
+ assert conn |> get(~p"/users/register") |> redirected_to() == "/"
+ assert conn |> get("/definitely-not-a-page") |> redirected_to() == "/"
+ end
+
+ test "blocks direct registration LiveView requests", %{conn: conn} do
+ assert {:error, {:redirect, %{to: "/"}}} = live(conn, ~p"/users/register")
+ end
+
+ test "blocks registration reached through LiveView navigation", %{conn: conn} do
+ {:ok, view, _html} = live(conn, ~p"/admin/log-in")
+
+ assert {:error, {:redirect, %{to: "/"}}} =
+ live_redirect(view, to: ~p"/users/register")
+
+ assert Repo.aggregate(User, :count) == 0
+ end
+
+ defp restore_env(key, nil), do: Application.delete_env(:chesstrainer, key)
+ defp restore_env(key, value), do: Application.put_env(:chesstrainer, key, value)
+end