Passed
Push — master ( 660c80...17f60a )
by Arthur
08:30
created

Auth0AuthenticationMiddleware::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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