Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
AuthorizeApiKey
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 2
12
0.00% covered (danger)
0.00%
0 / 1
 handle
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 logAccessEvent
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2
3namespace Ejarnutowski\LaravelApiKey\Http\Middleware;
4
5use Closure;
6use Ejarnutowski\LaravelApiKey\Models\ApiKey;
7use Ejarnutowski\LaravelApiKey\Models\ApiKeyAccessEvent;
8use Illuminate\Http\Request;
9
10class AuthorizeApiKey
11{
12    const AUTH_HEADER = 'X-Authorization';
13
14    /**
15     * Handle the incoming request
16     *
17     * @param Request $request
18     * @param Closure $next
19     * @return \Illuminate\Contracts\Routing\ResponseFactory|mixed|\Symfony\Component\HttpFoundation\Response
20     */
21    public function handle(Request $request, Closure $next)
22    {
23        $header = $request->header(self::AUTH_HEADER);
24        $apiKey = ApiKey::getByKey($header);
25
26        if ($apiKey instanceof ApiKey) { // @phpstan-ignore-line
27            $this->logAccessEvent($request, $apiKey);
28            return $next($request);
29        }
30
31        return response([
32            'errors' => [[
33                'message' => 'Unauthorized'
34            ]]
35        ], 401);
36    }
37
38    /**
39     * Log an API key access event
40     *
41     * @param Request $request
42     * @param ApiKey  $apiKey
43     */
44    protected function logAccessEvent(Request $request, ApiKey $apiKey) // @phpstan-ignore-line
45    {
46        $event = new ApiKeyAccessEvent;
47        $event->api_key_id = $apiKey->id;
48        $event->ip_address = $request->ip();
49        $event->url        = $request->fullUrl();
50        $event->save();
51    }
52}