diff --git a/src/Authentication/NamiGuard.php b/src/Authentication/NamiGuard.php index 6965b30..45ddcb3 100644 --- a/src/Authentication/NamiGuard.php +++ b/src/Authentication/NamiGuard.php @@ -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 $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 $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 $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';