Created
June 13, 2019 12:21
-
-
Save tobiashm/ad785be8ab92d3e2284cf39768ce65a4 to your computer and use it in GitHub Desktop.
Laravel composite guard
This file contains hidden or 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\Providers; | |
use App\Auth\CompositeGuard; | |
use Illuminate\Auth\TokenGuard; | |
use Illuminate\Foundation\Application; | |
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; | |
use MiladRahimi\LaraJwt\Guards\Jwt as JwtGuard; | |
class AuthServiceProvider extends ServiceProvider | |
{ | |
public function boot(): void | |
{ | |
$this->registerPolicies(); | |
\Auth::extend('any_token', static function (Application $app) { | |
$userProvider = \Auth::createUserProvider('users'); | |
$request = $app->make('request'); | |
$tokenGuard = new TokenGuard($userProvider, $request); | |
$jwtGuard = new JwtGuard($userProvider, $request); | |
return new CompositeGuard($tokenGuard, $jwtGuard); | |
}); | |
} | |
} |
This file contains hidden or 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\Auth; | |
use Illuminate\Auth\GuardHelpers; | |
use Illuminate\Contracts\Auth\Authenticatable; | |
use Illuminate\Contracts\Auth\Guard; | |
use Illuminate\Support\Arr; | |
class CompositeGuard implements Guard | |
{ | |
use GuardHelpers; | |
/** | |
* @var Guard[] | |
*/ | |
private $guards; | |
public function __construct(Guard ...$guards) | |
{ | |
$this->guards = $guards; | |
} | |
/** | |
* Get the currently authenticated user. | |
*/ | |
public function user(): ?Authenticatable | |
{ | |
$guard = $this->find(static function(Guard $guard) { | |
return $guard->user() !== null; | |
}); | |
return $guard ? $guard->user() : null; | |
} | |
/** | |
* Validate a user's credentials. | |
* | |
* @param array $credentials | |
*/ | |
public function validate(array $credentials = []): bool | |
{ | |
$guard = $this->find(static function (Guard $guard) use ($credentials) { | |
return $guard->validate($credentials); | |
}); | |
return $guard !== null; | |
} | |
private function find(callable $callable): ?Guard | |
{ | |
return Arr::first($this->guards, $callable); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment