lernschiff/app/Auth/TenantAwareUserProvider.php

84 lines
2.3 KiB
PHP

<?php
namespace App\Auth;
use App\Scopes\TenantScope;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Contracts\Support\Arrayable;
/**
* User provider that bypasses the TenantScope when retrieving users for
* authentication purposes (login, password reset, etc.).
*
* The TenantScope applies WHERE 0=1 for unauthenticated requests, which
* prevents Auth::attempt() from finding any user. This provider bypasses
* that restriction for credential lookups only.
*/
class TenantAwareUserProvider extends EloquentUserProvider
{
/**
* Retrieve a user by the given credentials without tenant scope.
*/
public function retrieveByCredentials(array $credentials)
{
$credentials = array_filter(
$credentials,
fn ($key) => ! str_contains($key, 'password'),
ARRAY_FILTER_USE_KEY,
);
if (empty($credentials)) {
return null;
}
$query = $this->newModelQuery()->withoutGlobalScope(TenantScope::class);
foreach ($credentials as $key => $value) {
if (is_array($value) || $value instanceof Arrayable) {
$query->whereIn($key, $value);
} else {
$query->where($key, $value);
}
}
return $query->first();
}
/**
* Retrieve a user by their unique identifier without tenant scope.
*/
public function retrieveById($identifier)
{
$model = $this->createModel();
return $this->newModelQuery()
->withoutGlobalScope(TenantScope::class)
->where($model->getAuthIdentifierName(), $identifier)
->first();
}
/**
* Retrieve a user by their unique identifier and "remember me" token
* without tenant scope.
*/
public function retrieveByToken($identifier, $token)
{
$model = $this->createModel();
$retrievedModel = $this->newModelQuery()
->withoutGlobalScope(TenantScope::class)
->where($model->getAuthIdentifierName(), $identifier)
->first();
if (! $retrievedModel) {
return null;
}
$rememberToken = $retrievedModel->getRememberToken();
return $rememberToken && hash_equals($rememberToken, $token)
? $retrievedModel
: null;
}
}