1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace app\modules\auth\services; |
4
|
|
|
|
5
|
|
|
use yii\authclient\ClientInterface; |
6
|
|
|
use app\modules\auth\oauth\ParserInterface; |
7
|
|
|
use app\models\entity\{User, UserProvider}; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* SocialAuth handles successful authentication |
11
|
|
|
*/ |
12
|
|
|
class SocialAuth |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var ParserInterface |
16
|
|
|
*/ |
17
|
|
|
private $parser; |
18
|
|
|
/** |
19
|
|
|
* @var ClientInterface |
20
|
|
|
*/ |
21
|
|
|
private $provider; |
22
|
|
|
/** |
23
|
|
|
* @var int |
24
|
|
|
*/ |
25
|
|
|
private $providerType; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @param ParserInterface $parser |
29
|
|
|
* @param ClientInterface $provider |
30
|
|
|
*/ |
31
|
|
|
public function __construct(ParserInterface $parser, ClientInterface $provider) |
32
|
|
|
{ |
33
|
|
|
$this->parser = $parser; |
34
|
|
|
$this->provider = $provider; |
35
|
|
|
$this->providerType = UserProvider::getTypeByName($provider->id); |
|
|
|
|
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function getUser(): User |
39
|
|
|
{ |
40
|
|
|
$user = null; |
41
|
|
|
|
42
|
|
|
$existUserProvider = UserProvider::find() |
43
|
|
|
->provider($this->providerType, $this->parser->profileId()) |
44
|
|
|
->one(); |
45
|
|
|
|
46
|
|
|
if ($existUserProvider) { |
47
|
|
|
$user = $existUserProvider->user; |
48
|
|
|
|
49
|
|
|
// if exist then update access tokens |
50
|
|
|
$existUserProvider->setAttributes($this->providerAttributes(), false); |
51
|
|
|
$existUserProvider->save(); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
if (!is_object($user)) { |
55
|
|
|
$user = new User(); |
56
|
|
|
|
57
|
|
|
$user->email = $this->parser->email(); |
58
|
|
|
$user->setProfile($this->profileAttributes()); |
59
|
|
|
$user->setProviders($this->providerAttributes()); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return $user; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
private function profileAttributes() |
66
|
|
|
{ |
67
|
|
|
return [ |
68
|
|
|
'full_name' => $this->parser->fullName(), |
69
|
|
|
'photo' => $this->parser->photo(), |
70
|
|
|
]; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
private function providerAttributes() |
74
|
|
|
{ |
75
|
|
|
return [ |
76
|
|
|
'type' => $this->providerType, |
77
|
|
|
'profile_id' => $this->parser->profileId(), |
78
|
|
|
'profile_url' => $this->parser->profileUrl(), |
79
|
|
|
'access_token' => $this->parser->accessToken(), |
80
|
|
|
'access_token_secret' => $this->parser->accessTokenSecret(), |
81
|
|
|
]; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|
If you access a property on an interface, you most likely code against a concrete implementation of the interface.
Available Fixes
Adding an additional type check:
Changing the type hint: