Skip to content

Commit d511a3c

Browse files
authored
[11.x] Stub client on guard when calling Passport::actingAsClient() (#1519)
* Allow token guard client to be set programmatically * Set the client on the TokenGuard when mocking the client * Apply fixes from StyleCI
1 parent 231ef17 commit d511a3c

File tree

3 files changed

+28
-3
lines changed

3 files changed

+28
-3
lines changed

src/Guards/TokenGuard.php

+14
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
use Illuminate\Cookie\Middleware\EncryptCookies;
1414
use Illuminate\Http\Request;
1515
use Illuminate\Support\Traits\Macroable;
16+
use Laravel\Passport\Client;
1617
use Laravel\Passport\ClientRepository;
1718
use Laravel\Passport\Passport;
1819
use Laravel\Passport\PassportUserProvider;
@@ -353,4 +354,17 @@ public static function serialized()
353354
{
354355
return EncryptCookies::serialized('XSRF-TOKEN');
355356
}
357+
358+
/**
359+
* Set the client for the current request.
360+
*
361+
* @param \Laravel\Passport\Client $client
362+
* @return $this
363+
*/
364+
public function setClient(Client $client)
365+
{
366+
$this->client = $client;
367+
368+
return $this;
369+
}
356370
}

src/Passport.php

+6-1
Original file line numberDiff line numberDiff line change
@@ -388,9 +388,10 @@ public static function actingAs($user, $scopes = [], $guard = 'api')
388388
*
389389
* @param \Laravel\Passport\Client $client
390390
* @param array $scopes
391+
* @param string $guard
391392
* @return \Laravel\Passport\Client
392393
*/
393-
public static function actingAsClient($client, $scopes = [])
394+
public static function actingAsClient($client, $scopes = [], $guard = 'api')
394395
{
395396
$token = app(self::tokenModel());
396397

@@ -414,6 +415,10 @@ public static function actingAsClient($client, $scopes = [])
414415

415416
app()->instance(TokenRepository::class, $mock);
416417

418+
app('auth')->guard($guard)->setClient($client);
419+
420+
app('auth')->shouldUse($guard);
421+
417422
return $client;
418423
}
419424

tests/Feature/ActingAsClientTest.php

+8-2
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,8 @@
77
use Laravel\Passport\Http\Middleware\CheckClientCredentials;
88
use Laravel\Passport\Http\Middleware\CheckClientCredentialsForAnyScope;
99
use Laravel\Passport\Passport;
10-
use Orchestra\Testbench\TestCase;
1110

12-
class ActingAsClientTest extends TestCase
11+
class ActingAsClientTest extends PassportTestCase
1312
{
1413
public function testActingAsClientWhenTheRouteIsProtectedByCheckClientCredentialsMiddleware()
1514
{
@@ -46,4 +45,11 @@ public function testActingAsClientWhenTheRouteIsProtectedByCheckClientCredential
4645
$response->assertSuccessful();
4746
$response->assertSee('bar');
4847
}
48+
49+
public function testActingAsClientSetsTheClientOnTheGuard()
50+
{
51+
Passport::actingAsClient($client = new Client());
52+
53+
$this->assertSame($client, app('auth')->client());
54+
}
4955
}

0 commit comments

Comments
 (0)