1 | <?php |
||
2 | |||
3 | namespace SMartins\PassportMultiauth; |
||
4 | |||
5 | use Mockery; |
||
6 | use Exception; |
||
7 | use Laravel\Passport\Token; |
||
8 | use Laravel\Passport\HasApiTokens; |
||
9 | use Illuminate\Support\Facades\App; |
||
10 | use SMartins\PassportMultiauth\Config\AuthConfigHelper; |
||
11 | |||
12 | class PassportMultiauth |
||
13 | { |
||
14 | /** |
||
15 | * Set the current user for the application with the given scopes. |
||
16 | * |
||
17 | * @param \Illuminate\Contracts\Auth\Authenticatable $user |
||
18 | * @param array $scopes |
||
19 | * @return \Illuminate\Contracts\Auth\Authenticatable |
||
20 | * @throws Exception |
||
21 | */ |
||
22 | 8 | public static function actingAs($user, $scopes = []) |
|
23 | { |
||
24 | 8 | $token = Mockery::mock(Token::class)->shouldIgnoreMissing(false); |
|
25 | |||
26 | 8 | foreach ($scopes as $scope) { |
|
27 | 1 | $token->shouldReceive('can')->with($scope)->andReturn(true); |
|
28 | } |
||
29 | |||
30 | 8 | $uses = array_flip(class_uses_recursive($user)); |
|
31 | |||
32 | 8 | if (! isset($uses[HasApiTokens::class])) { |
|
33 | 1 | throw new Exception('The model ['.get_class($user).'] must uses the trait '.HasApiTokens::class); |
|
34 | } |
||
35 | |||
36 | 7 | $user->withAccessToken($token); |
|
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
37 | |||
38 | 7 | if (isset($user->wasRecentlyCreated) && $user->wasRecentlyCreated) { |
|
0 ignored issues
–
show
|
|||
39 | $user->wasRecentlyCreated = false; |
||
40 | 7 | } |
|
41 | |||
42 | 7 | $guard = AuthConfigHelper::getUserGuard($user); |
|
43 | 7 | ||
44 | app('auth')->guard($guard)->setUser($user); |
||
45 | |||
46 | app('auth')->shouldUse($guard); |
||
47 | |||
48 | return $user; |
||
49 | } |
||
50 | |||
51 | 7 | /** |
|
52 | * If running unit test and try authenticate an user with actingAs($user) |
||
53 | 7 | * check the guards on request to authenticate or not the user. |
|
54 | 6 | * |
|
55 | * @return \Illuminate\Contracts\Auth\Authenticatable|null |
||
56 | 1 | */ |
|
57 | public static function userActing() |
||
58 | { |
||
59 | if (App::runningUnitTests() && $user = app('auth')->user()) { |
||
60 | return $user; |
||
61 | } |
||
62 | } |
||
63 | } |
||
64 |