Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
21 changes: 21 additions & 0 deletions src/BartenderManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down
2 changes: 2 additions & 0 deletions src/Facades/Bartender.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
36 changes: 34 additions & 2 deletions src/UserProviderRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'])
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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()]
Expand All @@ -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.
*/
Expand Down
16 changes: 16 additions & 0 deletions tests/BartenderManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
237 changes: 237 additions & 0 deletions tests/SoftDeleteRestorationTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,237 @@
<?php

use DirectoryTree\Bartender\Facades\Bartender;
use DirectoryTree\Bartender\ProviderRedirector;
use DirectoryTree\Bartender\Tests\SoftDeletingUser;
use DirectoryTree\Bartender\Tests\User;
use DirectoryTree\Bartender\UserProviderHandler;
use DirectoryTree\Bartender\UserProviderRepository;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Schema;
use Laravel\Socialite\Contracts\Provider;
use Laravel\Socialite\Contracts\User as SocialiteUserContract;
use Laravel\Socialite\Two\User as SocialiteUser;

beforeEach(function () {
Schema::table('users', function (Blueprint $table) {
$table->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']);
Loading
Loading