-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathRouter.php
243 lines (219 loc) · 8.41 KB
/
Router.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
<?php
use Illuminate\Http\Response;
use NPR\One\Controllers\{AuthCodeController, DeviceCodeController, LogoutController, RefreshTokenController};
use NPR\One\Exceptions\ApiException;
use Your\Package\Here\{ConfigProvider, StorageProvider};
/**
* This route corresponds to Phase 1 of the Authorization Code grant.
* @see https://github.com/npr/npr-one-backend-proxy-php#authorization-code-grant
*
* If you are using the Device Code grant, you do not need to implement this route.
*/
Route::get('/', function ()
{
$controller = (new AuthCodeController())
->setConfigProvider(new ConfigProvider())
->setStorageProvider(new StorageProvider());
try
{
$url = $controller->startAuthorizationGrant([
'identity.readonly',
'identity.write',
'listening.readonly',
'listening.write',
'localactivation'
]);
return redirect()->away($url); // in this case, all is well and we're redirecting to the login page on npr.org
}
catch (\Exception $e)
{
Log::error("During OAuth login, npr-one-backend-proxy encountered an error: {$e->getMessage()}");
}
return redirect()->away($controller->getRedirectUri()); // something went wrong; all we can do is redirect back to the app
// alternatively, you could create some kind of Error page saying "Something went wrong. Click here to go back to the app." (to make it more explicit to users)
});
/**
* This route corresponds to Phase 2 of the Authorization Code grant.
* @see https://github.com/npr/npr-one-backend-proxy-php#authorization-code-grant
*
* It is important to note that the path corresponding to this route should match EXACTLY what you registered as
* your `redirect_uri` in the NPR One Developer Center.
*
* If you are using the Device Code grant, you do not need to implement this route.
*/
Route::get('callback', function ()
{
$controller = (new AuthCodeController())
->setConfigProvider(new ConfigProvider())
->setStorageProvider(new StorageProvider());
$error = $_GET['error'];
$message = $_GET['message'];
try
{
if (!empty($error))
{
if ($error !== 'denied')
{
Log::error("During OAuth login, npr-one-backend-proxy encountered an error: $error, message: $message");
}
// if $error === 'denied' - user chose to deny the login request, no need to log it (not a "true" error state).
}
else
{
$authorizationCode = $_GET['code'];
$state = $_GET['state'];
if (empty($authorizationCode) || empty($state))
{
Log::error('During OAuth login, npr-one-backend-proxy encountered an error: Either authorization code or state not set.');
}
else
{
$controller->completeAuthorizationGrant($authorizationCode, $state); // if this doesn't throw any exceptions, then we're good
}
}
}
catch (\Exception $e)
{
Log::error("During OAuth login, npr-one-backend-proxy encountered an error: {$e->getMessage()}");
}
return redirect()->away($controller->getRedirectUri()); // no matter whether we're OK or we're in an error state, we redirect back to the app
// again, you may want to consider creating a "Something went wrong" page for error states, but that's beyond the scope of this example
});
/**
* This route corresponds to Phase 1 of the Device Code grant.
* @see https://github.com/npr/npr-one-backend-proxy-php#device-code-grant
*
* If you are using the Authorization Code grant, you do not need to implement this route.
*/
Route::post('device', function ()
{
$controller = (new DeviceCodeController())
->setConfigProvider(new ConfigProvider());
$statusCode = 201;
try
{
$data = $controller->startDeviceCodeGrant([
'identity.readonly',
'identity.write',
'listening.readonly',
'listening.write',
'localactivation'
]);
}
catch (ApiException $e)
{
$data = $e->getMessage();
$statusCode = $e->getStatusCode();
}
catch (\Exception $e)
{
$data = $e->getMessage();
$statusCode = 500;
}
return addCORSHeaders(response())->json($data)->setStatusCode($statusCode); // this route is meant to be called with AJAX/Fetch, so we're returning JSON
});
/**
* This route corresponds to Phase 2 of the Device Code grant.
* @see https://github.com/npr/npr-one-backend-proxy-php#device-code-grant
*
* If you are using the Authorization Code grant, you do not need to implement this route.
*/
Route::post('device/poll', function ()
{
$controller = (new DeviceCodeController())
->setConfigProvider(new ConfigProvider());
$statusCode = 201;
try
{
$data = $controller->pollDeviceCodeGrant();
}
catch (ApiException $e)
{
$data = !empty($e->getBody()) ? $e->getBody() : $e->getMessage();
$statusCode = $e->getStatusCode();
}
catch (\Exception $e)
{
$data = $e->getMessage();
$statusCode = 500;
}
return addCORSHeaders(response())->json($data)->setStatusCode($statusCode); // this route is meant to be called with AJAX/Fetch, so we're returning JSON
});
/**
* This route corresponds to the Refresh Token grant.
* @see https://github.com/npr/npr-one-backend-proxy-php#refresh-token-grant
*
* EVERYONE, regardless of which grant you use to log in your users, must implement this route.
*/
Route::post('refresh', function ()
{
$controller = (new RefreshTokenController())
->setConfigProvider(new ConfigProvider());
$statusCode = 201;
try
{
$data = $controller->generateNewAccessTokenFromRefreshToken();
}
catch (ApiException $e)
{
$data = $e->getMessage();
$statusCode = $e->getStatusCode();
}
catch (\Exception $e)
{
$data = $e->getMessage();
$statusCode = 500;
}
return addCORSHeaders(response())->json($data)->setStatusCode($statusCode); // this route is meant to be called with AJAX/Fetch, so we're returning JSON
});
Route::post('logout', function ()
{
$token = $_GET['token'];
$controller = (new LogoutController())
->setConfigProvider(new ConfigProvider());
$statusCode = 200;
try
{
$controller->deleteAccessAndRefreshTokens($token);
$data = ''; // there is nothing to return in the case of success; an empty string should suffice
}
catch (ApiException $e)
{
$data = $e->getMessage();
$statusCode = $e->getStatusCode();
}
catch (\Exception $e)
{
$data = $e->getMessage();
$statusCode = 500;
}
return addCORSHeaders(response())->json($data)->setStatusCode($statusCode); // this route is meant to be called with AJAX/Fetch, so we're returning JSON
});
/**
* This helper function sets the CORS headers required to use these endpoints in a frontend Javascript-based application.
*
* NOTE: It is HIGHLY recommended that you use a CORS middleware which is usually provided by your PHP framework
* (or available as an optional plugin); however, in the (unlikely) event that no such middleware is available,
* we have included here the headers that need to be set in order for the proxy to work with the secure cookie-based
* refresh tokens.
*
* @param Response $response
* @return Response
*/
function addCORSHeaders(Response $response)
{
$response->header('Access-Control-Allow-Origin', 'one.example.com'); // IMPORTANT!! you cannot use a wildcard ('*') here; you MUST include a host
$response->header('Access-Control-Allow-Credentials', 'true'); // this is the reason why you MUST include a host; you cannot use a wildcard with Allow-Credentials
$response->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS'); // if you are using methods other than POST and GET, update accordingly
$response->header('Access-Control-Allow-Headers', join(', ', [
'origin', 'accept', 'content-type', 'authorization',
'x-http-method-override', 'x-pingother', 'x-requested-with',
'if-match', 'if-modified-since', 'if-none-match', 'if-unmodified-since'
]));
$response->header('Access-Control-Expose-Headers', join(', ', [
'tag', 'link',
'X-RateLimit-Limit', 'X-RateLimit-Remaining', 'X-RateLimit-Reset',
'X-OAuth-Scopes', 'X-Accepted-OAuth-Scopes'
]));
return $response;
}