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,34 +71,72 @@ class NamiGuard {
*/
public function attempt(array $credentials = [], bool $remember = false): bool
{
$beforeResult = static::runBeforeLogin($credentials, $remember);
if (!is_null($beforeResult)) {
return $beforeResult;
}
try {
$api = Nami::login($credentials['mglnr'], $credentials['password']);
$user = $api->findNr($credentials['mglnr']);
$payload = [
'credentials' => $credentials,
'firstname' => $user->firstname,
'lastname' => $user->lastname,
'group_id' => $user->group_id,
];
$this->setUser(NamiUser::fromPayload($payload));
$key = $this->newCacheKey();
Cache::forever("namiauth-{$key}", $payload);
$this->updateSession($key);
return true;
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((int) $credentials['mglnr']);
$payload = [
'credentials' => $credentials,
'firstname' => $user->firstname,
'lastname' => $user->lastname,
'group_id' => $user->group_id,
];
$this->setUser(NamiUser::fromPayload($payload));
$key = $this->newCacheKey();
Cache::forever("namiauth-{$key}", $payload);
$this->updateSession($key);
return true;
}
/**
* @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
{
$this->session->put($this->getName(), $data);
$this->session->migrate(true);
}
/**
* @param callable $callback
*/
public static function beforeLogin(callable $callback): void
{
static::$loginCallbacks[] = $callback;
}
public function getName(): string
{
return 'auth_key';