From bfe66d36325cd829d931bde018b1e6660a2911e7 Mon Sep 17 00:00:00 2001 From: dannyclarkdev Date: Sun, 13 Sep 2026 21:52:37 -0400 Subject: [PATCH 1/2] docs: plan slice 28, invite-only registration --- ...9-13-feat-invite-only-registration-plan.md | 96 +++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 docs/plans/2026-09-13-feat-invite-only-registration-plan.md diff --git a/docs/plans/2026-09-13-feat-invite-only-registration-plan.md b/docs/plans/2026-09-13-feat-invite-only-registration-plan.md new file mode 100644 index 0000000..add46a1 --- /dev/null +++ b/docs/plans/2026-09-13-feat-invite-only-registration-plan.md @@ -0,0 +1,96 @@ +--- +title: "feat: Invite-only registration" +type: feat +date: 2026-09-13 +status: implemented +brainstorm: docs/brainstorms/2026-09-02-demgem-campaign-manager-brainstorm.md +follows: docs/plans/2026-09-13-feat-character-sheet-plan.md +--- + +# feat: Invite-only registration + +## Overview + +The first production install went up today, and its owner's first question was why a stranger with the URL can make an account. Every player joins a campaign through a GM's invite link, so the register page has no honest reason to be public. This slice closes it to everyone but the person holding an invite, with one exception for the first account on a fresh install. + +| Feature | What it adds | +|---|---| +| `DEMGEM_REGISTRATION` | `invite`, the default, or `open`. One env key, one config value, read in one class. | +| The gate | `Support\Auth\RegistrationGate` answers one question: may this request make an account? Yes when the mode is open, when the session holds a valid invite, or when the install has no users yet. | +| The invite page for a guest | `/invites/{token}` no longer sends a guest to log in first. It shows the campaign and the role, offers "Create an account" and "Log in", and puts the token in the session. Both doors lead back to the invite. | +| The closed register page | A 403 with a sentence: demgem is invite only, ask your GM for a link. The login page drops its "Create an account" link at the same time. | +| Discord | "Continue with Discord" for someone nobody has seen is a registration too, and it goes through the same gate. A refused sign-in says why, and nothing is written. | + +When this slice is done, the owner registers the first account on an empty install, makes a campaign, and hands out invite links. A player taps one, sees "You are invited to join The Ashgrove Chronicle as a Player", presses "Create an account", registers, and lands back on the invite to press Join. Anyone who types `/register` gets a closed door. + +## Problem Statement + +**Registration is Fortify's stock feature, and it is public.** Anyone who finds the URL can make an account. They cannot see a campaign without an invite, so the exposure is bounded, but a public register page on a private table is still a page that takes accounts from strangers. + +**The invite link already is the credential.** The routes file says so about calendar feeds and invites both: the token in the URL is the proof. Registration should trust the same proof and nothing else. + +**A fresh install has nobody to send an invite.** The first account has to come from somewhere, and a bootstrap command that prints a password is worse than a register page that is open exactly once. + +## Proposed Solution + +**One class decides.** `RegistrationGate::allows(Request)` is the only place that reads the mode, the session, and the users table. Fortify's register view callback, `CreateNewUser`, and the Discord sign-in all ask it. Nothing else knows the rule. + +**The invite page is the front door.** Today a guest who opens an invite is bounced to the login page by the auth middleware, and the invite survives only as `url.intended`. Now the show route sits outside the auth group, and for a guest it remembers the token in the session under its own key and sets `url.intended` to itself. The accept route stays behind auth. After register, login, or Discord, every path already redirects to `intended`, so the guest lands back on the invite with a Join button. + +**The session holds a token, and the gate looks it up every time.** Storing the token rather than a flag means an invite revoked between the tap and the form closes the door with it. `CampaignInvite::findByToken()` and `isValid()` already exist. + +**The first user is the exception, and it is a fact about the table, not a flag.** `User::query()->exists()` is false exactly once. No setup command, no env flip, nothing to forget. + +## Technical Approach + +### No new dependency + +Fortify's view callback receives the request. `CreateNewUser` is resolved from the container, so it takes the gate and the request in its constructor. `SignInWithDiscord::handle()` gains a third parameter, `bool $mayRegister`, that the controller fills from the gate; the action throws `DiscordSignInRefused` at step 4 when it is false, before the insert. + +### The data + +None. One config file, `config/registration.php`, with `mode`. One session key, `registration.invite`, written by the invite page for guests and cleared on accept. + +### Scope and decisions + +- The default is `invite`. An install that upgrades becomes invite only, which is the safe direction and the one this slice exists for. `open` restores the old page for a public instance. +- A value that is neither `open` nor `invite` reads as `invite`. +- The closed page is a 403 with a view, not a redirect. A script that posts to `/register` without a pending invite gets a 403 and no row. +- The register page shows which campaign the invite is for, so the person knows the link did its job before they type a password. +- No CAPTCHA, no admin approval, no allow-list of email domains. The invite is the allow-list. + +### Screens + +- `auth/register`: an alert naming the campaign and role when an invite is pending. +- `auth/register-closed`: the 403 page. +- `auth/login`: the footer link to register shows only when the gate allows. +- `invites/show`: a guest branch with "Create an account" and "Log in". + +## Verification + +Feature tests in `tests/Feature/Auth/InviteOnlyRegistrationTest.php`: + +- The register page is 403 when users exist and no invite is in the session, and the POST writes nothing. +- The first account on an empty install registers. +- A guest who opens an invite sees the campaign, can register, and lands on the invite. +- An expired or revoked invite in the session does not open the page. +- `open` mode keeps the page public. +- The login page hides the register link when closed. +- A Discord sign-in for a new user is refused when closed and allowed with a pending invite. + +Existing tests in `AcceptInviteTest` and `DiscordLoginTest` change where a guest used to be bounced to login. + +## References + +- `docs/plans/2026-09-11-feat-discord-login-plan.md`, the Discord front door this slice gates. +- `.ai/rules/auth.md`, the order of outcomes in `SignInWithDiscord`. + +## Implementation Results — 2026-09-13 + +### What shipped, against the plan + +Everything in the table. The gate is 60 lines; the rest is wiring. + +### Deviations + +None. From 3363cb271efa996cb1826425551cd7415413fc9a Mon Sep 17 00:00:00 2001 From: dannyclarkdev Date: Sun, 13 Sep 2026 21:52:37 -0400 Subject: [PATCH 2/2] feat: invite-only registration The register page now takes two people: whoever holds a valid invite link, and the first person to reach an install that has no users yet. Everyone else gets a 403 that says to ask their GM for a link, and the login page stops offering to make an account. DEMGEM_REGISTRATION=open restores the public page. Support\Auth\RegistrationGate is the one place that decides. Fortify's register view, CreateNewUser, and SignInWithDiscord's new-account step all ask it. The gate looks the session's token up on every call, so an invite revoked between the tap and the form closes the door with it. An invite link is the front door for a guest now: /invites/{token} sits outside the auth group, shows the campaign and the role, offers "Create an account" and "Log in", and remembers the token and the intended URL so register, login, and Discord all land back on the invite. --- .ai/rules/auth.md | 3 + .env.docker.example | 5 + .env.example | 5 + README.md | 4 +- app/Actions/Auth/SignInWithDiscord.php | 12 +- app/Actions/Fortify/CreateNewUser.php | 12 ++ .../Auth/DiscordAuthController.php | 5 +- app/Http/Controllers/InviteController.php | 16 ++- app/Providers/FortifyServiceProvider.php | 11 +- app/Support/Auth/RegistrationGate.php | 71 +++++++++ config/registration.php | 19 +++ resources/views/auth/login.blade.php | 6 +- .../views/auth/register-closed.blade.php | 8 ++ resources/views/auth/register.blade.php | 4 + resources/views/invites/show.blade.php | 10 +- routes/web.php | 8 +- tests/Feature/Auth/DiscordLoginTest.php | 31 +++- .../Auth/InviteOnlyRegistrationTest.php | 136 ++++++++++++++++++ tests/Feature/Auth/RegistrationTest.php | 2 + tests/Feature/Invites/AcceptInviteTest.php | 15 +- 20 files changed, 366 insertions(+), 17 deletions(-) create mode 100644 app/Support/Auth/RegistrationGate.php create mode 100644 config/registration.php create mode 100644 resources/views/auth/register-closed.blade.php create mode 100644 tests/Feature/Auth/InviteOnlyRegistrationTest.php diff --git a/.ai/rules/auth.md b/.ai/rules/auth.md index 4d9779c..e105792 100644 --- a/.ai/rules/auth.md +++ b/.ai/rules/auth.md @@ -7,3 +7,6 @@ paths: ## The Discord callback has one order of outcomes, and an unverified email never links `SignInWithDiscord::handle()` decides in this order and no other: a `social_accounts` row for the Discord id signs that user in; a signed-in user (linking from the profile) gets the row; a user whose email matches is linked and signed in only when Discord's raw payload says `verified: true`, else refused with the notice to log in with the password and link from the profile; otherwise a new user with a random 40-character password. An unverified email linking to an existing account is the account-takeover path, so the check is defensive: no raw payload reads as unverified. Only `identify` and `email` scopes; never guilds. The avatar is kept only from `https://cdn.discordapp.com/`. Both routes 404 while `services.discord.client_id` or `client_secret` is empty, and `DiscordAuthController::isConfigured()` is the one place that asks. `social_accounts` is a person table like `users`: never exported. Tests swap `Socialite::driver('discord')` for a mock whose `user()` returns a `Laravel\Socialite\Two\User` with `setRaw([... 'verified' => ...])`; re-mocking the facade in one test does not work, so one outcome per test. + +## Every way to make an account asks RegistrationGate, and nothing else +Registration is invite only by default (config registration.mode, env DEMGEM_REGISTRATION). Support\Auth\RegistrationGate::allows() is the one place that reads the mode, the session token (registration.invite, written by the invite page for guests, cleared on accept) and the users table (the first user is the exception). Fortify's register view, CreateNewUser, and SignInWithDiscord's step 4 all ask it; a new door to an account must ask it too. The gate looks the token up on every call rather than remembering a flag, so a revoked invite closes the door with it. diff --git a/.env.docker.example b/.env.docker.example index e9ddb11..eff10d1 100644 --- a/.env.docker.example +++ b/.env.docker.example @@ -89,5 +89,10 @@ DISCORD_CLIENT_ID= DISCORD_CLIENT_SECRET= DISCORD_REDIRECT_URI="${APP_URL}/auth/discord/callback" +# Who may make an account. "invite", the default, opens the register page to +# whoever holds an invite link, plus the first person on an install with no users. +# "open" is a public register page. +DEMGEM_REGISTRATION=invite + # One ceiling on a campaign's files, in megabytes: cover, images, handout files. 0 turns it off. CAMPAIGN_STORAGE_MB=500 diff --git a/.env.example b/.env.example index 98664dd..2e155fe 100644 --- a/.env.example +++ b/.env.example @@ -85,5 +85,10 @@ DISCORD_CLIENT_ID= DISCORD_CLIENT_SECRET= DISCORD_REDIRECT_URI="${APP_URL}/auth/discord/callback" +# Who may make an account. "invite", the default, opens the register page to +# whoever holds an invite link, plus the first person on an install with no users. +# "open" is a public register page. +DEMGEM_REGISTRATION=invite + # One ceiling on a campaign's files, in megabytes: cover, images, handout files. 0 turns it off. CAMPAIGN_STORAGE_MB=500 diff --git a/README.md b/README.md index 87a41dd..330400d 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,8 @@ Slice 26 adds **family trees**. A relationship may carry a kinship, parent, chil Slice 27 adds **the 5e character sheet**, as a ruleset module. On a campaign on the SRD 5.2.1 rules a character's page carries a sheet: six ability scores, saving throw and skill proficiencies with expertise, hit points and hit dice, spell slots, armour class and speed, with every modifier, the proficiency bonus, every save and skill bonus, passive Perception and initiative computed from the scores and the level on every read and never stored. The character's player or a GM edits it, takes damage and healing on it, and presses "Long rest"; whoever may read the character reads it, and the party's pack from the ledger sits under it. The sheet lives in its own table behind `Ruleset::hasCharacterSheet()`, so a system-agnostic campaign never sees it, and it travels nested under its character in the export, the vault, and the API. +Slice 28 adds **invite-only registration**. The register page takes two people: whoever holds a valid invite link, and the first person to reach an install that has no users yet. Everyone else gets a closed door that says to ask their GM for a link, and the login page stops offering to make an account. An invite link is now the front door for a guest: it shows the campaign and the role, offers "Create an account" and "Log in", and both land back on the invite with a Join button. "Continue with Discord" for someone nobody has seen goes through the same gate. `DEMGEM_REGISTRATION=open` restores a public register page. + Your creatures travel in your export with the prose you wrote. A shipped creature never does — it is named in the file and nothing more, exactly as before. The CC BY notice follows the words rather than the table: a creature you wrote carries none, and a copy of a shipped one keeps the source and licence it came from, so the credit travels with the text. ## Local setup @@ -105,7 +107,7 @@ docker compose run --rm --no-deps app php artisan key:generate --show docker compose up -d ``` -Open and register. The first account is an ordinary account: demgem has no instance administrator and does not need one. +Open and register. The first account is an ordinary account: demgem has no instance administrator and does not need one. It is also the only account the register page takes on its own; after it, every account arrives through an invite link, unless `DEMGEM_REGISTRATION=open`. | Service | What it does | |---|---| diff --git a/app/Actions/Auth/SignInWithDiscord.php b/app/Actions/Auth/SignInWithDiscord.php index 361dbc5..b53477c 100644 --- a/app/Actions/Auth/SignInWithDiscord.php +++ b/app/Actions/Auth/SignInWithDiscord.php @@ -17,13 +17,15 @@ * 3. A user with this email: linked and signed in, when Discord says the email is * verified. Refused otherwise, because an unverified email is how an account is * taken over. - * 4. Nobody: a new user, with a random password they never see. + * 4. Nobody: a new user, with a random password they never see. That is a + * registration, so it happens only when the caller says the register page + * would have taken this person too. */ class SignInWithDiscord { public const PROVIDER = SocialAccount::DISCORD; - public function handle(ProviderUser $discord, ?User $current = null): User + public function handle(ProviderUser $discord, ?User $current = null, bool $mayRegister = true): User { $providerId = (string) $discord->getId(); @@ -31,7 +33,7 @@ public function handle(ProviderUser $discord, ?User $current = null): User throw new DiscordSignInRefused('Discord did not say who you are. Try again.'); } - return DB::transaction(function () use ($discord, $providerId, $current): User { + return DB::transaction(function () use ($discord, $providerId, $current, $mayRegister): User { $linked = SocialAccount::query() ->where('provider', self::PROVIDER) ->where('provider_id', $providerId) @@ -69,6 +71,10 @@ public function handle(ProviderUser $discord, ?User $current = null): User return $existing; } + if (! $mayRegister) { + throw new DiscordSignInRefused('demgem is invite only. Open the invite link your GM sent you, then continue with Discord from there.'); + } + $user = User::create([ 'name' => $this->nameFrom($discord), 'email' => $email, diff --git a/app/Actions/Fortify/CreateNewUser.php b/app/Actions/Fortify/CreateNewUser.php index ee2d712..c191dd8 100644 --- a/app/Actions/Fortify/CreateNewUser.php +++ b/app/Actions/Fortify/CreateNewUser.php @@ -3,6 +3,8 @@ namespace App\Actions\Fortify; use App\Models\User; +use App\Support\Auth\RegistrationGate; +use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\Rule; @@ -13,15 +15,25 @@ class CreateNewUser implements CreatesNewUsers { use PasswordValidationRules; + public function __construct( + private RegistrationGate $gate, + private Request $request, + ) {} + /** * Validate and create a newly registered user. * + * A POST with no pending invite on an invite-only install is a script, not a + * form: a bare 403 and no row, the same answer the register page gave. + * * @param array $input * * @throws ValidationException */ public function create(array $input): User { + abort_unless($this->gate->allows($this->request), 403, 'demgem is invite only.'); + Validator::make($input, [ 'name' => ['required', 'string', 'max:255'], 'email' => [ diff --git a/app/Http/Controllers/Auth/DiscordAuthController.php b/app/Http/Controllers/Auth/DiscordAuthController.php index 4df64ec..655c72f 100644 --- a/app/Http/Controllers/Auth/DiscordAuthController.php +++ b/app/Http/Controllers/Auth/DiscordAuthController.php @@ -6,6 +6,7 @@ use App\Actions\Auth\SignInWithDiscord; use App\Http\Controllers\Controller; use App\Models\User; +use App\Support\Auth\RegistrationGate; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; @@ -35,7 +36,7 @@ public function redirect(): RedirectResponse return $driver->scopes(['identify', 'email'])->redirect(); } - public function callback(Request $request, SignInWithDiscord $signIn): RedirectResponse + public function callback(Request $request, SignInWithDiscord $signIn, RegistrationGate $gate): RedirectResponse { abort_unless(self::isConfigured(), 404); @@ -54,7 +55,7 @@ public function callback(Request $request, SignInWithDiscord $signIn): RedirectR $current = Auth::user(); try { - $user = $signIn->handle($discord, $current); + $user = $signIn->handle($discord, $current, mayRegister: $gate->allows($request)); } catch (DiscordSignInRefused $refused) { return $current !== null ? redirect()->route('profile.edit')->with('status', $refused->getMessage()) diff --git a/app/Http/Controllers/InviteController.php b/app/Http/Controllers/InviteController.php index 47d71d6..709ad8e 100644 --- a/app/Http/Controllers/InviteController.php +++ b/app/Http/Controllers/InviteController.php @@ -5,6 +5,7 @@ use App\Actions\Invites\AcceptInvite; use App\Exceptions\InvalidInviteException; use App\Models\CampaignInvite; +use App\Support\Auth\RegistrationGate; use Illuminate\Contracts\View\View; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; @@ -12,7 +13,12 @@ class InviteController extends Controller { - public function show(Request $request, string $token): View|Response + /** + * Open to guests: the token in the URL is the credential. A guest is shown the + * campaign and the role, and the session remembers the invite so that register, + * login, and Discord all land back here. + */ + public function show(Request $request, string $token, RegistrationGate $gate): View|Response { $invite = CampaignInvite::findByToken($token); @@ -20,13 +26,17 @@ public function show(Request $request, string $token): View|Response return $this->invalid(); } + if ($request->user() === null) { + $gate->remember($request, $invite); + } + return view('invites.show', [ 'invite' => $invite, 'membership' => $invite->campaign->memberFor($request->user()), ]); } - public function accept(Request $request, string $token, AcceptInvite $acceptInvite): RedirectResponse|Response + public function accept(Request $request, string $token, AcceptInvite $acceptInvite, RegistrationGate $gate): RedirectResponse|Response { $invite = CampaignInvite::findByToken($token); @@ -34,6 +44,8 @@ public function accept(Request $request, string $token, AcceptInvite $acceptInvi return $this->invalid(); } + $gate->forget($request); + $campaign = $invite->campaign; if ($campaign->memberFor($request->user()) !== null) { diff --git a/app/Providers/FortifyServiceProvider.php b/app/Providers/FortifyServiceProvider.php index ba16656..0e10918 100644 --- a/app/Providers/FortifyServiceProvider.php +++ b/app/Providers/FortifyServiceProvider.php @@ -7,6 +7,7 @@ use App\Actions\Fortify\UpdateUserPassword; use App\Actions\Fortify\UpdateUserProfileInformation; use App\Http\Responses\RegisterResponse; +use App\Support\Auth\RegistrationGate; use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Http\Request; use Illuminate\Support\Facades\RateLimiter; @@ -30,7 +31,15 @@ public function boot(): void Fortify::resetUserPasswordsUsing(ResetUserPassword::class); Fortify::loginView(fn () => view('auth.login')); - Fortify::registerView(fn () => view('auth.register')); + Fortify::registerView(function (Request $request) { + $gate = app(RegistrationGate::class); + + if (! $gate->allows($request)) { + return response()->view('auth.register-closed', [], 403); + } + + return view('auth.register', ['invite' => $gate->pendingInvite($request)]); + }); Fortify::requestPasswordResetLinkView(fn () => view('auth.forgot-password')); Fortify::resetPasswordView(fn (Request $request) => view('auth.reset-password', ['request' => $request])); diff --git a/app/Support/Auth/RegistrationGate.php b/app/Support/Auth/RegistrationGate.php new file mode 100644 index 0000000..90cd3ef --- /dev/null +++ b/app/Support/Auth/RegistrationGate.php @@ -0,0 +1,71 @@ +isInviteOnly()) { + return true; + } + + if ($this->pendingInvite($request) !== null) { + return true; + } + + return ! User::query()->exists(); + } + + public function pendingInvite(Request $request): ?CampaignInvite + { + $token = $request->session()->get(self::SESSION_KEY); + + if (! is_string($token) || $token === '') { + return null; + } + + $invite = CampaignInvite::findByToken($token); + + return $invite !== null && $invite->isValid() ? $invite : null; + } + + /** + * A guest opened an invite. Every door they take next, register, login, or + * Discord, redirects to the intended URL, so the invite is that URL. + */ + public function remember(Request $request, CampaignInvite $invite): void + { + $request->session()->put(self::SESSION_KEY, $invite->token); + $request->session()->put('url.intended', $invite->url()); + } + + public function forget(Request $request): void + { + $request->session()->forget(self::SESSION_KEY); + } +} diff --git a/config/registration.php b/config/registration.php new file mode 100644 index 0000000..77dfec4 --- /dev/null +++ b/config/registration.php @@ -0,0 +1,19 @@ + env('DEMGEM_REGISTRATION', 'invite'), + +]; diff --git a/resources/views/auth/login.blade.php b/resources/views/auth/login.blade.php index 333f339..fd5a8ee 100644 --- a/resources/views/auth/login.blade.php +++ b/resources/views/auth/login.blade.php @@ -21,5 +21,9 @@ Log in - New here? Create an account + @if (app(\App\Support\Auth\RegistrationGate::class)->allows(request())) + New here? Create an account + @else + New here? Ask your GM for an invite link. + @endif diff --git a/resources/views/auth/register-closed.blade.php b/resources/views/auth/register-closed.blade.php new file mode 100644 index 0000000..aeb6875 --- /dev/null +++ b/resources/views/auth/register-closed.blade.php @@ -0,0 +1,8 @@ + +

demgem is invite only

+

An account comes with an invite. Ask your GM for the campaign's invite link, open it, and create your account from there.

+ + Log in + + Already have an invite link? Open it again; it brings you here with the door unlocked. +
diff --git a/resources/views/auth/register.blade.php b/resources/views/auth/register.blade.php index 7cc0086..9e37210 100644 --- a/resources/views/auth/register.blade.php +++ b/resources/views/auth/register.blade.php @@ -2,6 +2,10 @@

Create your account

One account for every table you run or play at.

+ @if ($invite) + You are joining {{ $invite->campaign->name }} as a {{ $invite->role->label() }}. Create your account and the invite is waiting on the other side. + @endif +
diff --git a/resources/views/invites/show.blade.php b/resources/views/invites/show.blade.php index d35b14b..80dd173 100644 --- a/resources/views/invites/show.blade.php +++ b/resources/views/invites/show.blade.php @@ -3,7 +3,11 @@

{{ $invite->campaign->name }}

as a {{ $invite->role->label() }}. {{ $invite->role->description() }}

- @if ($membership) + @if (auth()->guest()) +

You need an account to join. This link unlocks the register page; log in instead if you already have one.

+ Create an account + Log in + @elseif ($membership) You are already a member of this campaign as {{ $membership->role->label() }}. Open campaign @else @@ -13,5 +17,7 @@ @endif - Signed in as {{ auth()->user()->name }}. Your campaigns + @auth + Signed in as {{ auth()->user()->name }}. Your campaigns + @endauth diff --git a/routes/web.php b/routes/web.php index 06be89b..2295652 100644 --- a/routes/web.php +++ b/routes/web.php @@ -64,6 +64,13 @@ ->middleware('throttle:20,1') ->name('auth.discord.callback'); +// An invite is the front door for a player with no account yet, so the page that +// shows it is open to guests. The token in the URL is the credential, and a wrong one +// is a bare 404. Accepting stays behind auth. +Route::get('/invites/{token}', [InviteController::class, 'show']) + ->middleware('throttle:30,1') + ->name('invites.show'); + Route::middleware('auth')->group(function () { Route::get('/campaigns', CampaignsIndex::class)->name('campaigns.index'); Route::get('/campaigns/create', CampaignsCreate::class)->name('campaigns.create'); @@ -74,7 +81,6 @@ Route::get('/campaigns/import', CampaignsImport::class)->name('campaigns.import'); Route::get('/profile', ProfileEdit::class)->name('profile.edit'); - Route::get('/invites/{token}', [InviteController::class, 'show'])->name('invites.show'); Route::post('/invites/{token}', [InviteController::class, 'accept']) ->middleware('throttle:20,1') ->name('invites.accept'); diff --git a/tests/Feature/Auth/DiscordLoginTest.php b/tests/Feature/Auth/DiscordLoginTest.php index c6028b4..0fd4ee6 100644 --- a/tests/Feature/Auth/DiscordLoginTest.php +++ b/tests/Feature/Auth/DiscordLoginTest.php @@ -49,8 +49,8 @@ function discordSays(string $id, ?string $email, bool $verified = true, string $ $campaign = Campaign::factory()->create(); $invite = CampaignInvite::factory()->for($campaign)->create(); - // A guest opens the invite, is sent to log in, and continues with Discord. - $this->get(route('invites.show', $invite->token))->assertRedirect(route('login')); + // A guest opens the invite, which unlocks registration, and continues with Discord. + $this->get(route('invites.show', $invite->token))->assertOk(); discordSays('123456789012345678', 'tobin@example.test', verified: true, name: 'Tobin Ashgrove', avatar: 'https://cdn.discordapp.com/avatars/1/abc.png'); @@ -67,6 +67,33 @@ function discordSays(string $id, ?string $email, bool $verified = true, string $ ->and($user->socialAccount('discord')?->avatar_url)->toBe('https://cdn.discordapp.com/avatars/1/abc.png'); }); +it('refuses to make an account through Discord while registration is closed', function () { + User::factory()->create(); + + discordSays('555', 'stranger@example.test', verified: true); + + $this->get(route('auth.discord.callback', ['code' => 'x', 'state' => 'y'])) + ->assertRedirect(route('login')) + ->assertSessionHas('status', fn (string $status) => str_contains($status, 'invite only')); + + $this->assertGuest(); + expect(User::query()->where('email', 'stranger@example.test')->exists())->toBeFalse() + ->and(SocialAccount::query()->count())->toBe(0); +}); + +it('still signs a linked user in while registration is closed', function () { + User::factory()->create(); + $user = User::factory()->create(); + SocialAccount::factory()->for($user)->discord('42')->create(); + + discordSays('42', 'other@example.test'); + + $this->get(route('auth.discord.callback', ['code' => 'x', 'state' => 'y'])) + ->assertRedirect(route('campaigns.index')); + + $this->assertAuthenticatedAs($user); +}); + it('signs a linked user in without touching their name', function () { $user = User::factory()->create(['name' => 'Danny']); SocialAccount::factory()->for($user)->discord('42')->create(); diff --git a/tests/Feature/Auth/InviteOnlyRegistrationTest.php b/tests/Feature/Auth/InviteOnlyRegistrationTest.php new file mode 100644 index 0000000..272f033 --- /dev/null +++ b/tests/Feature/Auth/InviteOnlyRegistrationTest.php @@ -0,0 +1,136 @@ + 'Tobin Ashgrove', + 'email' => $email, + 'password' => 'correct-horse-battery', + 'password_confirmation' => 'correct-horse-battery', + ]; +} + +it('closes the register page once the install has a user and no invite is pending', function () { + User::factory()->create(); + + $this->get(route('register')) + ->assertForbidden() + ->assertSee('invite only'); + + $this->post(route('register'), registerPayload())->assertForbidden(); + + $this->assertGuest(); + expect(User::query()->count())->toBe(1); +}); + +it('lets the first person on an empty install register', function () { + $this->get(route('register'))->assertOk()->assertSee('Create your account'); + + $this->post(route('register'), registerPayload())->assertRedirect(route('campaigns.index')); + + $this->assertAuthenticated(); +}); + +it('opens the register page to a guest who opened an invite, and lands them on it', function () { + $campaign = Campaign::factory()->create(['name' => 'The Ashgrove Chronicle']); + $invite = CampaignInvite::factory()->for($campaign)->role(CampaignRole::Player)->create(); + + $this->get($invite->url()) + ->assertOk() + ->assertSee('The Ashgrove Chronicle') + ->assertSee('Create an account') + ->assertSessionHas(RegistrationGate::SESSION_KEY, $invite->token) + ->assertSessionHas('url.intended', $invite->url()); + + $this->get(route('register')) + ->assertOk() + ->assertSee('You are joining') + ->assertSee('The Ashgrove Chronicle'); + + $this->post(route('register'), registerPayload())->assertRedirect($invite->url()); + + $this->assertAuthenticated(); + + $this->post(route('invites.accept', $invite->token)) + ->assertRedirect(route('campaigns.show', $campaign)) + ->assertSessionMissing(RegistrationGate::SESSION_KEY); + + $user = User::query()->where('email', 'tobin@example.test')->firstOrFail(); + + expect($campaign->fresh()->roleFor($user))->toBe(CampaignRole::Player); +}); + +it('does not open the page for an invite that died after it was opened', function () { + User::factory()->create(); + $invite = CampaignInvite::factory()->create(); + + $this->get($invite->url())->assertOk(); + + $invite->forceFill(['revoked_at' => now()])->save(); + + $this->get(route('register'))->assertForbidden(); + $this->post(route('register'), registerPayload())->assertForbidden(); + + $this->assertGuest(); +}); + +it('does not open the page for a token that was never an invite', function () { + User::factory()->create(); + + $this->withSession([RegistrationGate::SESSION_KEY => 'not-a-token']) + ->get(route('register')) + ->assertForbidden(); +}); + +it('keeps a public register page in open mode', function () { + config()->set('registration.mode', 'open'); + User::factory()->create(); + + $this->get(route('register'))->assertOk()->assertSee('Create your account'); + $this->post(route('register'), registerPayload())->assertRedirect(route('campaigns.index')); + + $this->assertAuthenticated(); +}); + +it('reads any other mode as invite', function () { + config()->set('registration.mode', 'yes please'); + User::factory()->create(); + + $this->get(route('register'))->assertForbidden(); +}); + +it('offers the register link on the login page only while the door is open', function () { + $this->get(route('login'))->assertOk()->assertSee('Create an account'); + + User::factory()->create(); + + $this->get(route('login')) + ->assertOk() + ->assertDontSee('Create an account') + ->assertSee('Ask your GM for an invite link'); + + $invite = CampaignInvite::factory()->create(); + $this->get($invite->url())->assertOk(); + + $this->get(route('login'))->assertOk()->assertSee('Create an account'); +}); + +it('sends a logged in user straight to the join button without touching the session', function () { + $invite = CampaignInvite::factory()->create(); + + $this->actingAs(User::factory()->create()) + ->get($invite->url()) + ->assertOk() + ->assertSee('Join') + ->assertDontSee('Create an account') + ->assertSessionMissing(RegistrationGate::SESSION_KEY); +}); diff --git a/tests/Feature/Auth/RegistrationTest.php b/tests/Feature/Auth/RegistrationTest.php index 1b55859..15654e7 100644 --- a/tests/Feature/Auth/RegistrationTest.php +++ b/tests/Feature/Auth/RegistrationTest.php @@ -42,6 +42,8 @@ }); it('rejects an email that is already registered', function () { + // A user exists, so the invite-only default would close the page first. + config()->set('registration.mode', 'open'); User::factory()->create(['email' => 'taken@example.com']); $this->post(route('register'), [ diff --git a/tests/Feature/Invites/AcceptInviteTest.php b/tests/Feature/Invites/AcceptInviteTest.php index 7cd6ab5..b36c904 100644 --- a/tests/Feature/Invites/AcceptInviteTest.php +++ b/tests/Feature/Invites/AcceptInviteTest.php @@ -5,14 +5,25 @@ use App\Models\CampaignInvite; use App\Models\User; -it('sends a guest to login and remembers the invite url', function () { +it('shows a guest the invite, remembers it, and sends them to register or log in', function () { $invite = CampaignInvite::factory()->create(); $this->get($invite->url()) - ->assertRedirect(route('login')) + ->assertOk() + ->assertSee($invite->campaign->name) + ->assertSee('Create an account') + ->assertSee('Log in') ->assertSessionHas('url.intended', $invite->url()); }); +it('keeps accepting behind the login', function () { + $invite = CampaignInvite::factory()->create(); + + $this->post(route('invites.accept', $invite->token))->assertRedirect(route('login')); + + expect($invite->fresh()->uses)->toBe(0); +}); + it('shows the campaign name and role to a logged in non-member', function () { $invite = CampaignInvite::factory()->role(CampaignRole::Player)->create();