Passed
Push — master ( 9a4391...fe7f4e )
by Dan Michael O.
03:45
created

WebhooksController   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 106
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 52
dl 0
loc 106
rs 10
c 0
b 0
f 0
wmc 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A handle() 0 25 3
B handleUserUpdate() 0 49 6
A challenge() 0 4 1
1
<?php
2
3
namespace App\Http\Controllers;
4
5
use App\User;
6
use Illuminate\Http\Request;
0 ignored issues
show
Bug introduced by
The type Illuminate\Http\Request was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use Illuminate\Http\Response;
0 ignored issues
show
Bug introduced by
The type Illuminate\Http\Response was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use Scriptotek\Alma\Client;
0 ignored issues
show
Bug introduced by
The type Scriptotek\Alma\Client was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
9
10
class WebhooksController extends Controller
11
{
12
    /**
13
     * Alma webhooks challenge handler.
14
     *
15
     * @param Request $request
16
     * @return Response
17
     */
18
    public function challenge(Request $request)
19
    {
20
        return response()->json([
0 ignored issues
show
Bug introduced by
The function response 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

20
        return /** @scrutinizer ignore-call */ response()->json([
Loading history...
21
            'challenge' => $request->query('challenge'),
22
        ]);
23
    }
24
25
    /**
26
     * Alma webhooks router.
27
     *
28
     * @param Client $almaClient
29
     * @param Request $request
30
     * @return Response
31
     */
32
    public function handle(Client $almaClient, Request $request)
33
    {
34
        $secret = config('services.alma.webhook_secret');
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

34
        $secret = /** @scrutinizer ignore-call */ config('services.alma.webhook_secret');
Loading history...
35
        $eventType = $request->input('action');
36
        $hash = $request->header('X-Exl-Signature');
37
38
        $expectedHash = base64_encode(
39
            hash_hmac('sha256', $request->getContent(), $secret, true)
40
        );
41
42
        if (!hash_equals($hash, $expectedHash)) {
43
            \Log::warning(
44
                "Ignoring Alma '{$eventType}' event due to invalid signature. " .
45
                "Expected '{$expectedHash}', got '{$hash}'."
46
            );
47
48
            return response()->json(['errorMessage' => 'Invalid Signature'], 401);
0 ignored issues
show
Bug introduced by
The function response 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

48
            return /** @scrutinizer ignore-call */ response()->json(['errorMessage' => 'Invalid Signature'], 401);
Loading history...
49
        }
50
51
        switch ($eventType) {
52
            case 'USER':
53
                return $this->handleUserUpdate($almaClient, $request);
54
55
            default:
56
                return response('No handler for this webhook event type.', 202);
57
        }
58
    }
59
60
    /**
61
     * Handler for the Alma user webhook.
62
     *
63
     * @param Client $almaClient
64
     * @param Request $request
65
     * @return Response
66
     */
67
    protected function handleUserUpdate(Client $almaClient, Request $request)
68
    {
69
        $data = $request->input('webhook_user');
70
        $primaryId = array_get($data, 'user.primary_id');
0 ignored issues
show
Bug introduced by
The function array_get 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

70
        $primaryId = /** @scrutinizer ignore-call */ array_get($data, 'user.primary_id');
Loading history...
71
72
        if ($data['method'] == 'UPDATE') {
73
            $almaClientUser = \Scriptotek\Alma\Users\User::make($almaClient, $primaryId)
0 ignored issues
show
Bug introduced by
The type Scriptotek\Alma\Users\User was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
74
                ->init(json_decode(json_encode($data['user'])));
75
76
            $almaUser = new \App\Alma\User($almaClientUser);
77
78
            $localUser = User::where('alma_primary_id', '=', $primaryId)
79
                ->orWhere('university_id', '=', $almaUser->getUniversityId())
80
                ->first();
81
82
            if (is_null($localUser)) {
83
                \Log::debug('Ignorerer Alma-brukeroppdateringsvarsel for bruker som ikke er i Bibrex.');
84
            } else {
85
                $localUser->mergeFromAlmaResponse($almaUser);
86
                if ($localUser->isDirty()) {
87
                    $localUser->save();
88
                    \Log::info(sprintf(
89
                        'Varsel fra Alma om at brukeren <a href="%s">%s</a> har blitt oppdatert.',
90
                        action('UsersController@getShow', $localUser->id),
0 ignored issues
show
Bug introduced by
The function action 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

90
                        /** @scrutinizer ignore-call */ 
91
                        action('UsersController@getShow', $localUser->id),
Loading history...
91
                        $localUser->name,
92
                        $data['cause'],
93
                        $data['method']
94
                    ));
95
                } else {
96
                    \Log::debug(
97
                        'Varsel fra Alma førte ikke til noen endringer på den tilknyttede Bibrex-brukeren.'
98
                    );
99
                }
100
            }
101
        } elseif ($data['method'] == 'DELETE') {
102
            $localUser = User::where('alma_primary_id', '=', $primaryId)->first();
103
            if (is_null($localUser)) {
104
                \Log::debug('Ignorerer Alma-brukeroppdateringsvarsel for bruker som ikke er i Bibrex.');
105
            } else {
106
                \Log::info(sprintf(
107
                    'Varsel fra Alma om at brukeren <a href="%s">%s</a> har blitt slettet.',
108
                    action('UsersController@getShow', $localUser->id),
109
                    $localUser->name
110
                ));
111
            }
112
        }
113
114
        // Say yo to Alma
115
        return response('Yo!', 200);
0 ignored issues
show
Bug introduced by
The function response 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

115
        return /** @scrutinizer ignore-call */ response('Yo!', 200);
Loading history...
116
    }
117
}
118