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
|
|
|
/** |
16
|
|
|
* Indicates if MultiAuth migrations will be run. |
17
|
|
|
* |
18
|
|
|
* @var bool |
19
|
|
|
*/ |
20
|
|
|
public static $runsMigrations = true; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Configure MultiAuth to not register its migrations. |
24
|
|
|
* |
25
|
|
|
* @return static |
26
|
|
|
*/ |
27
|
|
|
public static function ignoreMigrations() |
28
|
|
|
{ |
29
|
|
|
static::$runsMigrations = false; |
30
|
|
|
|
31
|
|
|
return new static; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Set the current user for the application with the given scopes. |
36
|
|
|
* |
37
|
|
|
* @param \Illuminate\Contracts\Auth\Authenticatable $user |
38
|
|
|
* @param array $scopes |
39
|
|
|
* @return \Illuminate\Contracts\Auth\Authenticatable |
40
|
|
|
* @throws Exception |
41
|
|
|
*/ |
42
|
4 |
|
public static function actingAs($user, $scopes = []) |
43
|
|
|
{ |
44
|
4 |
|
$token = Mockery::mock(Token::class)->shouldIgnoreMissing(false); |
45
|
|
|
|
46
|
4 |
|
foreach ($scopes as $scope) { |
47
|
1 |
|
$token->shouldReceive('can')->with($scope)->andReturn(true); |
48
|
|
|
} |
49
|
|
|
|
50
|
4 |
|
$uses = array_flip(class_uses_recursive($user)); |
51
|
|
|
|
52
|
4 |
|
if (!isset($uses[HasApiTokens::class])) { |
53
|
1 |
|
throw new Exception('The model [' . get_class($user) . '] must uses the trait ' . HasApiTokens::class); |
54
|
|
|
} |
55
|
|
|
|
56
|
3 |
|
$user->withAccessToken($token); |
|
|
|
|
57
|
|
|
|
58
|
3 |
|
if (isset($user->wasRecentlyCreated) && $user->wasRecentlyCreated) { |
|
|
|
|
59
|
3 |
|
$user->wasRecentlyCreated = false; |
60
|
|
|
} |
61
|
|
|
|
62
|
3 |
|
$guard = AuthConfigHelper::getUserGuard($user); |
63
|
|
|
|
64
|
3 |
|
app('auth')->guard($guard)->setUser($user); |
65
|
|
|
|
66
|
3 |
|
app('auth')->shouldUse($guard); |
67
|
|
|
|
68
|
3 |
|
return $user; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* If running unit test and try authenticate an user with actingAs($user) |
73
|
|
|
* check the guards on request to authenticate or not the user. |
74
|
|
|
* |
75
|
|
|
* @return \Illuminate\Contracts\Auth\Authenticatable|null |
76
|
|
|
*/ |
77
|
3 |
|
public static function userActing() |
78
|
|
|
{ |
79
|
3 |
|
if (App::runningUnitTests() && $user = app('auth')->user()) { |
80
|
2 |
|
return $user; |
81
|
|
|
} |
82
|
1 |
|
} |
83
|
|
|
} |
84
|
|
|
|