Completed
Push — master ( 7c0e89...5c9864 )
by Wang
13:40
created

MiniProgramResourceOwner::getResponseUserInfo()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
4
namespace Oakhope\OAuth2\Client\Provider;
5
6
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
7
use League\OAuth2\Client\Provider\ResourceOwnerInterface;
8
use Oakhope\OAuth2\Client\Token\MiniProgram\AccessToken;
9
use Oakhope\OAuth2\Client\Support\MiniProgram\MiniProgramDataCrypt;
10
11
class MiniProgramResourceOwner implements ResourceOwnerInterface
12
{
13
    /** @var  AccessToken */
14
    protected $token;
15
16
    protected $appid;
17
    protected $responseUserInfo;
18
    protected $decryptData;
19
20
    public function __construct(array $response, $token, $appid)
21
    {
22
        $this->checkSignature($response, $token);
23
        $this->responseUserInfo = $response;
24
        $this->token = $token;
25
        $this->appid = $appid;
26
27
        if (!empty($response['encryptedData'])) {
28
            $this->decryptData = $this->decrypt();
29
        }
30
    }
31
32
33
    /**
34
     * @param $response
35
     * @param AccessToken $token
36
     * @throws \Exception
37
     */
38
    private function checkSignature($response, $token)
39
    {
40
        if ($response['signature'] !== sha1(
41
            $response['rawData'].$token->getSessionKey()
42
        )) {
43
            throw new IdentityProviderException('signature error', 0, $response);
44
        }
45
    }
46
47
    /**
48
     * @return mixed
49
     * @throws \Exception
50
     */
51
    private function decrypt()
52
    {
53
        $dataCrypt = new MiniProgramDataCrypt(
54
            $this->appid,
55
            $this->token->getSessionKey()
56
        );
57
        $errCode = $dataCrypt->decryptData(
58
            $this->responseUserInfo['encryptedData'],
59
            $this->responseUserInfo['iv'],
60
            $data
61
        );
62
63
        if ($errCode == 0) {
64
            return $data;
65
        } else {
66
            throw new IdentityProviderException('decrypt error', $errCode, $this->responseUserInfo);
67
        }
68
    }
69
70
    /**
71
     * Returns the identifier of the authorized resource owner.
72
     *
73
     * @return mixed
74
     */
75
    public function getId()
76
    {
77
        return $this->decryptData ? $this->decryptData['openid'] : null;
78
    }
79
80
    public function getDecryptData()
81
    {
82
        return $this->decryptData;
83
    }
84
85
    public function getResponseUserInfo()
86
    {
87
        return $this->responseUserInfo;
88
    }
89
90
    /**
91
     * Return all of the owner details available as an array.
92
     *
93
     * @return array
94
     */
95
    public function toArray()
96
    {
97
        return $this->token->getValues();
98
    }
99
}
100