Auth0AuthenticationMiddleware::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 3
cp 0
crap 2
rs 10
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
    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