Passed
Pull Request — master (#7)
by Lars
04:36
created

AuthMiddleware::retrieveAndValidateToken()   A

Complexity

Conditions 2
Paths 3

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 3
nop 1
dl 0
loc 13
ccs 0
cts 9
cp 0
crap 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace App\Http\Middleware;
4
5
6
use App\Helper\FormatHelper;
7
use Auth0\SDK\JWTVerifier;
8
use Closure;
9
use Exception;
10
use Illuminate\Http\Request;
11
12
class AuthMiddleware
13
{
14
    /**
15
     * Run the request filter.
16
     *
17
     * @param  Request $request
18
     * @param  Closure $next
19
     * @return mixed
20
     */
21
    public function handle($request, Closure $next)
22
    {
23
        $returnArray = array();
24
25
        if (!$request->hasHeader('Authorization')) {
26
            $returnArray["error-code"] = "authorization-header-not-found";
27
        }
28
29
        $token = $request->bearerToken();
30
31
        if ($request->header('Authorization') == null || $token == null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $token of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
32
            $returnArray["error-code"] = "no-token-provided";
33
        }
34
35
        if (!$this->retrieveAndValidateToken($token)) {
36
            $returnArray["error-code"] = "token-is-not-valid";
37
        }
38
39
        if (!empty($returnArray)) {
40
            return FormatHelper::formatData($returnArray, false, 401);
41
        }
42
43
        return $next($request);
44
45
    }
46
47
    /**
48
     * Check the given Token.
49
     *
50
     * @param string $token
51
     * @return bool
52
     */
53
    private function retrieveAndValidateToken($token)
54
    {
55
        try {
56
            $verifier = new JWTVerifier([
57
                'supported_algs' => ["RS256"],
58
                'valid_audiences' => [getenv("AUTH0_API_AUDIENCE")],
59
                'authorized_iss' => [getenv("AUTH0_DOMAIN")]
60
            ]);
61
62
            $verifier->verifyAndDecode($token);
63
            return true;
64
        } catch (Exception $e) {
65
            return false;
66
        }
67
    }
68
}
69