Auth0AuthenticationMiddleware   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 42
ccs 0
cts 21
cp 0
rs 10
c 0
b 0
f 0
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A handle() 0 22 4
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
    public function __construct(Auth0UserRepository $auth0Service)
20
    {
21
        $this->auth0Service = $auth0Service;
22
    }
23
24
    /**
25
     * Handle an incoming request.
26
     *
27
     * @param \Illuminate\Http\Request $request
28
     * @param \Closure                 $next
29
     *
30
     * @return mixed
31
     */
32
    public function handle(Request $request, Closure $next)
33
    {
34
        $auth0 = \App::make('auth0');
35
36
        $accessToken = $request->bearerToken();
37
38
        try {
39
            $tokenInfo = $auth0->decodeJWT($accessToken);
40
            $user = $this->auth0Service->getUserByDecodedJWT($tokenInfo);
41
42
            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
            \Auth::login($user);
47
        } catch (InvalidTokenException $e) {
48
            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
        return $next($request);
54
    }
55
}
56