Failed Conditions
Pull Request — master (#48)
by Chad
08:46
created

Authorization::__construct()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 2
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 Psr\Http\Message\ServerRequestInterface;
8
use Psr\Http\Message\ResponseInterface;
9
use Psr\Http\Server\MiddlewareInterface;
10
use Psr\Http\Server\RequestHandlerInterface;
11
use Interop\Container\ContainerInterface;
12
use OAuth2;
13
14
/**
15
 * Slim Middleware to handle OAuth2 Authorization.
16
 */
17
class Authorization implements MiddlewareInterface
18
{
19
    /**
20
     * OAuth2 Server
21
     *
22
     * @var OAuth2\Server
23
     */
24
    private $server;
25
26
    /**
27
     * Array of scopes required for authorization.
28
     *
29
     * @var array
30
     */
31
    private $scopes;
32
33
    /**
34
     * Container for token.
35
     *
36
     * @var ArrayAccess|ContainerInterface
37
     */
38
    private $container;
39
40
    /**
41
     * Create a new instance of the Authroization middleware.
42
     *
43
     * @param OAuth2\Server                  $server    The configured OAuth2 server.
44
     * @param ArrayAccess|ContainerInterface $container A container object in which to store the token from the
45
     *                                                  request.
46
     * @param array                          $scopes    Scopes required for authorization. $scopes can be given as an
47
     *                                                  array of arrays. OR logic will use with each grouping.
48
     *                                                  Example:
49
     *                                                  Given ['superUser', ['basicUser', 'aPermission']], the request
50
     *                                                  will be verified if the request token has 'superUser' scope
51
     *                                                  OR 'basicUser' and 'aPermission' as its scope.
52
     *
53
     * @throws \InvalidArgumentException Thrown if $container is not an instance of ArrayAccess or ContainerInterface.
54
     */
55
    public function __construct(OAuth2\Server $server, $container, array $scopes = [])
56
    {
57
        $this->server = $server;
58
        if (!is_a($container, '\\ArrayAccess') && !is_a($container, '\\Interop\\Container\\ContainerInterface')) {
59
            throw new \InvalidArgumentException(
60
                '$container does not implement \\ArrayAccess or \\Interop\\Container\\ContainerInterface'
61
            );
62
        }
63
64
        $this->container = $container;
65
        $this->scopes = $this->formatScopes($scopes);
66
    }
67
68
    /**
69
     * Execute this middleware as a function.
70
     *
71
     * @param  ServerRequestInterface $request  The PSR7 request.
72
     * @param  ResponseInterface      $response The PSR7 response.
73
     * @param  callable               $next     The Next middleware.
74
     *
75
     * @return ResponseInterface
76
     */
77
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
78
    {
79
        $handler = new class implements RequestHandlerInterface
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
Coding Style introduced by
This class is not in CamelCase format.

Classes in PHP are usually named in CamelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. The whole name starts with a capital letter as well.

Thus the name database provider becomes DatabaseProvider.

Loading history...
80
        {
81
            public $next;
82
            public $response;
83
84
            /**
85
             * Handle the request and return a response.
86
             *
87
             * @param ServerRequestInterface $request The request to handle.
88
             *
89
             * @return ResponseInterface
90
             */
91
            public function handle(ServerRequestInterface $request): ResponseInterface
92
            {
93
                return call_user_func_array($this->next, [$request, $this->response]);
94
            }
95
        };
96
97
        $handler->next = $next;
98
        $handler->response = $response;
99
100
        return $this->process($request, $handler);
101
    }
102
103
    /**
104
     * Execute this middleware.
105
     *
106
     * @param ServerRequestInterface  $request The PSR-7 request.
107
     * @param RequestHandlerInterface $handler The PSR-15 request handler.
108
     *
109
     * @return ResponseInterface
110
     */
111
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
112
    {
113
        $oauth2Request = RequestBridge::toOAuth2($request);
114
        foreach ($this->scopes as $scope) {
115
            if ($this->server->verifyResourceRequest($oauth2Request, null, $scope)) {
116
                $this->setToken($this->server->getResourceController()->getToken());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface OAuth2\Controller\ResourceControllerInterface as the method getToken() does only exist in the following implementations of said interface: OAuth2\Controller\ResourceController, OAuth2\OpenID\Controller\UserInfoController.

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...
117
                return $handler->handle($request);
118
            }
119
        }
120
121
        $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...
122
123
        if ($response->hasHeader('Content-Type')) {
124
            return $response;
125
        }
126
127
        return $response->withHeader('Content-Type', 'application/json');
128
    }
129
130
    /**
131
     * Helper method to set the token value in the container instance.
132
     *
133
     * @param array $token The token from the incoming request.
134
     *
135
     * @return void
136
     */
137
    private function setToken(array $token)
138
    {
139
        if (is_a($this->container, '\\ArrayAccess')) {
140
            $this->container['token'] = $token;
141
            return;
142
        }
143
144
        $this->container->set('token', $token);
145
    }
146
147
    /**
148
     * Returns a callable function to be used as a authorization middleware with a specified scope.
149
     *
150
     * @param array $scopes Scopes require for authorization.
151
     *
152
     * @return Authorization
153
     */
154
    public function withRequiredScope(array $scopes)
155
    {
156
        $clone = clone $this;
157
        $clone->scopes = $clone->formatScopes($scopes);
158
        return $clone;
159
    }
160
161
    /**
162
     * Helper method to ensure given scopes are formatted properly.
163
     *
164
     * @param array $scopes Scopes required for authorization.
165
     *
166
     * @return array The formatted scopes array.
167
     */
168
    private function formatScopes(array $scopes)
169
    {
170
        if (empty($scopes)) {
171
            return [null]; //use at least 1 null scope
172
        }
173
174
        array_walk(
175
            $scopes,
176
            function (&$scope) {
177
                if (is_array($scope)) {
178
                    $scope = implode(' ', $scope);
179
                }
180
            }
181
        );
182
183
        return $scopes;
184
    }
185
}
186