forked from Kyon147/laravel-shopify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVerifyShopify.php
540 lines (478 loc) · 15.8 KB
/
VerifyShopify.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
<?php
namespace Osiset\ShopifyApp\Http\Middleware;
use Assert\AssertionFailedException;
use Closure;
use Illuminate\Auth\AuthManager;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Str;
use Osiset\ShopifyApp\Contracts\ApiHelper as IApiHelper;
use Osiset\ShopifyApp\Contracts\Objects\Values\ShopDomain as ShopDomainValue;
use Osiset\ShopifyApp\Contracts\Queries\Shop as IShopQuery;
use Osiset\ShopifyApp\Contracts\ShopModel;
use Osiset\ShopifyApp\Exceptions\HttpException;
use Osiset\ShopifyApp\Exceptions\SignatureVerificationException;
use Osiset\ShopifyApp\Objects\Enums\DataSource;
use Osiset\ShopifyApp\Objects\Values\NullableSessionId;
use Osiset\ShopifyApp\Objects\Values\SessionContext;
use Osiset\ShopifyApp\Objects\Values\SessionToken;
use Osiset\ShopifyApp\Objects\Values\ShopDomain;
use Osiset\ShopifyApp\Util;
/**
* Responsible for validating the request.
*/
class VerifyShopify
{
/**
* The auth manager.
*
* @var AuthManager
*/
protected $auth;
/**
* The API helper.
*
* @var IApiHelper
*/
protected $apiHelper;
/**
* The shop querier.
*
* @var IShopQuery
*/
protected $shopQuery;
/**
* Previous request shop.
*
* @var ShopModel|null
*/
protected $previousShop;
/**
* Constructor.
*
* @param AuthManager $auth The Laravel auth manager.
* @param IApiHelper $apiHelper The API helper.
* @param IShopQuery $shopQuery The shop querier.
*
* @return void
*/
public function __construct(
AuthManager $auth,
IApiHelper $apiHelper,
IShopQuery $shopQuery
) {
$this->auth = $auth;
$this->shopQuery = $shopQuery;
$this->apiHelper = $apiHelper;
$this->apiHelper->make();
}
/**
* Undocumented function.
*
* @param Request $request The request object.
* @param Closure $next The next action.
*
* @throws SignatureVerificationException|HttpException If HMAC verification fails.
*
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
// Verify the HMAC (if available)
$hmacResult = $this->verifyHmac($request);
if ($hmacResult === false) {
// Invalid HMAC
throw new SignatureVerificationException('Unable to verify signature.');
}
// Continue if current route is an auth or billing route
if (Str::contains($request->getRequestUri(), ['/authenticate', '/billing'])) {
return $next($request);
}
if (!Util::useNativeAppBridge()) {
$shop = $this->getShopIfAlreadyInstalled($request);
$storeResult = !$this->isApiRequest($request) && $shop;
if ($storeResult) {
$this->loginFromShop($shop);
return $next($request);
}
}
$tokenSource = $this->getAccessTokenFromRequest($request);
if ($tokenSource === null) {
//Check if there is a store record in the database
return $this->checkPreviousInstallation($request)
// Shop exists, token not available, we need to get one
? $this->handleMissingToken($request)
// Shop does not exist
: $this->handleInvalidShop($request);
}
try {
// Try and process the token
$token = SessionToken::fromNative($tokenSource);
} catch (AssertionFailedException $e) {
// Invalid or expired token, we need a new one
return $this->handleInvalidToken($request, $e);
}
// Set the previous shop (if available)
if ($request->user()) {
$this->previousShop = $request->user();
}
// Login the shop
$loginResult = $this->loginShopFromToken(
$token,
NullableSessionId::fromNative($request->query('session'))
);
if (! $loginResult) {
// Shop is not installed or something is missing from it's data
return $this->handleInvalidShop($request);
}
return $next($request);
}
/**
* Handle missing token.
*
* @param Request $request The request object.
*
* @throws HttpException If an AJAX/JSON request.
*
* @return mixed
*/
protected function handleMissingToken(Request $request)
{
if ($this->isApiRequest($request)) {
// AJAX, return HTTP exception
throw new HttpException(SessionToken::EXCEPTION_INVALID, Response::HTTP_BAD_REQUEST);
}
return $this->tokenRedirect($request);
}
/**
* Handle an invalid or expired token.
*
* @param Request $request The request object.
* @param AssertionFailedException $e The assertion failure exception.
*
* @throws HttpException If an AJAX/JSON request.
*
* @return mixed
*/
protected function handleInvalidToken(Request $request, AssertionFailedException $e)
{
$isExpired = $e->getMessage() === SessionToken::EXCEPTION_EXPIRED;
if ($this->isApiRequest($request)) {
// AJAX, return HTTP exception
throw new HttpException(
$e->getMessage(),
$isExpired ? Response::HTTP_FORBIDDEN : Response::HTTP_BAD_REQUEST
);
}
return $this->tokenRedirect($request);
}
/**
* Handle a shop that is not installed or it's data is invalid.
*
* @param Request $request The request object.
*
* @throws HttpException If an AJAX/JSON request.
*
* @return mixed
*/
protected function handleInvalidShop(Request $request)
{
if ($this->isApiRequest($request)) {
// AJAX, return HTTP exception
throw new HttpException('Shop is not installed or missing data.', Response::HTTP_FORBIDDEN);
}
return $this->installRedirect(ShopDomain::fromRequest($request));
}
/**
* Verify HMAC data, if present.
*
* @param Request $request The request object.
*
* @throws SignatureVerificationException
*
* @return bool|null
*/
protected function verifyHmac(Request $request): ?bool
{
$hmac = $this->getHmacFromRequest($request);
if ($hmac['source'] === null) {
// No HMAC, skip
return null;
}
// We have HMAC, validate it
$data = $this->getRequestData($request, $hmac['source']);
return $this->apiHelper->verifyRequest($data);
}
/**
* Login and verify the shop and it's data.
*
* @param SessionToken $token The session token.
* @param NullableSessionId $sessionId Incoming session ID (if available).
*
* @return bool
*/
protected function loginShopFromToken(SessionToken $token, NullableSessionId $sessionId): bool
{
// Get the shop
$shop = $this->shopQuery->getByDomain($token->getShopDomain(), [], true);
if (! $shop) {
return false;
}
// Set the session details for the token, session ID, and access token
$context = new SessionContext($token, $sessionId, $shop->getAccessToken());
$shop->setSessionContext($context);
$previousContext = $this->previousShop ? $this->previousShop->getSessionContext() : null;
if (! $shop->getSessionContext()->isValid($previousContext)) {
// Something is invalid
return false;
}
// Override auth guard
if (($guard = Util::getShopifyConfig('shop_auth_guard'))) {
$this->auth->setDefaultDriver($guard);
}
// All is well, login the shop
$this->auth->login($shop);
return true;
}
/**
* Redirect to token route.
*
* @param Request $request The request object.
*
* @return RedirectResponse
*/
protected function tokenRedirect(Request $request): RedirectResponse
{
// At this point the HMAC and other details are verified already, filter it out
$path = $request->path();
$target = Str::start($path, '/');
if ($request->query()) {
$filteredQuery = Collection::make($request->query())->except([
'hmac',
'locale',
'new_design_language',
'timestamp',
'session',
'shop',
]);
if ($filteredQuery->isNotEmpty()) {
$target .= '?'.http_build_query($filteredQuery->toArray());
}
}
return Redirect::route(
Util::getShopifyConfig('route_names.authenticate.token'),
[
'shop' => ShopDomain::fromRequest($request)->toNative(),
'target' => $target,
'host' => $request->get('host'),
'locale' => $request->get('locale'),
]
);
}
/**
* Redirect to install route.
*
* @param ShopDomainValue $shopDomain The shop domain.
*
* @return RedirectResponse
*/
protected function installRedirect(ShopDomainValue $shopDomain): RedirectResponse
{
return Redirect::route(
Util::getShopifyConfig('route_names.authenticate'),
['shop' => $shopDomain->toNative(), 'host' => request('host'), 'locale' => request('locale')]
);
}
/**
* Grab the HMAC value, if present, and how it was found.
* Order of precedence is:.
*
* - GET/POST Variable
* - Headers
* - Referer
*
* @param Request $request The request object.
*
* @return array
*/
protected function getHmacFromRequest(Request $request): array
{
// All possible methods
$options = [
// GET/POST
DataSource::INPUT()->toNative() => $request->input('hmac'),
// Headers
DataSource::HEADER()->toNative() => $request->header('X-Shop-Signature'),
// Headers: Referer
DataSource::REFERER()->toNative() => function () use ($request): ?string {
$url = parse_url($request->header('referer', ''), PHP_URL_QUERY);
parse_str($url ?? '', $refererQueryParams);
if (! $refererQueryParams || ! isset($refererQueryParams['hmac'])) {
return null;
}
return $refererQueryParams['hmac'];
},
];
// Loop through each until we find the HMAC
foreach ($options as $method => $value) {
$result = is_callable($value) ? $value() : $value;
if ($result !== null) {
return ['source' => $method, 'value' => $value];
}
}
return ['source' => null, 'value' => null];
}
/**
* Get the token from request (if available).
*
* @param Request $request The request object.
*
* @return string
*/
protected function getAccessTokenFromRequest(Request $request): ?string
{
return $this->isApiRequest($request)
? $request->bearerToken()
: $request->get('token');
}
/**
* Grab the request data.
*
* @param Request $request The request object.
* @param string $source The source of the data.
*
* @return array
*/
protected function getRequestData(Request $request, string $source): array
{
// All possible methods
$options = [
// GET/POST
DataSource::INPUT()->toNative() => function () use ($request): array {
// Verify
$verify = [];
foreach ($request->query() as $key => $value) {
$verify[$key] = $this->parseDataSourceValue($value);
}
return $verify;
},
// Headers
DataSource::HEADER()->toNative() => function () use ($request): array {
// Always present
$shop = $request->header('X-Shop-Domain');
$signature = $request->header('X-Shop-Signature');
$timestamp = $request->header('X-Shop-Time');
$verify = [
'shop' => $shop,
'hmac' => $signature,
'timestamp' => $timestamp,
];
// Sometimes present
$code = $request->header('X-Shop-Code') ?? null;
$locale = $request->header('X-Shop-Locale') ?? null;
$state = $request->header('X-Shop-State') ?? null;
$id = $request->header('X-Shop-ID') ?? null;
$ids = $request->header('X-Shop-IDs') ?? null;
foreach (compact('code', 'locale', 'state', 'id', 'ids') as $key => $value) {
if ($value) {
$verify[$key] = $this->parseDataSourceValue($value);
}
}
return $verify;
},
// Headers: Referer
DataSource::REFERER()->toNative() => function () use ($request): array {
$url = parse_url($request->header('referer'), PHP_URL_QUERY);
parse_str($url, $refererQueryParams);
// Verify
$verify = [];
foreach ($refererQueryParams as $key => $value) {
$verify[$key] = $this->parseDataSourceValue($value);
}
return $verify;
},
];
return $options[$source]();
}
/**
* Parse the data source value.
* Handle simple key/values, arrays, and nested arrays.
*
* @param mixed $value
*
* @return string
*/
protected function parseDataSourceValue($value): string
{
/**
* Format the value.
*
* @param mixed $val
*
* @return string
*/
$formatValue = function ($val): string {
return is_array($val) ? '["'.implode('", "', $val).'"]' : $val;
};
// Nested array
if (is_array($value) && is_array(current($value))) {
return implode(', ', array_map($formatValue, $value));
}
// Array or basic value
return $formatValue($value);
}
/**
* Determine if the request is AJAX or expects JSON.
*
* @param Request $request The request object.
*
* @return bool
*/
protected function isApiRequest(Request $request): bool
{
return $request->ajax() || $request->expectsJson();
}
/**
* Check if there is a store record in the database.
*
* @param Request $request The request object.
*
* @return bool
*/
protected function checkPreviousInstallation(Request $request): bool
{
$shop = $this->shopQuery->getByDomain(ShopDomain::fromRequest($request), [], true);
return $shop && $shop->password && ! $shop->trashed();
}
/**
* Get shop model if there is a store record in the database.
*
* @param Request $request The request object.
*
* @return ?ShopModel
*/
protected function getShopIfAlreadyInstalled(Request $request): ?ShopModel
{
$shop = $this->shopQuery->getByDomain(ShopDomain::fromRequest($request), [], true);
return $shop && $shop->password && ! $shop->trashed() ? $shop : null;
}
/**
* Login and validate store
*
* @param ShopModel $shop
*
* @return void
*/
protected function loginFromShop(ShopModel $shop): void
{
// Override auth guard
if (($guard = Util::getShopifyConfig('shop_auth_guard'))) {
$this->auth->setDefaultDriver($guard);
}
// All is well, login the shop
$this->auth->login($shop);
}
}