Completed
Push — master ( e2d8b6...aa5383 )
by Chad
9s
created

Authorization::__invoke()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.2
c 0
b 0
f 0
cc 4
eloc 10
nc 5
nop 3
1
<?php
2
namespace Chadicus\Slim\OAuth2\Middleware;
3
4
use ArrayAccess;
5
use Chadicus\Slim\OAuth2\Http\RequestBridge;
6
use Chadicus\Slim\OAuth2\Http\ResponseBridge;
7
use Chadicus\Psr\Middleware\MiddlewareInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Http\Message\ResponseInterface;
10
use OAuth2;
11
12
/**
13
 * Slim Middleware to handle OAuth2 Authorization.
14
 */
15
class Authorization implements MiddlewareInterface
16
{
17
    /**
18
     * OAuth2 Server
19
     *
20
     * @var OAuth2\Server
21
     */
22
    private $server;
23
24
    /**
25
     * Array of scopes required for authorization.
26
     *
27
     * @var array
28
     */
29
    private $scopes;
30
31
    /**
32
     * Container for token.
33
     *
34
     * @var ArrayAccess|ContainerInterface
35
     */
36
    private $container;
37
38
    /**
39
     * Create a new instance of the Authroization middleware.
40
     *
41
     * @param OAuth2\Server $server          The configured OAuth2 server.
0 ignored issues
show
Coding Style introduced by
Expected 18 spaces after parameter type; 1 found
Loading history...
Coding Style introduced by
Expected 4 spaces after parameter name; 10 found
Loading history...
42
     * @param ArrayAccess|ContainerInterface $container A container object in which to store the token from the request.
43
     * @param array         $scopes          Scopes required for authorization. $scopes can be given as an array of
0 ignored issues
show
Coding Style introduced by
Expected 26 spaces after parameter type; 9 found
Loading history...
Coding Style introduced by
Expected 4 spaces after parameter name; 10 found
Loading history...
44
     *                                       arrays. OR logic will use with each grouping.
45
     *                                       Example:
46
     *                                       Given ['superUser', ['basicUser', 'aPermission']], the request will be
47
     *                                       verified if the request token has 'superUser' scope OR 'basicUser' and
48
     *                                       'aPermission' as its scope.
49
     *
50
     * @throws \InvalidArgumentException Thrown if $container is not an instance of ArrayAccess or ContainerInterface.
51
     */
52
    public function __construct(OAuth2\Server $server, $container, array $scopes = [])
53
    {
54
        $this->server = $server;
55
        if (!is_a($container, '\\ArrayAccess') && !is_a($container, '\\Interop\\Container\\ContainerInterface')) {
56
            throw new \InvalidArgumentException(
57
                '$container does not implement \\ArrayAccess or \\Interop\\Container\\ContainerInterface'
58
            );
59
        }
60
61
        $this->container = $container;
62
        $this->scopes = $this->formatScopes($scopes);
63
    }
64
65
    /**
66
     * Execute this middleware.
67
     *
68
     * @param  ServerRequestInterface $request  The PSR7 request.
69
     * @param  ResponseInterface      $response The PSR7 response.
70
     * @param  callable               $next     The Next middleware.
71
     *
72
     * @return ResponseInterface
73
     */
74
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
75
    {
76
        $oauth2Request = RequestBridge::toOAuth2($request);
77
        foreach ($this->scopes as $scope) {
78
            if ($this->server->verifyResourceRequest($oauth2Request, null, $scope)) {
79
                $this->setToken($this->server->getResourceController()->getToken());
80
                return $next($request, $response);
81
            }
82
        }
83
84
        $response = ResponseBridge::fromOAuth2($this->server->getResponse());
0 ignored issues
show
Compatibility introduced by
$this->server->getResponse() of type object<OAuth2\ResponseInterface> is not a sub-type of object<OAuth2\Response>. It seems like you assume a concrete implementation of the interface OAuth2\ResponseInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
85
86
        if ($response->hasHeader('Content-Type')) {
87
            return $response;
88
        }
89
90
        return $response->withHeader('Content-Type', 'application/json');
91
    }
92
93
    /**
94
     * Helper method to set the token value in the container instance.
95
     *
96
     * @param array $token The token from the incoming request.
97
     *
98
     * @return void
99
     */
100
    private function setToken(array $token)
101
    {
102
        if (is_a($this->container, '\\ArrayAccess')) {
103
            $this->container['token'] = $token;
104
            return;
105
        }
106
107
       $this->container->set('token', $token);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface ArrayAccess as the method set() does only exist in the following implementations of said interface: Guzzle\Common\Collection, Guzzle\Http\QueryString, Guzzle\Service\Builder\ServiceBuilder, Guzzle\Service\Command\AbstractCommand, Guzzle\Service\Command\ClosureCommand, Guzzle\Service\Command\OperationCommand, Guzzle\Service\Resource\Model, Guzzle\Tests\Service\Mock\Command\IterableCommand, Guzzle\Tests\Service\Mock\Command\MockCommand, Guzzle\Tests\Service\Mock\Command\OtherCommand, Guzzle\Tests\Service\Mock\Command\Sub\Sub, HttpQueryString.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
108
    }
109
110
    /**
111
     * Returns a callable function to be used as a authorization middleware with a specified scope.
112
     *
113
     * @param array $scopes Scopes require for authorization.
114
     *
115
     * @return Authorization
116
     */
117
    public function withRequiredScope(array $scopes)
118
    {
119
        $clone = clone $this;
120
        $clone->scopes = $clone->formatScopes($scopes);
121
        return $clone;
122
    }
123
124
    /**
125
     * Helper method to ensure given scopes are formatted properly.
126
     *
127
     * @param array $scopes Scopes required for authorization.
128
     *
129
     * @return array The formatted scopes array.
130
     */
131
    private function formatScopes(array $scopes)
132
    {
133
        if (empty($scopes)) {
134
            return [null]; //use at least 1 null scope
135
        }
136
137
        array_walk(
138
            $scopes,
139
            function (&$scope) {
140
                if (is_array($scope)) {
141
                    $scope = implode(' ', $scope);
142
                }
143
            }
144
        );
145
146
        return $scopes;
147
    }
148
}
149