From 228bb299865d0e2376b19d3c5edd2a8518074671 Mon Sep 17 00:00:00 2001 From: Steve Bauman Date: Mon, 9 Nov 2026 15:34:39 -0500 Subject: [PATCH] Allow disabling automatic restoration of deleted accounts (#22) * Allow disabling soft-deleted account restoration * Combine identity conflict and deleted account lookups * Restore separate deleted account and identity checks * Cast provider_id to string for consistency Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> * Enforce deleted account policy during provider updates * Rename soft-deleted user restoration opt-out --------- Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> (cherry picked from commit 556bc0c9f61c6a52e1a9a982c839cac0a6325190) --- README.md | 19 ++- src/BartenderManager.php | 21 +++ src/Facades/Bartender.php | 2 + src/UserProviderRepository.php | 36 ++++- tests/BartenderManagerTest.php | 16 ++ tests/SoftDeleteRestorationTest.php | 237 ++++++++++++++++++++++++++++ tests/SoftDeletingUser.php | 12 ++ 7 files changed, 340 insertions(+), 3 deletions(-) create mode 100644 tests/SoftDeleteRestorationTest.php create mode 100644 tests/SoftDeletingUser.php diff --git a/README.md b/README.md index 3359815..29b1731 100644 --- a/README.md +++ b/README.md @@ -185,7 +185,24 @@ configure case-sensitive provider columns and uniqueness constraints themselves. With the default `UserProviderRepository`, soft-deleted users will be restored if they log in with their provider. -To change this behaviour, [swap out the repository](#user-creation--updating). +To prevent provider sign-in from restoring or recreating a soft-deleted account, disable +restoration in your service provider: + +```php +Bartender::dontRestoreSoftDeletedUsers(); +``` + +Automatic restoration remains enabled by default. To explicitly allow restoration again, +call `Bartender::dontRestoreSoftDeletedUsers(false)`. You can inspect the current policy +with `Bartender::shouldRestoreSoftDeletedUsers()`. + +When restoration is disabled, Bartender rejects +a deleted account by its provider identity or email address, including when the +provider reports a different email. Rejected deleted accounts raise an +`AuthenticationException` rather than being reported as email conflicts. The account +is checked again before updating, and its deletion timestamp is only cleared when +restoration is enabled. You can also [swap out the repository](#user-creation--updating) +for a custom policy. ### Email Verification diff --git a/src/BartenderManager.php b/src/BartenderManager.php index 6551162..16f0b91 100644 --- a/src/BartenderManager.php +++ b/src/BartenderManager.php @@ -20,6 +20,27 @@ class BartenderManager */ protected array $handlers = []; + /** + * Whether provider sign-in may restore a soft-deleted user. + */ + protected bool $restoreSoftDeletedUsers = true; + + /** + * Prevent automatic restoration during provider sign-in. + */ + public function dontRestoreSoftDeletedUsers(bool $dontRestore = true): void + { + $this->restoreSoftDeletedUsers = ! $dontRestore; + } + + /** + * Determine whether provider sign-in may restore a soft-deleted user. + */ + public function shouldRestoreSoftDeletedUsers(): bool + { + return $this->restoreSoftDeletedUsers; + } + /** * Set the user model class name. */ diff --git a/src/Facades/Bartender.php b/src/Facades/Bartender.php index 3c5090f..63c9d11 100644 --- a/src/Facades/Bartender.php +++ b/src/Facades/Bartender.php @@ -8,6 +8,8 @@ /** * @method static void routes() * @method static array handlers() + * @method static void dontRestoreSoftDeletedUsers(bool $dontRestore = true) + * @method static bool shouldRestoreSoftDeletedUsers() * @method static string getUserModel() * @method static void setUserModel(string $userModel) * @method static void serve(string $driver, ?string $handler = null) diff --git a/src/UserProviderRepository.php b/src/UserProviderRepository.php index add09af..912a237 100644 --- a/src/UserProviderRepository.php +++ b/src/UserProviderRepository.php @@ -25,6 +25,10 @@ public function exists(string $driver, SocialiteUser $user): bool throw new AuthenticationException('The provider did not return a user ID.'); } + if ($this->isDeleted($driver, $user)) { + throw new AuthenticationException('This account has been deleted and cannot be restored.'); + } + return $this->newUserQuery(Bartender::getUserModel()) ->where('email', $user->getEmail()) ->get(['provider_name', 'provider_id']) @@ -46,6 +50,8 @@ public function updateOrCreate(string $driver, SocialiteUser $user): Authenticat } $model = Bartender::getUserModel(); + $usesSoftDeletes = $this->isUsingSoftDeletes($model); + $restoreDeletedUsers = Bartender::shouldRestoreSoftDeletedUsers(); $eloquent = $this->newUserQuery($model)->firstWhere([ 'provider_name' => $driver, @@ -56,6 +62,10 @@ public function updateOrCreate(string $driver, SocialiteUser $user): Authenticat throw new AuthenticationException('The provider identity does not exactly match the existing account.'); } + if ($eloquent && $usesSoftDeletes && ! $restoreDeletedUsers && $eloquent->trashed()) { + throw new AuthenticationException('This account has been deleted and cannot be restored.'); + } + $eloquent ??= (new $model)->forceFill([ 'email' => $user->getEmail(), 'provider_name' => $driver, @@ -68,8 +78,8 @@ public function updateOrCreate(string $driver, SocialiteUser $user): Authenticat 'provider_id' => $providerId, 'password' => $eloquent->password ?? $this->hash($this->getNewPassword()), ], - $this->isUsingSoftDeletes($model) - ? ['deleted_at' => null] + $usesSoftDeletes && $restoreDeletedUsers + ? [$eloquent->getDeletedAtColumn() => null] : [], $this->isVerifyingEmails($model) ? ['email_verified_at' => $eloquent->email_verified_at ?? now()] @@ -85,6 +95,28 @@ public function updateOrCreate(string $driver, SocialiteUser $user): Authenticat return $eloquent; } + /** + * Reject deleted accounts by identity or email when restoration is disabled. + */ + protected function isDeleted(string $driver, SocialiteUser $user): bool + { + $model = Bartender::getUserModel(); + + if (Bartender::shouldRestoreSoftDeletedUsers() || ! $this->isUsingSoftDeletes($model)) { + return false; + } + + return $model::onlyTrashed() + ->where(function (Builder $query) use ($driver, $user) { + $query->where('email', $user->getEmail()) + ->orWhere(function (Builder $query) use ($driver, $user) { + $query->where('provider_name', $driver) + ->where('provider_id', (string) $user->getId()); + }); + }) + ->exists(); + } + /** * Hash the given value. */ diff --git a/tests/BartenderManagerTest.php b/tests/BartenderManagerTest.php index 98e09de..1556da0 100644 --- a/tests/BartenderManagerTest.php +++ b/tests/BartenderManagerTest.php @@ -33,3 +33,19 @@ expect(Route::has('auth.driver.callback'))->toBeTrue(); expect(Route::has('auth.driver.redirect'))->toBeTrue(); }); + +it('allows soft deleted user restoration by default', function () { + $manager = new BartenderManager; + + expect($manager->shouldRestoreSoftDeletedUsers())->toBeTrue(); +}); + +it('can disable and reenable soft deleted user restoration through the facade', function () { + Bartender::dontRestoreSoftDeletedUsers(); + + expect(Bartender::shouldRestoreSoftDeletedUsers())->toBeFalse(); + + Bartender::dontRestoreSoftDeletedUsers(false); + + expect(Bartender::shouldRestoreSoftDeletedUsers())->toBeTrue(); +}); diff --git a/tests/SoftDeleteRestorationTest.php b/tests/SoftDeleteRestorationTest.php new file mode 100644 index 0000000..4c91a62 --- /dev/null +++ b/tests/SoftDeleteRestorationTest.php @@ -0,0 +1,237 @@ +softDeletes(); + }); + Bartender::setUserModel(SoftDeletingUser::class); + Bartender::dontRestoreSoftDeletedUsers(false); +}); + +it('preserves automatic restoration by default', function (string $email) { + $account = SoftDeletingUser::create([ + 'name' => 'Person', 'email' => 'person@example.com', 'password' => 'password', + 'provider_name' => 'foo', 'provider_id' => '123', + ]); + $account->delete(); + $identity = (new SocialiteUser)->map([ + 'id' => '123', 'name' => 'Person', 'email' => $email, + ]); + + $restored = (new UserProviderRepository)->updateOrCreate('foo', $identity); + + expect($restored->id)->toBe($account->id)->and($restored->trashed())->toBeFalse(); +})->with(['person@example.com', 'changed@example.com']); + +it('rejects a deleted account even when its email or provider identity changes', function (string $email, string $id) { + $account = SoftDeletingUser::create([ + 'name' => 'Person', 'email' => 'person@example.com', 'password' => 'password', + 'provider_name' => 'foo', 'provider_id' => '123', + ]); + $account->delete(); + Bartender::dontRestoreSoftDeletedUsers(); + $identity = (new SocialiteUser)->map(['id' => $id, 'name' => 'Person', 'email' => $email]); + $repository = new UserProviderRepository; + + expect(fn () => $repository->exists('foo', $identity)) + ->toThrow(AuthenticationException::class, 'This account has been deleted and cannot be restored.'); + expect(fn () => $repository->updateOrCreate('foo', $identity))->toThrow(AuthenticationException::class); + expect($account->fresh()->trashed())->toBeTrue() + ->and(SoftDeletingUser::withTrashed()->count())->toBe(1); +})->with([ + ['person@example.com', '123'], + ['changed@example.com', '123'], + ['person@example.com', 'different'], +]); + +it('allows active accounts and models without soft deletes when restoration is disabled', function () { + Bartender::dontRestoreSoftDeletedUsers(); + $account = SoftDeletingUser::create([ + 'name' => 'Person', 'email' => 'person@example.com', 'password' => 'password', + 'provider_name' => 'foo', 'provider_id' => '123', + ]); + $identity = (new SocialiteUser)->map([ + 'id' => '123', 'name' => 'Person', 'email' => 'person@example.com', + ]); + + expect((new UserProviderRepository)->updateOrCreate('foo', $identity)->id)->toBe($account->id); + Bartender::setUserModel(User::class); + expect((new UserProviderRepository)->updateOrCreate('foo', $identity)->id)->toBe($account->id); +}); + +it('allows an active identity to change email without matching unrelated deleted accounts', function (string $deletedDriver, string $deletedId) { + Bartender::dontRestoreSoftDeletedUsers(); + $account = SoftDeletingUser::create([ + 'name' => 'Active', 'email' => 'active@example.com', 'password' => 'password', + 'provider_name' => 'foo', 'provider_id' => '123', + ]); + $deleted = SoftDeletingUser::create([ + 'name' => 'Deleted', 'email' => 'deleted@example.com', 'password' => 'password', + 'provider_name' => $deletedDriver, 'provider_id' => $deletedId, + ]); + $deleted->delete(); + $identity = (new SocialiteUser)->map([ + 'id' => '123', 'name' => 'Updated', 'email' => 'changed@example.com', + ]); + $repository = new UserProviderRepository; + + expect($repository->exists('foo', $identity))->toBeFalse(); + expect($repository->updateOrCreate('foo', $identity)->id)->toBe($account->id); + expect($account->fresh()->email)->toBe('changed@example.com') + ->and($deleted->fresh()->trashed())->toBeTrue() + ->and($deleted->fresh()->email)->toBe('deleted@example.com') + ->and(SoftDeletingUser::withTrashed()->count())->toBe(2); +})->with([ + 'same provider, different ID' => ['foo', '456'], + 'different provider, same ID' => ['bar', '123'], +]); + +it('rejects email conflicts without restoring the matching deleted identity', function (bool $restore) { + Bartender::dontRestoreSoftDeletedUsers(! $restore); + $active = SoftDeletingUser::create([ + 'name' => 'Active', 'email' => 'taken@example.com', 'password' => 'password', + 'provider_name' => 'foo', 'provider_id' => '456', + ]); + $deleted = SoftDeletingUser::create([ + 'name' => 'Deleted', 'email' => 'old@example.com', 'password' => 'password', + 'provider_name' => 'foo', 'provider_id' => '123', + 'provider_access_token' => 'original-token', + ]); + $deleted->delete(); + $identity = (new SocialiteUser)->map([ + 'id' => '123', 'name' => 'Incoming', 'email' => 'taken@example.com', + ]); + $identity->token = 'incoming-token'; + $repository = new UserProviderRepository; + + if ($restore) { + expect($repository->exists('foo', $identity))->toBeTrue(); + } else { + expect(fn () => $repository->exists('foo', $identity)) + ->toThrow(AuthenticationException::class, 'This account has been deleted and cannot be restored.'); + } + expect(fn () => $repository->updateOrCreate('foo', $identity)) + ->toThrow(AuthenticationException::class); + expect($deleted->fresh()->trashed())->toBeTrue() + ->and($deleted->fresh()->email)->toBe('old@example.com') + ->and($deleted->fresh()->provider_access_token)->toBe('original-token') + ->and($active->fresh()->email)->toBe('taken@example.com') + ->and($active->fresh()->provider_id)->toBe('456'); +})->with([true, false]); + +it('respects a custom soft delete column when matching changed emails', function () { + Schema::table('users', function (Blueprint $table) { + $table->softDeletes('archived_at'); + }); + $model = new class extends SoftDeletingUser + { + public const DELETED_AT = 'archived_at'; + }; + Bartender::setUserModel($model::class); + Bartender::dontRestoreSoftDeletedUsers(); + $account = $model::create([ + 'name' => 'Deleted', 'email' => 'old@example.com', 'password' => 'password', + 'provider_name' => 'foo', 'provider_id' => '123', + ]); + $account->delete(); + $identity = (new SocialiteUser)->map([ + 'id' => '123', 'name' => 'Incoming', 'email' => 'changed@example.com', + ]); + $repository = new UserProviderRepository; + + expect(fn () => $repository->exists('foo', $identity)) + ->toThrow(AuthenticationException::class, 'This account has been deleted and cannot be restored.'); + expect(fn () => $repository->updateOrCreate('foo', $identity)) + ->toThrow(AuthenticationException::class); + expect($account->fresh()->trashed())->toBeTrue() + ->and($account->fresh()->email)->toBe('old@example.com'); + + Bartender::dontRestoreSoftDeletedUsers(false); + + expect($repository->exists('foo', $identity))->toBeFalse(); + expect($repository->updateOrCreate('foo', $identity)->id)->toBe($account->id); + expect($account->fresh()->trashed())->toBeFalse() + ->and($account->fresh()->email)->toBe('changed@example.com'); +}); + +it('rechecks deletion when it occurs between eligibility and account lookup', function (bool $restore) { + Bartender::dontRestoreSoftDeletedUsers(! $restore); + $account = SoftDeletingUser::create([ + 'name' => 'Original', 'email' => 'original@example.com', 'password' => 'password', + 'provider_name' => 'foo', 'provider_id' => '123', + 'provider_access_token' => 'original-token', + ]); + $identity = (new SocialiteUser)->map([ + 'id' => '123', 'name' => 'Incoming', 'email' => 'changed@example.com', + ]); + $identity->token = 'incoming-token'; + $repository = new class($account) extends UserProviderRepository + { + public function __construct( + protected SoftDeletingUser $account, + ) {} + + public function exists(string $driver, SocialiteUserContract $user): bool + { + $exists = parent::exists($driver, $user); + $this->account->delete(); + + return $exists; + } + }; + + if ($restore) { + expect($repository->updateOrCreate('foo', $identity)->id)->toBe($account->id); + expect($account->fresh()->trashed())->toBeFalse() + ->and($account->fresh()->email)->toBe('changed@example.com'); + } else { + expect(fn () => $repository->updateOrCreate('foo', $identity)) + ->toThrow(AuthenticationException::class, 'This account has been deleted and cannot be restored.'); + expect($account->fresh()->trashed())->toBeTrue() + ->and($account->fresh()->name)->toBe('Original') + ->and($account->fresh()->email)->toBe('original@example.com') + ->and($account->fresh()->provider_access_token)->toBe('original-token'); + } + + expect(SoftDeletingUser::withTrashed()->count())->toBe(1); +})->with([true, false]); + +it('reports deleted identities as authentication failures instead of email conflicts', function (string $email) { + Bartender::dontRestoreSoftDeletedUsers(); + $account = SoftDeletingUser::create([ + 'name' => 'Deleted', 'email' => 'old@example.com', 'password' => 'password', + 'provider_name' => 'foo', 'provider_id' => '123', + ]); + $account->delete(); + $identity = (new SocialiteUser)->map(['id' => '123', 'name' => 'Incoming', 'email' => $email]); + $provider = mock(Provider::class); + $provider->shouldReceive('user')->once()->andReturn($identity); + $redirector = mock(ProviderRedirector::class); + $redirector->shouldReceive('unableToAuthenticateUser')->once() + ->with(Mockery::on(fn ($exception) => $exception instanceof AuthenticationException + && $exception->getMessage() === 'This account has been deleted and cannot be restored.'), 'foo') + ->andReturn($redirect = redirect('/deleted-account')); + $redirector->shouldNotReceive('userAlreadyExists'); + $redirector->shouldNotReceive('userAuthenticated'); + app()->instance(ProviderRedirector::class, $redirector); + + expect(app(UserProviderHandler::class)->callback($provider, 'foo'))->toBe($redirect) + ->and(Auth::check())->toBeFalse() + ->and($account->fresh()->trashed())->toBeTrue() + ->and($account->fresh()->email)->toBe('old@example.com') + ->and(SoftDeletingUser::withTrashed()->count())->toBe(1); +})->with(['old@example.com', 'changed@example.com']); diff --git a/tests/SoftDeletingUser.php b/tests/SoftDeletingUser.php new file mode 100644 index 0000000..3402213 --- /dev/null +++ b/tests/SoftDeletingUser.php @@ -0,0 +1,12 @@ +