Skip to content

Instantly share code, notes, and snippets.

@jenky
Created May 11, 2022 12:49
Show Gist options
  • Save jenky/161c86a1f689d9493db8fac85b831287 to your computer and use it in GitHub Desktop.
Save jenky/161c86a1f689d9493db8fac85b831287 to your computer and use it in GitHub Desktop.
Laravel Compass Passport authenticator
<?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