Passed
Push — master ( 55f76c...4f5a8c )
by Derek Stephen
02:54
created

AuthCodeController::accessTokenAction()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 3

Importance

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