AuthenticateClient::handle()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
c 0
b 0
f 0
rs 10
cc 1
nc 1
nop 2
1
<?php
2
3
namespace Bytesfield\KeyManager\Middlewares;
4
5
use Bytesfield\KeyManager\Models\ApiCredential;
6
use Bytesfield\KeyManager\Models\Client;
7
use Closure;
8
use Illuminate\Auth\AuthenticationException;
9
use Illuminate\Http\Request;
10
11
class AuthenticateClient
12
{
13
    /**
14
     * Handle an incoming request.
15
     *
16
     * @param \Illuminate\Http\Request $request
17
     * @param \Closure $next
18
     *
19
     * @return mixed
20
     * @throws \Illuminate\Auth\AuthenticationException
21
     */
22
    public function handle(Request $request, Closure $next)
23
    {
24
        $this->authenticateClientFromRequest($request);
25
26
        return $next($request);
27
    }
28
29
    /**
30
     * Authenticate client from the request.
31
     *
32
     * @param \Illuminate\Http\Request $request
33
     *
34
     * @return \App\Models\Client
35
     * @throws \Illuminate\Auth\AuthenticationException
36
     */
37
    private function authenticateClientFromRequest(Request $request): Client
38
    {
39
        if (! $privateKey = $request->header('api-auth-key')) {
40
            throw new AuthenticationException('API key in api-auth-key header is required.');
41
        }
42
43
        if (! $apiCredential = ApiCredential::findByPrivateKey($privateKey)) {
44
            throw new AuthenticationException('Invalid API private key.');
45
        }
46
47
        if ($apiCredential->status !== ApiCredential::STATUSES['ACTIVE']) {
48
            throw new AuthenticationException('The private key is currently suspended.');
49
        }
50
51
        if ($apiCredential->client->status !== ApiCredential::STATUSES['ACTIVE']) {
52
            throw new AuthenticationException('The owner of this private key is currently suspended.');
53
        }
54
55
        return $apiCredential->client;
56
    }
57
}
58