Test Failed
Push — new-feature-manage-tokens ( 089f0c...266329 )
by Samuel
02:59
created

MultiAuthenticate::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 3
dl 0
loc 9
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SMartins\PassportMultiauth\Http\Middleware;
4
5
use Closure;
6
use League\OAuth2\Server\ResourceServer;
7
use Illuminate\Auth\AuthenticationException;
8
use Illuminate\Auth\Middleware\Authenticate;
9
use Illuminate\Contracts\Auth\Authenticatable;
10
use Illuminate\Contracts\Auth\Factory as Auth;
11
use SMartins\PassportMultiauth\Config\AuthConfigHelper;
12
use SMartins\PassportMultiauth\PassportMultiauth;
13
use SMartins\PassportMultiauth\Provider as Token;
14
use SMartins\PassportMultiauth\ProviderRepository;
15
use SMartins\PassportMultiauth\Guards\GuardChecker;
16
use SMartins\PassportMultiauth\Facades\ServerRequest;
17
use League\OAuth2\Server\Exception\OAuthServerException;
18
19
class MultiAuthenticate extends Authenticate
20
{
21
    /**
22
     * @var \League\OAuth2\Server\ResourceServer
23
     */
24
    protected $server;
25
26
    /**
27
     * @var \SMartins\PassportMultiauth\ProviderRepository
28
     */
29
    protected $providers;
30
31
    /**
32
     * Create a new middleware instance.
33
     *
34
     * @param ResourceServer $server
35
     * @param ProviderRepository $providers
36
     * @param Auth $auth
37
     */
38 13
    public function __construct(
39
        ResourceServer $server,
40
        ProviderRepository $providers,
41
        Auth $auth
42
    ) {
43 13
        parent::__construct($auth);
44
45 13
        $this->server = $server;
46 13
        $this->providers = $providers;
47 13
    }
48
49
    /**
50
     * Handle an incoming request. Authenticates the guard from access token
51
     * used on request.
52
     *
53
     * @param \Illuminate\Http\Request $request
54
     * @param \Closure                 $next
55
     * @param string[]                 ...$guards
56
     * @return mixed
57
     *
58
     * @throws \Illuminate\Auth\AuthenticationException
59
     */
60 13
    public function handle($request, Closure $next, ...$guards)
61
    {
62
        // If don't has any guard follow the flow
63 13
        if (empty($guards)) {
64 2
            $this->authenticate($guards);
65
66
            // Stop laravel from checking for a token if session is not set
67
            return $next($request);
68
        }
69
70 11
        $psrRequest = ServerRequest::createRequest($request);
0 ignored issues
show
Bug Best Practice introduced by
The method SMartins\PassportMultiau...equest::createRequest() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

70
        /** @scrutinizer ignore-call */ 
71
        $psrRequest = ServerRequest::createRequest($request);
Loading history...
71
72
        try {
73 11
            $psrRequest = $this->server->validateAuthenticatedRequest($psrRequest);
74
75 4
            if (! $tokenId = $psrRequest->getAttribute('oauth_access_token_id')) {
76 1
                throw new AuthenticationException('Unauthenticated', $guards);
77
            }
78
79 3
            if (! $accessToken = $this->providers->findForToken($tokenId)) {
80 1
                throw new AuthenticationException('Unauthenticated', $guards);
81
            }
82
83 2
            $this->authenticateTokenGuard($accessToken, $guards);
84 10
        } catch (OAuthServerException $e) {
85
            // If has an OAuthServerException check if has unit tests and fake
86
            // user authenticated.
87 7
            if ($user = PassportMultiauth::userActing()) {
88 6
                if ($this->canBeAuthenticated($user, $guards)) {
89 4
                    return $next($request);
90
                }
91
            }
92
93
            // @todo Check if it's the best way to handle with OAuthServerException
94 3
            throw new AuthenticationException('Unauthenticated', $guards);
95
        }
96
97 1
        return $next($request);
98
    }
99
100
    /**
101
     * Check if user acting has the required guards and scopes on request.
102
     *
103
     * @param Authenticatable $user
104
     * @param  array $guards
105
     * @return bool
106
     */
107 6
    public function canBeAuthenticated(Authenticatable $user, $guards)
108
    {
109 6
        $userGuard = AuthConfigHelper::getUserGuard($user);
110
111 6
        return in_array($userGuard, $guards);
112
    }
113
114
    /**
115
     * Authenticate correct guard based on token.
116
     *
117
     * @param \SMartins\PassportMultiauth\Provider $token
118
     * @param  array $guards
119
     * @return void
120
     *
121
     * @throws \Illuminate\Auth\AuthenticationException
122
     */
123 2
    public function authenticateTokenGuard(Token $token, $guards)
124
    {
125 2
        $providers = GuardChecker::getGuardsProviders($guards);
126
127
        // use only guard associated to access token provider
128 2
        $authGuards = $providers->has($token->provider) ? [$providers->get($token->provider)] : [];
129
130 2
        $this->authenticate($authGuards);
131 1
    }
132
}
133