OAuthServerController::init()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 36
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 24
nc 1
nop 0
dl 0
loc 36
ccs 25
cts 25
cp 1
crap 1
rs 9.536
c 0
b 0
f 0
1
<?php
2
3
namespace App\Controller;
4
5
use DateInterval;
6
use Del\Common\ContainerService;
7
use Del\Form\Field\Radio;
8
use Del\Form\Field\Submit;
9
use Del\Form\Form;
10
use Exception;
11
use League\OAuth2\Server\AuthorizationServer;
12
use League\OAuth2\Server\Exception\OAuthServerException;
13
use League\OAuth2\Server\Grant\AuthCodeGrant;
14
use League\OAuth2\Server\Grant\ClientCredentialsGrant;
15
use League\OAuth2\Server\Grant\RefreshTokenGrant;
16
use OAuth\OAuthUser;
17
use Zend\Diactoros\Response;
18
use Zend\Diactoros\Stream;
19
20
class OAuthServerController extends BaseController
21
{
22
    /** @var AuthorizationServer $oauth2Server */
23
    protected $oauth2Server;
24
25
    /**
26
     * @throws \Exception
27
     */
28 7
    public function init()
29
    {
30 7
        $container = ContainerService::getInstance()->getContainer();
31 7
        $clientRepository = $container['repository.Client'];
32 7
        $accessTokenRepository = $container['repository.AccessToken'];
33 7
        $scopeRepository = $container['repository.Scope'];
34 7
        $authCodeRepository = $container['repository.AuthCode'];
35 7
        $refreshTokenRepository = $container['repository.RefreshToken'];
36
37
        // Setup the authorization server
38 7
        $server = new AuthorizationServer($clientRepository, $accessTokenRepository, $scopeRepository,
39 7
            'file://'.APPLICATION_PATH.'/data/keys/private.key',    // path to private key
40 7
            'file://'.APPLICATION_PATH.'/data/keys/public.key'      // path to public key
41
        );
42
43 7
        $this->oauth2Server = $server;
44
45 7
        $this->oauth2Server->enableGrantType(
46 7
            new ClientCredentialsGrant(),
47 7
            new DateInterval('PT1H')
48
        );
49
50 7
        $this->oauth2Server->enableGrantType(
51 7
            new AuthCodeGrant(
52 7
                $authCodeRepository,
53 7
                $refreshTokenRepository,
54 7
                new DateInterval('PT10M')
55
            ),
56 7
            new DateInterval('PT1H')
57
        );
58
59 7
        $refreshGrant = new RefreshTokenGrant($refreshTokenRepository);
60 7
        $refreshGrant->setRefreshTokenTTL(new DateInterval('PT1M'));
61 7
        $this->oauth2Server->enableGrantType(
62 7
            $refreshGrant,
63 7
            new DateInterval('PT1H')
64
        );
65 7
    }
66
67
    /**
68
     *
69
     * @OA\Get(
70
     *     path="/oauth2/authorize",
71
     *     @OA\Response(response="200", description="An access token"),
72
     *     tags={"auth"},
73
     *     @OA\Parameter(
74
     *         name="response_type",
75
     *         in="query",
76
     *         type="string",
77
     *         description="the type of response",
78
     *         required=true,
79
     *         default="code"
80
     *     ),
81
     *     @OA\Parameter(
82
     *         name="client_id",
83
     *         in="query",
84
     *         type="string",
85
     *         description="the client identifier",
86
     *         required=true,
87
     *         default="testclient"
88
     *     ),
89
     *     @OA\Parameter(
90
     *         name="client_secret",
91
     *         in="query",
92
     *         type="string",
93
     *         description="the client identifier",
94
     *         required=false,
95
     *         default="testclient"
96
     *     ),
97
     *     @OA\Parameter(
98
     *         name="redirect_uri",
99
     *         in="query",
100
     *         type="string",
101
     *         description="where to send the response",
102
     *         required=false
103
     *     ),
104
     *     @OA\Parameter(
105
     *         name="state",
106
     *         in="query",
107
     *         type="string",
108
     *         description="with a CSRF token. This parameter is optional but highly recommended.",
109
     *         required=false,
110
     *     ),
111
     *     @OA\Parameter(
112
     *         name="scope",
113
     *         in="query",
114
     *         type="string",
115
     *         description="allowed scopes, space separated",
116
     *         required=false,
117
     *     )
118
     * )
119
     */
120 1
    public function authorizeAction()
121
    {
122
        /* @var AuthorizationServer $server */
123 1
        $server = $this->oauth2Server;
124
125 1
        $request = $this->getRequest();
126 1
        $response = new Response();
127
128
        try {
129
            // Validate the HTTP request and return an AuthorizationRequest object.
130
            // The auth request object can be serialized into a user's session
131 1
            $authRequest = $server->validateAuthorizationRequest($request);
132
            // Once the user has logged in set the user on the AuthorizationRequest
133 1
            $authRequest->setUser(new OAuthUser());
134
            // Once the user has approved or denied the client update the status
135
            // (true = approved, false = denied)
136 1
            $authRequest->setAuthorizationApproved(true);
137
            // Return the HTTP redirect response
138 1
            $response = $server->completeAuthorizationRequest($authRequest, $response);
139
140
        } catch (OAuthServerException $e) {
141
            $response = $e->generateHttpResponse($response);
142
143
        } catch (Exception $e) {
144
            $body = new Stream('php://temp', 'r+');
145
            $body->write($e->getMessage());
146
            $response = $response->withStatus(500)->withBody($body);
147
        }
148
149 1
        $redirectUri = $response->getHeader('Location');
150 1
        if (!empty($redirectUri)) {
151 1
            if (\substr($redirectUri[0], 0, 1) == '?') {
152
                $uri = \str_replace('?', '', $redirectUri[0]);
153
                \parse_str($uri, $vars);
154
                $this->sendJsonResponse($vars);
155
            }
156
        } else {
157
            $this->sendResponse($response);
158
        }
159
160 1
        return $response;
161
    }
162
163
    /**
164
     * @OA\Post(
165
     *     path="/oauth2/access-token",
166
     *     operationId="accessToken",
167
     *     @OA\Response(response="200", description="An access token"),
168
     *     tags={"auth"},
169
     *     @OA\Parameter(
170
     *         name="grant_type",
171
     *         in="formData",
172
     *         type="string",
173
     *         description="the type of grant",
174
     *         required=true,
175
     *         default="client_credentials",
176
     *     ),
177
     *     @OA\Parameter(
178
     *         name="client_id",
179
     *         in="formData",
180
     *         type="string",
181
     *         description="the client id",
182
     *         required=true,
183
     *         default="ceac682a9a4808bf910ad49134230e0e"
184
     *     ),
185
     *     @OA\Parameter(
186
     *         name="client_secret",
187
     *         in="formData",
188
     *         type="string",
189
     *         description="the client secret",
190
     *         required=false,
191
     *         default="JDJ5JDEwJGNEd1J1VEdOY0YxS3QvL0pWQzMxay52"
192
     *     ),
193
     *     @OA\Parameter(
194
     *         name="scope",
195
     *         in="formData",
196
     *         type="string",
197
     *         description="the scopes you wish to use",
198
     *         required=false,
199
     *         default="admin"
200
     *     ),
201
     *     @OA\Parameter(
202
     *         name="redirect_uri",
203
     *         in="formData",
204
     *         type="string",
205
     *         description="with the same redirect URI the user was redirect back to",
206
     *         required=false,
207
     *     ),
208
     *     @OA\Parameter(
209
     *         name="code",
210
     *         in="formData",
211
     *         type="string",
212
     *         description="with the authorization code from the query string",
213
     *         required=false,
214
     *     ),
215
     * )
216
     */
217 7
    public function accessTokenAction()
218
    {
219
        /* @var AuthorizationServer $server */
220 7
        $server = $this->oauth2Server;
221
222 7
        $request = $this->getRequest();
223 7
        $response = new Response();
224
225
        try {
226
            // Try to respond to the access token request
227 7
            $response = $server->respondToAccessTokenRequest($request, $response);
228 4
        } catch (OAuthServerException $e) {
229 3
            $response = $e->generateHttpResponse($response);
230 1
        } catch (Exception $e) {
231 1
            $code = $e->getCode() ?: 500;
232
            $response = $response
233 1
                ->withStatus($code)
234 1
                ->withHeader('content-type', 'application/json; charset=UTF-8');
235 1
            $response->getBody()->write(\json_encode([
236 1
                'error' => $code,
237 1
                'message' => $e->getMessage(),
238
            ]));
239
        }
240 7
        $this->sendResponse($response);
241
    }
242
243
    /**
244
     * @return Form
245
     */
246
    private function getForm()
247
    {
248
        $form = new Form('auth');
249
        $radio = new Radio('auth');
250
        $radio->setOptions([
251
            'yes' => 'Yes',
252
            'no' => 'No',
253
        ]);
254
        $radio->setLabel('Do you authorise TestClient?');
255
        $radio->setRenderInline(true);
256
        $radio->setRequired(true);
257
        $submit = new Submit('submit');
258
259
        $form->addField($radio)
260
            ->addField($submit);
261
262
        return $form;
263
    }
264
}
265