Completed
Push — master ( a1da6f...207f38 )
by Arthur
01:11
created

Token::generateApnsTopic()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16

Duplication

Lines 16
Ratio 100 %

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 1
dl 16
loc 16
rs 9.7333
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the Pushok package.
5
 *
6
 * (c) Arthur Edamov <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Pushok\AuthProvider;
13
14
use Jose\Component\Core\JWK;
15
use Jose\Component\KeyManagement\JWKFactory;
16
use Jose\Component\Core\AlgorithmManager;
17
use Jose\Component\Signature\JWSBuilder;
18
use Jose\Component\Signature\Algorithm\ES512;
19
use Jose\Component\Signature\Serializer\CompactSerializer;
20
use Pushok\AuthProviderInterface;
21
use Pushok\Request;
22
23
/**
24
 * Class Token
25
 * @package Pushok\AuthProvider
26
 *
27
 * @see http://bit.ly/communicating-with-apns
28
 */
29
class Token implements AuthProviderInterface
0 ignored issues
show
Coding Style introduced by
Since you have declared the constructor as private, maybe you should also declare the class as final.
Loading history...
30
{
31
    /**
32
     * Generated auth token.
33
     *
34
     * @var string
35
     */
36
    private $token;
37
38
    /**
39
     * Path to p8 private key.
40
     *
41
     * @var string|null
42
     */
43
    private $privateKeyPath;
44
45
    /**
46
     * Private key data.
47
     *
48
     * @var string|null
49
     */
50
    private $privateKeyContent;
51
52
    /**
53
     * Private key secret.
54
     *
55
     * @var string|null
56
     */
57
    private $privateKeySecret;
58
59
    /**
60
     * The Key ID obtained from Apple developer account.
61
     *
62
     * @var string
63
     */
64
    private $keyId;
65
66
    /**
67
     * The Team ID obtained from Apple developer account.
68
     *
69
     * @var string
70
     */
71
    private $teamId;
72
73
    /**
74
     * The bundle ID for app obtained from Apple developer account.
75
     *
76
     * @var string
77
     */
78
    private $appBundleId;
79
80
    /**
81
     * This provider accepts the following options:
82
     *
83
     * - key_id
84
     * - team_id
85
     * - app_bundle_id
86
     * - private_key_path
87
     * - private_key_content
88
     * - private_key_secret
89
     *
90
     * @param array $options
91
     */
92
    private function __construct(array $options)
93
    {
94
        $this->keyId = $options['key_id'];
95
        $this->teamId = $options['team_id'];
96
        $this->appBundleId = $options['app_bundle_id'];
97
        $this->privateKeyPath = $options['private_key_path'] ?? null;
98
        $this->privateKeyContent = $options['private_key_content'] ?? null;
99
        $this->privateKeySecret = $options['private_key_secret'] ?? null;
100
    }
101
102
    /**
103
     * Create Token Auth Provider.
104
     *
105
     * @param array $options
106
     * @return Token
107
     */
108
    public static function create(array $options): Token
109
    {
110
        $token = new self($options);
111
        $token->token = $token->generate();
112
113
        return $token;
114
    }
115
116
    /**
117
     * Use previously generated token.
118
     *
119
     * @param string $tokenString
120
     * @param array $options
121
     * @return Token
122
     */
123
    public static function useExisting(string $tokenString, array $options): Token
124
    {
125
        $token = new self($options);
126
        $token->token = $tokenString;
127
128
        return $token;
129
    }
130
131
    /**
132
     * Authenticate client.
133
     *
134
     * @param Request $request
135
     */
136
    public function authenticateClient(Request $request)
137
    {
138
        $request->addHeaders([
139
            'apns-topic' => $this->generateApnsTopic($request->getHeaders()['apns-push-type']),
140
            'Authorization' => 'bearer ' . $this->token,
141
        ]);
142
    }
143
144
    /**
145
     * Generate a correct apns-topic string
146
     *
147
     * @param string $pushType
148
     * @return string
149
     */
150 View Code Duplication
    public function generateApnsTopic(string $pushType)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
151
    {
152
        switch ($pushType) {
153
            case 'voip':
154
                return $this->appBundleId . '.voip';
155
156
            case 'complication':
157
                return $this->appBundleId . '.complication';
158
159
            case 'fileprovider':
160
                return $this->appBundleId . '.pushkit.fileprovider';
161
162
            default:
163
                return $this->appBundleId;
164
        }
165
    }
166
167
    /**
168
     * Get last generated token.
169
     *
170
     * @return string
171
     */
172
    public function get(): string
173
    {
174
        return $this->token;
175
    }
176
177
    /**
178
     * Generate private EC key.
179
     *
180
     * @return JWK
181
     */
182
    private function generatePrivateECKey(): JWK
183
    {
184
        if ($this->privateKeyContent) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->privateKeyContent of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
185
            $content = $this->privateKeyContent;
186
        } elseif ($this->privateKeyPath) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->privateKeyPath of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
187
            $content = \file_get_contents($this->privateKeyPath);
188
        } else {
189
            throw new \InvalidArgumentException('Unable to find private key.');
190
        }
191
192
        return JWKFactory::createFromKey($content, $this->privateKeySecret, [
193
            'kid' => $this->keyId,
194
            'alg' => 'ES512',
195
            'use' => 'sig'
196
        ]);
197
    }
198
199
    /**
200
     * Get claims payload.
201
     *
202
     * @return array
203
     */
204
    private function getClaimsPayload(): array
205
    {
206
        return [
207
            'iss' => $this->teamId,
208
            'iat' => time(),
209
        ];
210
    }
211
212
    /**
213
     * Get protected header.
214
     *
215
     * @param JWK $privateECKey
216
     * @return array
217
     */
218
    private function getProtectedHeader(JWK $privateECKey): array
219
    {
220
        return [
221
            'alg' => 'ES512',
222
            'kid' => $privateECKey->get('kid'),
223
        ];
224
    }
225
226
    /**
227
     * Generate new token.
228
     *
229
     * @return string
230
     */
231
    private function generate(): string
232
    {
233
        $algorithmManager = new AlgorithmManager([
234
          new ES512(),
235
        ]);
236
237
        $jwsBuilder = new JWSBuilder($algorithmManager);
238
        $payload = json_encode($this->getClaimsPayload(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
239
240
        $privateECKey = $this->generatePrivateECKey();
241
242
        $jws = $jwsBuilder
243
            ->create()
244
            ->withPayload($payload)
245
            ->addSignature($privateECKey, $this->getProtectedHeader($privateECKey))
246
            ->build();
247
248
        $serializer = new CompactSerializer();
249
        $this->token = $serializer->serialize($jws);
250
251
        return $this->token;
252
    }
253
}
254