Created
May 11, 2022 12:49
-
-
Save jenky/161c86a1f689d9493db8fac85b831287 to your computer and use it in GitHub Desktop.
Laravel Compass Passport authenticator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Support; | |
use Davidhsianturi\Compass\Authenticators\CredentialResult; | |
use Davidhsianturi\Compass\Authenticators\UserProvider; | |
use Davidhsianturi\Compass\Contracts\AuthenticatorRepository; | |
use Illuminate\Support\Arr; | |
use Illuminate\Support\Facades\Cache; | |
class PassportAuthenticator implements AuthenticatorRepository | |
{ | |
use UserProvider; | |
/** | |
* Return a valid credential of users. | |
* | |
* @return \Illuminate\Support\Collection|\Davidhsianturi\Compass\Authenticators\CredentialResult[] | |
*/ | |
public function credentials() | |
{ | |
return $this->getUsers() | |
->map(function ($user) { | |
$identifier = Arr::only($user->toArray(), (array) $this->identifier); | |
$identifier = ! empty(array_filter($identifier)) ? implode(' - ', $identifier) : 'anonymous'; | |
return new CredentialResult( | |
$identifier, $this->getTokenFromStorage($user) | |
); | |
})->values(); | |
} | |
/** | |
* Get the cached token from cache storage or create new if not exists. | |
* | |
* @param \App\Models\User $user | |
* @return string | |
*/ | |
protected function getTokenFromStorage($user) | |
{ | |
return Cache::remember('compass::passport::'.$user->getKey(), now()->addMonths(3), function () use ($user) { | |
return $user->createToken('Compass', ['*'])->accessToken; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment