feat: registration checks name rules and uniqueness, email, password and accepted terms, and names the wrong field; players get protected_until and last_active_at

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-30 11:13:57 +01:00
parent 64f0d40256
commit fcdcb089cc
4 changed files with 79 additions and 21 deletions

View File

@ -10,28 +10,40 @@ use Illuminate\Support\Facades\Hash;
/** Issues the bearer token the WS client sends when it subscribes. Everything else is WS. */ /** Issues the bearer token the WS client sends when it subscribes. Everything else is WS. */
class AuthController extends Controller class AuthController extends Controller
{ {
/** 3 to 24 characters: letters, digits, and spaces, dots, dashes or underscores inside. */
public const NAME = '/^[\p{L}\p{N}][\p{L}\p{N} ._\-]{1,22}[\p{L}\p{N}]$/u';
/**
* A new account. Every refusal names the field and a code the client translates, so
* the form can mark the right field.
*/
public function register(Request $request): JsonResponse public function register(Request $request): JsonResponse
{ {
$data = $request->validate([ $name = trim((string) $request->input('name'));
'name' => ['required', 'string', 'max:40'], $email = mb_strtolower(trim((string) $request->input('email')));
'email' => ['required', 'email', 'max:255'], $password = (string) $request->input('password');
'password' => ['required', 'string', 'min:8', 'max:255'],
]); $refusal = match (true) {
if (User::where('email', $data['email'])->exists()) { ! preg_match(self::NAME, $name) || str_contains($name, ' ') => ['name', 'name_invalid', 'Names are 3 to 24 letters, digits, spaces, dots, dashes or underscores.'],
return $this->refuse('email_taken', 'This email is already registered.'); User::whereRaw('LOWER(name) = ?', [mb_strtolower($name)])->exists() => ['name', 'name_taken', 'That name is taken.'],
! filter_var($email, FILTER_VALIDATE_EMAIL) || mb_strlen($email) > 255 => ['email', 'email_invalid', 'That is not an email address.'],
User::where('email', $email)->exists() => ['email', 'email_taken', 'This email is already registered.'],
mb_strlen($password) < 8 || mb_strlen($password) > 255 => ['password', 'password_short', 'Passwords are at least 8 characters.'],
! $request->boolean('terms') => ['terms', 'terms_required', 'Accept the terms to play.'],
default => null,
};
if ($refusal) {
return $this->refuse($refusal[1], $refusal[2], $refusal[0]);
} }
return $this->issue(User::create($data)); return $this->issue(User::create(['name' => $name, 'email' => $email, 'password' => $password, 'terms_accepted_at' => now()]));
} }
public function login(Request $request): JsonResponse public function login(Request $request): JsonResponse
{ {
$data = $request->validate([ $email = mb_strtolower(trim((string) $request->input('email')));
'email' => ['required', 'email'], $user = User::where('email', $email)->first();
'password' => ['required', 'string'], if (! $user || ! Hash::check((string) $request->input('password'), $user->password)) {
]);
$user = User::where('email', $data['email'])->first();
if (! $user || ! Hash::check($data['password'], $user->password)) {
return $this->refuse('invalid_credentials', 'Wrong email or password.'); return $this->refuse('invalid_credentials', 'Wrong email or password.');
} }
@ -46,8 +58,8 @@ class AuthController extends Controller
]); ]);
} }
private function refuse(string $code, string $message): JsonResponse private function refuse(string $code, string $message, ?string $field = null): JsonResponse
{ {
return response()->json(['code' => $code, 'message' => $message], 422); return response()->json(['code' => $code, 'message' => $message, 'field' => $field], 422);
} }
} }

View File

@ -12,7 +12,7 @@ use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens; use Laravel\Sanctum\HasApiTokens;
#[Fillable(['name', 'email', 'password'])] #[Fillable(['name', 'email', 'password', 'terms_accepted_at'])]
#[Hidden(['password', 'remember_token'])] #[Hidden(['password', 'remember_token'])]
class User extends Authenticatable class User extends Authenticatable
{ {
@ -34,6 +34,7 @@ class User extends Authenticatable
{ {
return [ return [
'email_verified_at' => 'datetime', 'email_verified_at' => 'datetime',
'terms_accepted_at' => 'datetime',
'password' => 'hashed', 'password' => 'hashed',
]; ];
} }

View File

@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
// Accounts accept the terms; players carry their own beginner protection and when they were last seen.
return new class extends Migration
{
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->timestamp('terms_accepted_at')->nullable();
});
Schema::table('players', function (Blueprint $table) {
// Until when nobody may attack them: from joining, and again from a restart.
$table->dateTime('protected_until', 3)->nullable();
$table->dateTime('last_active_at', 3)->nullable()->index();
});
}
public function down(): void
{
Schema::table('players', function (Blueprint $table) {
$table->dropColumn(['protected_until', 'last_active_at']);
});
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('terms_accepted_at');
});
}
};

View File

@ -4,18 +4,19 @@ use App\Models\User;
it('registers a player and returns a bearer token', function () { it('registers a player and returns a bearer token', function () {
$response = $this->postJson('/api/auth/register', [ $response = $this->postJson('/api/auth/register', [
'name' => 'Ada', 'email' => 'ada@example.test', 'password' => 'secret-pass', 'name' => 'Ada', 'email' => 'Ada@Example.test', 'password' => 'secret-pass', 'terms' => true,
]); ]);
$response->assertOk()->assertJsonPath('user.name', 'Ada')->assertJsonStructure(['token', 'user' => ['id', 'name', 'email']]); $response->assertOk()->assertJsonPath('user.name', 'Ada')->assertJsonStructure(['token', 'user' => ['id', 'name', 'email']]);
expect(User::where('email', 'ada@example.test')->first()->tokens)->toHaveCount(1); $user = User::where('email', 'ada@example.test')->first();
expect($user->tokens)->toHaveCount(1)->and($user->terms_accepted_at)->not->toBeNull();
}); });
it('refuses a second account with the same email', function () { it('refuses a second account with the same email', function () {
User::factory()->create(['email' => 'ada@example.test']); User::factory()->create(['email' => 'ada@example.test']);
$this->postJson('/api/auth/register', ['name' => 'Ada', 'email' => 'ada@example.test', 'password' => 'secret-pass']) $this->postJson('/api/auth/register', ['name' => 'Ada', 'email' => 'ada@example.test', 'password' => 'secret-pass', 'terms' => true])
->assertStatus(422)->assertJsonPath('code', 'email_taken'); ->assertStatus(422)->assertJsonPath('code', 'email_taken')->assertJsonPath('field', 'email');
}); });
it('logs in with the right password only', function () { it('logs in with the right password only', function () {
@ -26,3 +27,16 @@ it('logs in with the right password only', function () {
$this->postJson('/api/auth/login', ['email' => 'ada@example.test', 'password' => 'secret-pass']) $this->postJson('/api/auth/login', ['email' => 'ada@example.test', 'password' => 'secret-pass'])
->assertOk()->assertJsonStructure(['token']); ->assertOk()->assertJsonStructure(['token']);
}); });
it('checks every field and names the one that is wrong', function () {
User::factory()->create(['name' => 'Taken One']);
$try = fn (array $over) => $this->postJson('/api/auth/register', [...['name' => 'Ada', 'email' => 'ada@example.test', 'password' => 'secret-pass', 'terms' => true], ...$over]);
$try(['name' => 'A'])->assertStatus(422)->assertJsonPath('code', 'name_invalid')->assertJsonPath('field', 'name');
$try(['name' => '<script>'])->assertJsonPath('code', 'name_invalid');
$try(['name' => 'taken one'])->assertJsonPath('code', 'name_taken');
$try(['email' => 'not-an-email'])->assertJsonPath('code', 'email_invalid');
$try(['password' => 'short'])->assertJsonPath('code', 'password_short');
$try(['terms' => false])->assertJsonPath('code', 'terms_required')->assertJsonPath('field', 'terms');
$try(['name' => ' Ada Lovelace '])->assertOk()->assertJsonPath('user.name', 'Ada Lovelace');
});