Normalize email case in admin commands, Filament user form, imports and placeholder merging (#1398)

* Normalize email case in admin commands, Filament user form, imports and placeholder merging

* Add tests for email case normalization

* Lowercase existing invitation emails and match duplicates case-insensitively

Adds a migration that lowercases organization_invitations.email. Invitations of the
same organization whose emails only differ in case are deduplicated first (accepted
invitation preferred, otherwise the newest), so the unique index is not violated.
The duplicate check when inviting a user now ignores case.

* Lowercase placeholder emails in migration and use Str::lower for emails
This commit is contained in:
Constantin Graf
2026-11-19 14:16:03 +01:00
committed by GitHub
parent 065967ad02
commit 34ab2aed32
17 changed files with 471 additions and 15 deletions

View File

@@ -10,6 +10,8 @@ use App\Models\User;
use App\Service\UserService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use LogicException;
class UserCreateCommand extends Command
@@ -38,10 +40,18 @@ class UserCreateCommand extends Command
public function handle(): int
{
$name = $this->argument('name');
$email = $this->argument('email');
// Lowercased like UserService::createUser() stores it, so the existence check below finds any casing.
$email = Str::lower((string) $this->argument('email'));
$askForPassword = (bool) $this->option('ask-for-password');
$verifyEmail = (bool) $this->option('verify-email');
// Same rule as registration
if (Validator::make(['email' => $email], ['email' => ['required', 'email:rfc,strict']])->fails()) {
$this->error('"'.$email.'" is not a valid email address.');
return self::FAILURE;
}
if (User::query()->where('email', $email)->where('is_placeholder', '=', false)->exists()) {
$this->error('User with email "'.$email.'" already exists.');

View File

@@ -7,6 +7,7 @@ namespace App\Console\Commands\Admin;
use App\Models\User;
use Illuminate\Auth\Events\Verified;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
class UserVerifyCommand extends Command
{
@@ -30,7 +31,8 @@ class UserVerifyCommand extends Command
*/
public function handle(): int
{
$email = $this->argument('email');
// Emails are stored lowercase (see UserService::createUser)
$email = Str::lower((string) $this->argument('email'));
$this->info('Start verifying user with email "'.$email.'"');

View File

@@ -17,6 +17,7 @@ use App\Service\DeletionService;
use App\Service\TimezoneService;
use App\Service\UserService;
use Brick\Money\IsoCurrencyProvider;
use Closure;
use Exception;
use Filament\Actions\BulkAction;
use Filament\Actions\DeleteAction;
@@ -36,7 +37,7 @@ use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Korridor\LaravelModelValidationRules\Rules\UniqueEloquent;
use Illuminate\Support\Str;
use STS\FilamentImpersonate\Actions\Impersonate;
class UserResource extends Resource
@@ -71,12 +72,25 @@ class UserResource extends Resource
->label('Email')
->required()
->rules($record?->is_placeholder ? [] : [
UniqueEloquent::make(User::class, 'email')
->ignore($record?->getKey()),
// Compared lowercased, since that is how the email is stored (see dehydrateStateUsing).
// Wrapped, because Filament evaluates closures in rules() itself.
fn (): Closure => function (string $attribute, mixed $value, Closure $fail) use ($record): void {
$emailAlreadyInUse = is_string($value) && User::query()
->where('email', '=', Str::lower($value))
->where('is_placeholder', '=', false)
->when($record !== null, fn (Builder $query) => $query->whereKeyNot($record->getKey()))
->exists();
if ($emailAlreadyInUse) {
$fail(__('validation.unique', ['attribute' => $attribute]));
}
},
])
->rule([
'email:rfc,strict',
])
// Emails are stored lowercase, and login and invitations look them up lowercased.
->dehydrateStateUsing(fn (?string $state): ?string => $state !== null ? Str::lower($state) : null)
->maxLength(255),
Toggle::make('is_placeholder')
->label('Is Placeholder?')

View File

@@ -10,13 +10,14 @@ use App\Models\User;
use App\Service\MemberService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use RuntimeException;
class OrganizationInvitationController extends Controller
{
public function accept(OrganizationInvitation $invitation, MemberService $memberService): RedirectResponse
{
$email = strtolower($invitation->email);
$email = Str::lower($invitation->email);
$role = Role::tryFrom($invitation->role);
if ($role === null || $role === Role::Owner || $role === Role::Placeholder) {
throw new RuntimeException('Invalid role');

View File

@@ -19,6 +19,7 @@ use App\Service\Import\ImportDatabaseHelper;
use App\Service\TimezoneService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Override;
abstract class DefaultImporter implements ImporterContract
@@ -210,13 +211,13 @@ abstract class DefaultImporter implements ImporterContract
/**
* Uses the same rule as registration and invitations, so every email the app accepts can be re-imported.
* The value is not trimmed, so it matches existing users exactly as stored.
* The value is lowercased (not trimmed), so it matches existing users exactly as stored.
*
* @throws ImportException
*/
protected function validateEmail(mixed $email, string $field): string
{
$email = is_string($email) ? $email : '';
$email = is_string($email) ? Str::lower($email) : '';
if (Validator::make(['email' => $email], ['email' => ['required', 'email:rfc,strict']])->fails()) {
throw new ImportException('Value of '.$field.' ("'.$email.'") is not a valid email address');
}

View File

@@ -16,13 +16,14 @@ use App\Models\User;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
class InvitationService
{
public function hasAcceptedInvitationForEmail(string $email): bool
{
return OrganizationInvitation::query()
->whereRaw('lower(email) = ?', [strtolower($email)])
->whereRaw('lower(email) = ?', [Str::lower($email)])
->whereNotNull('accepted_at')
->exists();
}
@@ -30,7 +31,7 @@ class InvitationService
public function hasPendingInvitationForEmail(string $email): bool
{
return OrganizationInvitation::query()
->whereRaw('lower(email) = ?', [strtolower($email)])
->whereRaw('lower(email) = ?', [Str::lower($email)])
->whereNull('accepted_at')
->exists();
}
@@ -42,14 +43,14 @@ class InvitationService
{
// Normalize the email so it matches how user emails are stored (see UserService::createUser),
// otherwise a mixed-case invite silently fails to link on registration.
$email = strtolower($email);
$email = Str::lower($email);
if (app(MemberService::class)->isEmailAlreadyMember($organization, $email)) {
throw new UserIsAlreadyMemberOfOrganizationApiException;
}
if (OrganizationInvitation::query()
->where('email', $email)
->whereRaw('lower(email) = ?', [$email])
->whereBelongsTo($organization, 'organization')
->exists()) {
throw new InvitationForTheEmailAlreadyExistsApiException;
@@ -76,7 +77,7 @@ class InvitationService
$organizations = new Collection;
$invitations = OrganizationInvitation::query()
->whereRaw('lower(email) = ?', [strtolower($user->email)])
->whereRaw('lower(email) = ?', [Str::lower($user->email)])
->whereNotNull('accepted_at')
->with('organization')
->get();

View File

@@ -23,6 +23,7 @@ use App\Models\TimeEntry;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use InvalidArgumentException;
class MemberService
@@ -64,8 +65,9 @@ class MemberService
$placeholders = Member::query()
->whereHas('user', function (Builder $query) use ($user): void {
/** @var Builder<User> $query */
// Placeholders come from imports and may keep the casing of the source file
$query->where('is_placeholder', '=', true)
->where('email', '=', $user->email);
->whereRaw('lower(email) = ?', [Str::lower($user->email)]);
})
->whereBelongsTo($organization, 'organization')
->with(['user'])

View File

@@ -22,6 +22,7 @@ use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use InvalidArgumentException;
class UserService
@@ -49,7 +50,7 @@ class UserService
): User {
$user = new User;
$user->name = $name;
$user->email = strtolower($email);
$user->email = Str::lower($email);
$user->password = $password !== null ? Hash::make($password) : null;
$user->timezone = $timezone;
$user->week_start = $weekStart;

View File

@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
/**
* Invitations used to be stored with the email as entered, while user emails are stored lowercase.
* This lowercases the existing invitation emails. Invitations of the same organization whose emails
* only differ in case would violate the unique index on (organization_id, email) after lowercasing,
* so only one of them is kept: an accepted invitation is preferred, otherwise the newest one.
*
* It also lowercases placeholder user emails. Imports used to store them as written in the source file,
* while imports now look them up lowercased. Placeholders are excluded from the unique index on
* users.email, so this can not fail on duplicates.
*/
public function up(): void
{
DB::statement('
DELETE FROM organization_invitations
WHERE id IN (
SELECT id FROM (
SELECT
id,
ROW_NUMBER() OVER (
PARTITION BY organization_id, LOWER(email)
ORDER BY (accepted_at IS NULL), created_at DESC NULLS LAST, id
) AS row_number
FROM organization_invitations
) AS ranked_invitations
WHERE row_number > 1
)
');
DB::table('organization_invitations')
->whereRaw('email <> LOWER(email)')
->update([
'email' => DB::raw('LOWER(email)'),
]);
DB::table('users')
->where('is_placeholder', '=', true)
->whereRaw('email <> LOWER(email)')
->update([
'email' => DB::raw('LOWER(email)'),
]);
}
/**
* Reverse the migrations.
*/
public function down(): void
{
//
}
};

View File

@@ -115,4 +115,54 @@ class UserCreateCommandCommandTest extends TestCaseWithDatabase
$this->assertNotNull($user->password);
$this->assertTrue(Hash::check('password', $user->password));
}
public function test_it_stores_email_lowercased(): void
{
// Act
$exitCode = $this->withoutMockingConsoleOutput()->artisan('admin:user:create', [
'name' => 'Test User',
'email' => 'Mail@TestUser.test',
]);
// Assert
$this->assertSame(Command::SUCCESS, $exitCode);
$this->assertDatabaseHas(User::class, [
'email' => 'mail@testuser.test',
]);
}
public function test_it_fails_if_user_with_email_in_different_case_already_exists(): void
{
// Arrange
User::factory()->create([
'email' => 'mail@testuser.test',
]);
// Act
$exitCode = $this->withoutMockingConsoleOutput()->artisan('admin:user:create', [
'name' => 'Test User',
'email' => 'MAIL@testuser.test',
]);
// Assert
$this->assertSame(Command::FAILURE, $exitCode);
$output = Artisan::output();
$this->assertStringContainsString('User with email "mail@testuser.test" already exists.', $output);
$this->assertSame(1, User::query()->count());
}
public function test_it_fails_if_email_is_invalid(): void
{
// Act
$exitCode = $this->withoutMockingConsoleOutput()->artisan('admin:user:create', [
'name' => 'Test User',
'email' => 'not-an-email',
]);
// Assert
$this->assertSame(Command::FAILURE, $exitCode);
$output = Artisan::output();
$this->assertStringContainsString('"not-an-email" is not a valid email address.', $output);
$this->assertSame(0, User::query()->count());
}
}

View File

@@ -67,4 +67,23 @@ class UserVerifyCommandTest extends TestCaseWithDatabase
$command->expectsOutput('User with email "'.$user->email.'" already verified.')
->assertExitCode(1);
}
public function test_it_finds_user_if_email_is_given_in_different_case(): void
{
// Arrange
$user = User::factory()->create([
'email' => 'test@test.test',
'email_verified_at' => null,
]);
Member::factory()->forUser($user)->forOrganization(Organization::factory()->create())->create();
// Act
$command = $this->artisan('admin:user:verify', ['email' => 'Test@TEST.test']);
// Assert
$command->expectsOutput('User with email "test@test.test" has been verified.')
->assertExitCode(0)
->run();
$this->assertNotNull($user->refresh()->email_verified_at);
}
}

View File

@@ -0,0 +1,122 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Database;
use App\Models\Organization;
use App\Models\OrganizationInvitation;
use App\Models\User;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Tests\TestCaseWithDatabase;
class LowercaseOrganizationInvitationEmailsMigrationTest extends TestCaseWithDatabase
{
private function runMigration(): void
{
$migration = require database_path('migrations/2026_11_18_000001_lowercase_organization_invitation_emails.php');
assert($migration instanceof Migration && method_exists($migration, 'up'));
$migration->up();
}
public function test_lowercases_invitation_emails(): void
{
// Arrange
$organization = Organization::factory()->create();
$invitation = OrganizationInvitation::factory()->forOrganization($organization)->create([
'email' => 'Mixed.Case@Email.test',
]);
$lowercaseInvitation = OrganizationInvitation::factory()->forOrganization($organization)->create([
'email' => 'lower@email.test',
]);
// Act
$this->runMigration();
// Assert
$this->assertSame('mixed.case@email.test', $invitation->refresh()->email);
$this->assertSame('lower@email.test', $lowercaseInvitation->refresh()->email);
}
public function test_keeps_the_accepted_invitation_if_emails_of_the_same_organization_only_differ_in_case(): void
{
// Arrange
$organization = Organization::factory()->create();
$acceptedInvitation = OrganizationInvitation::factory()->forOrganization($organization)->accepted()->create([
'email' => 'User@Email.test',
'created_at' => Carbon::now()->subDay(),
]);
$newerPendingInvitation = OrganizationInvitation::factory()->forOrganization($organization)->create([
'email' => 'user@email.test',
'created_at' => Carbon::now(),
]);
// Act
$this->runMigration();
// Assert
$this->assertDatabaseMissing(OrganizationInvitation::class, ['id' => $newerPendingInvitation->getKey()]);
$this->assertSame('user@email.test', $acceptedInvitation->refresh()->email);
}
public function test_keeps_the_newest_invitation_if_none_of_the_duplicates_is_accepted(): void
{
// Arrange
$organization = Organization::factory()->create();
$olderInvitation = OrganizationInvitation::factory()->forOrganization($organization)->create([
'email' => 'user@email.test',
'created_at' => Carbon::now()->subDay(),
]);
$newerInvitation = OrganizationInvitation::factory()->forOrganization($organization)->create([
'email' => 'USER@email.test',
'created_at' => Carbon::now(),
]);
// Act
$this->runMigration();
// Assert
$this->assertDatabaseMissing(OrganizationInvitation::class, ['id' => $olderInvitation->getKey()]);
$this->assertSame('user@email.test', $newerInvitation->refresh()->email);
}
public function test_keeps_invitations_with_the_same_email_in_different_organizations(): void
{
// Arrange
$organization = Organization::factory()->create();
$otherOrganization = Organization::factory()->create();
$invitation = OrganizationInvitation::factory()->forOrganization($organization)->create([
'email' => 'User@Email.test',
]);
$otherInvitation = OrganizationInvitation::factory()->forOrganization($otherOrganization)->create([
'email' => 'user@email.test',
]);
// Act
$this->runMigration();
// Assert
$this->assertSame('user@email.test', $invitation->refresh()->email);
$this->assertSame('user@email.test', $otherInvitation->refresh()->email);
}
public function test_lowercases_placeholder_user_emails_but_not_other_user_emails(): void
{
// Arrange
$placeholder = User::factory()->placeholder()->create([
'email' => 'Placeholder@Email.test',
]);
// Non-placeholder emails are lowercased by an earlier migration, this one must not touch them
$user = User::factory()->create();
DB::table('users')->where('id', '=', $user->getKey())->update(['email' => 'Real.User@Email.test']);
// Act
$this->runMigration();
// Assert
$this->assertSame('placeholder@email.test', $placeholder->refresh()->email);
$this->assertSame('Real.User@Email.test', $user->refresh()->email);
}
}

View File

@@ -182,6 +182,29 @@ class InvitationEndpointTest extends ApiEndpointTestAbstract
]);
}
public function test_store_fails_if_an_invitation_with_the_same_email_in_different_case_already_exists(): void
{
// Arrange
$data = $this->createUserWithPermission([
'invitations:create',
]);
Passport::actingAs($data->user);
OrganizationInvitation::factory()->forOrganization($data->organization)->create([
'email' => 'User@Email.test',
]);
// Act
$response = $this->postJson(route('api.v1.invitations.store', $data->organization->getKey()), [
'email' => 'user@email.test',
'role' => Role::Employee->value,
]);
// Assert
$response->assertStatus(400);
$response->assertJsonPath('key', 'invitation_for_the_email_already_exists');
$this->assertSame(1, OrganizationInvitation::query()->whereBelongsTo($data->organization, 'organization')->count());
}
public function test_store_works_if_user_invites_user_who_is_also_a_placeholder(): void
{
// Arrange

View File

@@ -446,4 +446,107 @@ class UserResourceTest extends FilamentTestCase
'record' => $organization->getKey(),
]), $organization);
}
public function test_create_user_stores_email_lowercased(): void
{
// Arrange
$userFake = User::factory()->make();
// Act
Livewire::test(UserResource\Pages\CreateUser::class)
->fillForm([
'name' => $userFake->name,
'email' => 'New.User@Example.com',
'password_create' => 'password',
'timezone' => $userFake->timezone,
'week_start' => $userFake->week_start->value,
'currency' => 'EUR',
])
->call('create')
->assertHasNoFormErrors();
// Assert
$this->assertDatabaseHas(User::class, ['email' => 'new.user@example.com']);
}
public function test_create_user_fails_if_email_is_already_used_in_different_case(): void
{
// Arrange
User::factory()->create(['email' => 'existing@example.com']);
$userFake = User::factory()->make();
// Act
Livewire::test(UserResource\Pages\CreateUser::class)
->fillForm([
'name' => $userFake->name,
'email' => 'Existing@Example.com',
'password_create' => 'password',
'timezone' => $userFake->timezone,
'week_start' => $userFake->week_start->value,
'currency' => 'EUR',
])
->call('create')
->assertHasFormErrors(['email']);
// Assert
$this->assertSame(1, User::query()->where('email', '=', 'existing@example.com')->count());
}
public function test_create_user_succeeds_if_email_is_only_used_by_placeholder(): void
{
// Arrange
User::factory()->placeholder()->create(['email' => 'existing@example.com']);
$userFake = User::factory()->make();
// Act
Livewire::test(UserResource\Pages\CreateUser::class)
->fillForm([
'name' => $userFake->name,
'email' => 'existing@example.com',
'password_create' => 'password',
'timezone' => $userFake->timezone,
'week_start' => $userFake->week_start->value,
'currency' => 'EUR',
])
->call('create')
->assertHasNoFormErrors();
// Assert
$this->assertSame(1, User::query()->where('email', '=', 'existing@example.com')->where('is_placeholder', '=', false)->count());
}
public function test_edit_user_can_keep_own_email_and_stores_it_lowercased(): void
{
// Arrange
$user = User::factory()->create(['email' => 'user@example.com']);
// Act
Livewire::test(UserResource\Pages\EditUser::class, ['record' => $user->getKey()])
->fillForm([
'email' => 'User@Example.com',
])
->call('save')
->assertHasNoFormErrors();
// Assert
$this->assertSame('user@example.com', $user->refresh()->email);
}
public function test_edit_user_fails_if_email_is_used_by_other_user_in_different_case(): void
{
// Arrange
User::factory()->create(['email' => 'other@example.com']);
$user = User::factory()->create(['email' => 'user@example.com']);
// Act
Livewire::test(UserResource\Pages\EditUser::class, ['record' => $user->getKey()])
->fillForm([
'email' => 'Other@Example.com',
])
->call('save')
->assertHasFormErrors(['email']);
// Assert
$this->assertSame('user@example.com', $user->refresh()->email);
}
}

View File

@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Tests\Unit\Service\Import\Importers;
use App\Models\Member;
use App\Models\Organization;
use App\Models\TimeEntry;
use App\Models\User;
@@ -230,4 +231,25 @@ class GenericTimeEntriesImporterTest extends ImporterTestAbstract
$this->assertNull($timeEntry->billable_rate);
}
}
public function test_import_lowercases_user_email_and_matches_existing_user(): void
{
// Arrange
$organization = Organization::factory()->create();
$user = User::factory()->create(['email' => 'ivanna@example.com']);
Member::factory()->forOrganization($organization)->forUser($user)->create();
$timezone = 'Europe/Vienna';
$importer = new GenericTimeEntriesImporter;
$importer->init($organization);
$data = "description,billable,client,project,tags,start,end,task,user_name,user_email\n".
'"Working hard","true","","","","2024-03-04T09:23:00Z","2024-03-04T10:23:00Z","","Ivanna","Ivanna@Example.com"';
// Act
$importer->importData($data, $timezone);
// Assert
$this->assertSame(1, User::query()->whereRaw('lower(email) = ?', ['ivanna@example.com'])->count());
$this->assertSame(0, User::query()->where('email', '=', 'Ivanna@Example.com')->count());
$this->assertSame(1, TimeEntry::query()->where('user_id', '=', $user->getKey())->count());
}
}

View File

@@ -441,4 +441,21 @@ class MemberServiceTest extends TestCaseWithDatabase
'billable_rate' => 1,
]);
}
public function test_add_member_merges_placeholder_with_same_email_in_different_case(): void
{
// Arrange
$organization = Organization::factory()->create();
$user = User::factory()->create(['email' => 'user@example.com']);
$placeholderUser = User::factory()->placeholder()->create(['email' => 'User@Example.com']);
$placeholderMember = Member::factory()->forOrganization($organization)->forUser($placeholderUser)->role(Role::Placeholder)->create();
$timeEntry = TimeEntry::factory()->forMember($placeholderMember)->create();
// Act
$newMember = $this->memberService->addMember($user, $organization, Role::Employee);
// Assert
$this->assertDatabaseMissing(Member::class, ['id' => $placeholderMember->getKey()]);
$this->assertDatabaseHas(TimeEntry::class, ['id' => $timeEntry->getKey(), 'member_id' => $newMember->getKey(), 'user_id' => $user->getKey()]);
}
}

View File

@@ -61,6 +61,15 @@ class UserServiceTest extends TestCase
Event::assertNotDispatched(Verified::class);
}
public function test_create_user_lowercases_non_ascii_characters_in_email(): void
{
// Act
$user = $this->userService->createUser('Test User', 'Ünal@Example.test', 'password', 'Europe/Vienna', Weekday::Monday, 'EUR');
// Assert
$this->assertSame('ünal@example.test', $user->email);
}
public function test_assign_organization_entities_to_different_user(): void
{
// Arrange