From 498b4d9eaca56de5c2d5de56a1b474cdf72c1737 Mon Sep 17 00:00:00 2001 From: ncoronel Date: Tue, 11 Aug 2026 16:05:37 -0300 Subject: [PATCH] fix(auth): correct tenant code handling in login failure registration --- .../Auth/Services/PasswordLoginService.php | 4 +- .../Auth/ScannerLoginControllerTest.php | 37 +++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/app/Domains/Auth/Services/PasswordLoginService.php b/app/Domains/Auth/Services/PasswordLoginService.php index 1e25389..42c76c5 100644 --- a/app/Domains/Auth/Services/PasswordLoginService.php +++ b/app/Domains/Auth/Services/PasswordLoginService.php @@ -159,8 +159,8 @@ class PasswordLoginService } if ($user === null || ! Hash::check($password, $user->password)) { - if ($user !== null) { - $this->registerFailure($user, $now, $tenantCode); + if ($user !== null && $attemptTenantCode !== null) { + $this->registerFailure($user, $now, $attemptTenantCode); } $outcome = $user?->locked_until?->isFuture() diff --git a/tests/Feature/Auth/ScannerLoginControllerTest.php b/tests/Feature/Auth/ScannerLoginControllerTest.php index b33b2a9..1c1437d 100644 --- a/tests/Feature/Auth/ScannerLoginControllerTest.php +++ b/tests/Feature/Auth/ScannerLoginControllerTest.php @@ -2,6 +2,7 @@ namespace Tests\Feature\Auth; +use App\Domains\Auth\Models\LoginAttempt; use App\Domains\Auth\Models\User; use App\Domains\Authorization\Enums\PermissionCode; use App\Domains\Authorization\Enums\RoleCode; @@ -76,4 +77,40 @@ class ScannerLoginControllerTest extends TestCase 'password' => 'secret123', ])->assertUnprocessable()->assertJsonValidationErrors(['email']); } + + public function test_an_invalid_password_is_recorded_with_the_users_tenant(): void + { + $role = Role::query()->create([ + 'codigo' => RoleCode::Scanner->value, + 'nombre' => 'Scanner', + ]); + $permission = Permission::query()->create([ + 'codigo' => PermissionCode::ScanTickets->value, + 'nombre' => 'Escanear tickets', + ]); + $role->permissions()->attach($permission->codigo); + $tenant = Tenant::query()->create([ + 'codigo' => 'acme', + 'nombre' => 'Acme', + 'dominio' => 'acme.test', + ]); + $user = User::factory()->create([ + 'email' => 'scanner@example.com', + 'password' => Hash::make('correct-password'), + 'rol_codigo' => $role->codigo, + 'tenant_codigo' => $tenant->codigo, + ]); + + $this->postJson('/api/v1/scanner/login', [ + 'email' => $user->email, + 'password' => 'wrong-password', + ])->assertUnprocessable()->assertJsonValidationErrors(['email']); + + $this->assertSame(1, $user->refresh()->failed_login_attempts); + $this->assertDatabaseHas('login_attempts', [ + 'user_id' => $user->id, + 'tenant_codigo' => $tenant->codigo, + 'outcome' => LoginAttempt::OUTCOME_INVALID_CREDENTIALS, + ]); + } }