Passed
Push — master ( d88618...734b92 )
by Derek Stephen
02:56
created

AuthCodeController   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 207
Duplicated Lines 0 %

Test Coverage

Coverage 61.4%

Importance

Changes 0
Metric Value
eloc 58
dl 0
loc 207
ccs 35
cts 57
cp 0.614
rs 10
c 0
b 0
f 0
wmc 10

3 Methods

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