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