Add filter for guard

This commit is contained in:
philipp lang 2021-11-23 01:01:30 +01:00
parent d96457dd33
commit 6d6aa60363
1 changed files with 58 additions and 16 deletions

View File

@ -10,6 +10,7 @@ use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Session\Store as SessionStore;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Str;
use Zoomyboy\LaravelNami\LoginException;
use Zoomyboy\LaravelNami\Nami;
@ -21,6 +22,9 @@ class NamiGuard {
protected CacheRepository $cache;
/** @var <int, callback> $loginCallbacks */
public static array $loginCallbacks = [];
/**
* The currently authenticated user.
*
@ -67,9 +71,26 @@ class NamiGuard {
*/
public function attempt(array $credentials = [], bool $remember = false): bool
{
$beforeResult = static::runBeforeLogin($credentials, $remember);
if (!is_null($beforeResult)) {
return $beforeResult;
}
try {
return $this->login($credentials);
} catch (LoginException $e) {
return false;
}
}
/**
* @param array<string, string> $credentials
*/
public function login(array $credentials): bool
{
$api = Nami::login($credentials['mglnr'], $credentials['password']);
$user = $api->findNr($credentials['mglnr']);
$user = $api->findNr((int) $credentials['mglnr']);
$payload = [
'credentials' => $credentials,
@ -84,9 +105,22 @@ class NamiGuard {
$this->updateSession($key);
return true;
} catch (LoginException $e) {
return false;
}
/**
* @param array<string, string> $credentials
* @param bool $remember
*/
protected function runBeforeLogin(array $credentials, bool $remember): ?bool
{
foreach (static::$loginCallbacks as $callback) {
$result = $callback($credentials, $remember);
if ($result !== null) {
return $result;
}
}
return null;
}
protected function updateSession(string $data): void
@ -95,6 +129,14 @@ class NamiGuard {
$this->session->migrate(true);
}
/**
* @param callable $callback
*/
public static function beforeLogin(callable $callback): void
{
static::$loginCallbacks[] = $callback;
}
public function getName(): string
{
return 'auth_key';