Completed
Push — master ( d874fd...3a6bc2 )
by Conrad
01:56
created

src/Services/AuthenticationService.php (2 issues)

Labels
Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace AdvancedLearning\Oauth2Server\Services;
4
5
6
use AdvancedLearning\Oauth2Server\Exceptions\AuthenticationException;
7
use AdvancedLearning\Oauth2Server\Repositories\AccessTokenRepository;
8
use GuzzleHttp\Psr7\Response;
9
use League\OAuth2\Server\Exception\OAuthServerException;
10
use League\OAuth2\Server\ResourceServer;
11
use Robbie\Psr7\HttpRequestAdapter;
12
use Robbie\Psr7\HttpResponseAdapter;
13
use SilverStripe\Control\HTTPRequest;
14
use SilverStripe\Core\Environment;
15
16
class AuthenticationService implements Authenticator
17
{
18
    protected $server;
19
20
    /**
21
     * AuthenticationService constructor.
22
     *
23
     * @param ResourceServer|null $server Optional resource server.
24
     */
25
    public function __construct(ResourceServer $server = null)
26
    {
27
        $this->server = $server ?: $this->createServer();
28
    }
29
30
    /**
31
     * Authenticate the request. Adds oauth fields as headers on the request.
32
     *
33
     * @param HTTPRequest $request The SilverStripe request object to be authenticated.
34
     *
35
     * @return HTTPRequest
36
     * @throws AuthenticationException
37
     */
38
    public function authenticate(HTTPRequest $request): HTTPRequest
39
    {
40
        $requestAdapter = new HttpRequestAdapter();
41
        $responseAdapter = new HttpResponseAdapter();
42
43
        // missing vars (cli)
44
        $this->addMissingServerVariables($requestAdapter);
45
46
        $server = $this->getServer();
47
        $psrRequest = $requestAdapter->toPsr7($request);
48
        $psrResponse = new Response();
49
50
        try {
51
            $psrRequest = $server->validateAuthenticatedRequest($psrRequest);
52
        } catch (OAuthServerException $exception) {
53
            // convert to authentication exception
54
            throw new AuthenticationException(
55
                $exception->getMessage(),
56
                $exception->getCode(),
57
                $responseAdapter->fromPsr7($exception->generateHttpResponse($psrResponse))
0 ignored issues
show
It seems like $responseAdapter->fromPs...Response($psrResponse)) targeting Robbie\Psr7\HttpResponseAdapter::fromPsr7() can also be of type object<SilverStripe\Control\HTTPRequest>; however, AdvancedLearning\Oauth2S...xception::__construct() does only seem to accept object<SilverStripe\Control\HTTPResponse>, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
58
            );
59
        } catch (\Exception $exception) {
60
            // convert to authentication exception
61
            throw new AuthenticationException(
62
                $exception->getMessage(),
63
                $exception->getCode(),
64
                $responseAdapter->fromPsr7(
0 ignored issues
show
It seems like $responseAdapter->fromPs...Response($psrResponse)) targeting Robbie\Psr7\HttpResponseAdapter::fromPsr7() can also be of type object<SilverStripe\Control\HTTPRequest>; however, AdvancedLearning\Oauth2S...xception::__construct() does only seem to accept object<SilverStripe\Control\HTTPResponse>, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
65
                    (new OAuthServerException($exception->getMessage(), 0, 'unknown_error', 500))
66
                        ->generateHttpResponse($psrResponse)
67
                )
68
            );
69
        }
70
        // add the request attributes as custom auth headers
71
        foreach ($psrRequest->getAttributes() as $attribute => $value) {
72
            $request->addHeader($attribute, $value);
73
        }
74
75
        return $request;
76
    }
77
78
    /**
79
     * Override the default ResourceServer.
80
     *
81
     * @param ResourceServer $v The new ResourceServer to use.
82
     *
83
     * @return $this
84
     */
85
    public function setServer(ResourceServer $v): Authenticator
86
    {
87
        $this->server = $v;
88
        return $this;
89
    }
90
91
    /**
92
     * Get the ResourceServer.
93
     *
94
     * @return ResourceServer
95
     */
96
    public function getServer(): ResourceServer
97
    {
98
        return $this->server;
99
    }
100
101
    /**
102
     * Create a default ResourceServer. Used if one isn't provided.
103
     *
104
     * @return ResourceServer
105
     */
106
    protected function createServer(): ResourceServer
107
    {
108
        // Init our repositories
109
        $accessTokenRepository = new AccessTokenRepository(); // instance of AccessTokenRepositoryInterface
110
111
        // Path to authorization server's public key
112
        $publicKeyPath = Environment::getEnv('OAUTH_PUBLIC_KEY_PATH');
113
114
        // Setup the authorization server
115
        return new ResourceServer(
116
            $accessTokenRepository,
117
            $publicKeyPath
118
        );
119
    }
120
121
    /**
122
     * Cli is missing some $_SERVER variables.
123
     *
124
     * @param HttpRequestAdapter $adapter
125
     */
126
    protected function addMissingServerVariables(HttpRequestAdapter $adapter)
127
    {
128
        $vars = $adapter->getServerVars() ?: [];
129
        $defaults = [
130
            'SERVER_PORT' => 80,
131
            'HTTP_HOST' => Environment::getEnv('SS_BASE_URL')
132
        ];
133
134
        foreach ($defaults as $key => $value) {
135
            if (empty($vars[$key])) {
136
                $vars[$key] = $value;
137
            }
138
        }
139
140
        $adapter->setServerVars($vars);
141
    }
142
}
143