Completed
Pull Request — master (#101)
by Chimit
01:26
created

Token::generateApnsTopic()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 20

Duplication

Lines 20
Ratio 100 %

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 1
dl 20
loc 20
rs 9.6
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
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
156
157
            case 'complication':
158
                return $this->appBundleId . '.complication';
159
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
160
161
            case 'fileprovider':
162
                return $this->appBundleId . '.pushkit.fileprovider';
163
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
164
165
            default:
166
                return $this->appBundleId;
167
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
168
        }
169
    }
170
171
    /**
172
     * Get last generated token.
173
     *
174
     * @return string
175
     */
176
    public function get(): string
177
    {
178
        return $this->token;
179
    }
180
181
    /**
182
     * Generate private EC key.
183
     *
184
     * @return JWK
185
     */
186
    private function generatePrivateECKey(): JWK
187
    {
188
        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...
189
            $content = $this->privateKeyContent;
190
        } 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...
191
            $content = \file_get_contents($this->privateKeyPath);
192
        } else {
193
            throw new \InvalidArgumentException('Unable to find private key.');
194
        }
195
196
        return JWKFactory::createFromKey($content, $this->privateKeySecret, [
197
            'kid' => $this->keyId,
198
            'alg' => 'ES512',
199
            'use' => 'sig'
200
        ]);
201
    }
202
203
    /**
204
     * Get claims payload.
205
     *
206
     * @return array
207
     */
208
    private function getClaimsPayload(): array
209
    {
210
        return [
211
            'iss' => $this->teamId,
212
            'iat' => time(),
213
        ];
214
    }
215
216
    /**
217
     * Get protected header.
218
     *
219
     * @param JWK $privateECKey
220
     * @return array
221
     */
222
    private function getProtectedHeader(JWK $privateECKey): array
223
    {
224
        return [
225
            'alg' => 'ES512',
226
            'kid' => $privateECKey->get('kid'),
227
        ];
228
    }
229
230
    /**
231
     * Generate new token.
232
     *
233
     * @return string
234
     */
235
    private function generate(): string
236
    {
237
        $algorithmManager = new AlgorithmManager([
238
          new ES512(),
239
        ]);
240
241
        $jwsBuilder = new JWSBuilder($algorithmManager);
242
        $payload = json_encode($this->getClaimsPayload(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
243
244
        $privateECKey = $this->generatePrivateECKey();
245
246
        $jws = $jwsBuilder
247
            ->create()
248
            ->withPayload($payload)
249
            ->addSignature($privateECKey, $this->getProtectedHeader($privateECKey))
250
            ->build();
251
252
        $serializer = new CompactSerializer();
253
        $this->token = $serializer->serialize($jws);
254
255
        return $this->token;
256
    }
257
}
258