Completed
Pull Request — master (#48)
by Chad
06:03
created

Authorization::setToken()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
namespace Chadicus\Slim\OAuth2\Middleware;
3
4
use Chadicus\Slim\OAuth2\Http\RequestBridge;
5
use Chadicus\Slim\OAuth2\Http\ResponseBridge;
6
use Psr\Http\Message\ServerRequestInterface;
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Server\MiddlewareInterface;
9
use Psr\Http\Server\RequestHandlerInterface;
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
     * Create a new instance of the Authroization middleware.
33
     *
34
     * @param OAuth2\Server $server The configured OAuth2 server.
35
     * @param array         $scopes Scopes required for authorization. $scopes can be given as an array of arrays.
36
     *                              OR logic will use with each grouping.
37
     *                              Example: Given ['superUser', ['basicUser', 'aPermission']], the request will be
38
     *                              verified if the request token has 'superUser' scope OR 'basicUser' and
39
     *                              'aPermission' as its scope.
40
     */
41
    public function __construct(OAuth2\Server $server, array $scopes = [])
42
    {
43
        $this->server = $server;
44
        $this->scopes = $this->formatScopes($scopes);
45
    }
46
47
    /**
48
     * Execute this middleware as a function.
49
     *
50
     * @param  ServerRequestInterface $request  The PSR7 request.
51
     * @param  ResponseInterface      $response The PSR7 response.
52
     * @param  callable               $next     The Next middleware.
53
     *
54
     * @return ResponseInterface
55
     */
56
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
57
    {
58
        $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...
59
        {
60
            public $next;
61
            public $response;
62
63
            /**
64
             * Handle the request and return a response.
65
             *
66
             * @param ServerRequestInterface $request The request to handle.
67
             *
68
             * @return ResponseInterface
69
             */
70
            public function handle(ServerRequestInterface $request): ResponseInterface
71
            {
72
                return call_user_func_array($this->next, [$request, $this->response]);
73
            }
74
        };
75
76
        $handler->next = $next;
77
        $handler->response = $response;
78
79
        return $this->process($request, $handler);
80
    }
81
82
    /**
83
     * Execute this middleware.
84
     *
85
     * @param ServerRequestInterface  $request The PSR-7 request.
86
     * @param RequestHandlerInterface $handler The PSR-15 request handler.
87
     *
88
     * @return ResponseInterface
89
     */
90
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
91
    {
92
        $oauth2Request = RequestBridge::toOAuth2($request);
93
        foreach ($this->scopes as $scope) {
94
            if ($this->server->verifyResourceRequest($oauth2Request, null, $scope)) {
95
                $token = $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...
96
                return $handler->handle($request->withAttribute('oauth2-token', $token));
97
            }
98
        }
99
100
        $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...
101
102
        if ($response->hasHeader('Content-Type')) {
103
            return $response;
104
        }
105
106
        return $response->withHeader('Content-Type', 'application/json');
107
    }
108
109
    /**
110
     * Returns a callable function to be used as a authorization middleware with a specified scope.
111
     *
112
     * @param array $scopes Scopes require for authorization.
113
     *
114
     * @return Authorization
115
     */
116
    public function withRequiredScope(array $scopes)
117
    {
118
        $clone = clone $this;
119
        $clone->scopes = $clone->formatScopes($scopes);
120
        return $clone;
121
    }
122
123
    /**
124
     * Helper method to ensure given scopes are formatted properly.
125
     *
126
     * @param array $scopes Scopes required for authorization.
127
     *
128
     * @return array The formatted scopes array.
129
     */
130
    private function formatScopes(array $scopes)
131
    {
132
        if (empty($scopes)) {
133
            return [null]; //use at least 1 null scope
134
        }
135
136
        array_walk(
137
            $scopes,
138
            function (&$scope) {
139
                if (is_array($scope)) {
140
                    $scope = implode(' ', $scope);
141
                }
142
            }
143
        );
144
145
        return $scopes;
146
    }
147
}
148