Passed
Branch feature/add-webhook-services (535460)
by Eudald
02:00
created

VerifySignature::isValid()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 10
nc 6
nop 3
dl 0
loc 17
rs 9.9332
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: eudaldarranztresserra
5
 * Date: 2019-03-01
6
 * Time: 13:06
7
 */
8
9
namespace Nestednet\Gocardless\Middlewares;
10
11
use Closure;
12
use Exception;
13
use GoCardlessPro\Webhook;
14
use Nestednet\Gocardless\Exceptions\WebhookFailed;
15
16
class VerifySignature
17
{
18
    public function handle($request, Closure $next)
19
    {
20
        $signature = $request->header('Webhook-Signature');
21
22
        if (! $signature) {
23
            throw WebhookFailed::missingSignature();
24
        }
25
26
        if (! $this->isValid($signature, $request->getContent(), $request->route('configKey'))) {
27
            throw WebhookFailed::invalidSignature($signature);
28
        }
29
30
        return $next($request);
31
    }
32
33
    protected function isValid(string $signature, string $payload, string $configKey = null) : bool
34
    {
35
        $secret = ($configKey) ?
36
            config('gocardless.webhooks.webhook_endpoint_secret_'.$configKey) :
0 ignored issues
show
Bug introduced by
The function config was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

36
            /** @scrutinizer ignore-call */ 
37
            config('gocardless.webhooks.webhook_endpoint_secret_'.$configKey) :
Loading history...
37
            config('gocardless.webhooks.webhook_endpoint_secret');
38
39
        if (empty($secret)) {
40
            throw WebhookFailed::noSecretKeyProvided();
41
        }
42
43
        try {
44
            Webhook::parse($payload, $signature, $secret);
45
        } catch (Exception $e) {
46
            return false;
47
        }
48
49
        return true;
50
    }
51
52
}