Passed
Push — master ( b4b8e8...3089dd )
by Arthur
26:17 queued 02:28
created

Auth0AuthenticationMiddleware::handle()   A

Complexity

Conditions 4
Paths 10

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4.1967

Importance

Changes 0
Metric Value
cc 4
eloc 13
nc 10
nop 2
dl 0
loc 22
ccs 10
cts 13
cp 0.7692
crap 4.1967
rs 9.8333
c 0
b 0
f 0
1
<?php
2
3
namespace Modules\Auth0\Middleware;
4
5
use Auth0\Login\Contract\Auth0UserRepository;
6
use Auth0\SDK\Exception\CoreException;
7
use Auth0\SDK\Exception\InvalidTokenException;
8
use Closure;
9
use Foundation\Abstracts\Middleware\Middleware;
10
use Illuminate\Http\Request;
11
12
class Auth0AuthenticationMiddleware extends Middleware
13
{
14
    protected $auth0Service;
15
16
    /**
17
     * Auth0AuthenticationMiddleware constructor.
18
     */
19 52
    public function __construct(Auth0UserRepository $auth0Service)
20
    {
21 52
        $this->auth0Service = $auth0Service;
22 52
    }
23
24
    /**
25
     * Handle an incoming request.
26
     *
27
     * @param \Illuminate\Http\Request $request
28
     * @param \Closure                 $next
29
     *
30
     * @return mixed
31
     */
32 52
    public function handle(Request $request, Closure $next)
33
    {
34 52
        $auth0 = \App::make('auth0');
35
36 52
        $accessToken = $request->bearerToken();
37
38
        try {
39 52
            $tokenInfo = $auth0->decodeJWT($accessToken);
40 51
            $user = $this->auth0Service->getUserByDecodedJWT($tokenInfo);
41
42 51
            if (! $user) {
0 ignored issues
show
introduced by
$user is of type Illuminate\Contracts\Auth\Authenticatable, thus it always evaluated to true.
Loading history...
43
                return response()->json(['error' => 'Unauthorized user.'], 401);
44
            }
45
46 51
            \Auth::login($user);
47 1
        } catch (InvalidTokenException $e) {
48 1
            return response()->json(['error' => 'Invalid or no token set.'], 401);
49
        } catch (CoreException $e) {
50
            return response()->json(['error' => $e->getMessage()], 401);
51
        }
52
53 51
        return $next($request);
54
    }
55
}
56