-
Notifications
You must be signed in to change notification settings - Fork 0
/
RestController.php
457 lines (413 loc) · 15.6 KB
/
RestController.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
<?php
/**
* @category Kiatng
* @package Kiatng_Shooter
* @copyright Copyright (c) 2024 Ng Kiat Siong
* @license GNU GPL v3.0
*/
class Kiatng_Shooter_RestController extends Kiatng_Shooter_Controller_Abstract
{
const STATE_INIT = 0;
const STATE_REQUEST_TOKEN = 1;
const STATE_ACCESS_TOKEN = 2;
const STATE_RESOURCE = 3;
public function preDispatch()
{
/**
* Check if we lost the session at callback.
* URL: domain/shooter/rest/callback/ssid/37teecslrt5k6q40if0nrqel7e/?oauth_token=random&oauth_verifier=random
* @link https://stackoverflow.com/questions/22079477/session-is-lost-after-an-oauth-redirect
*/
if (
$this->getRequest()->getActionName() === 'callback'
&& !Mage::getSingleton('customer/session')->isLoggedIn()
&& $sid = $this->getRequest()->getParam('ssid')
) {
// Set the session in browser's cookie.
Mage::getSingleton('core/cookie')->set(self::SESSION_NAMESPACE, $sid);
// Use js to redirect in browser to restore the session, other redirect methods will lose the session.
$url = Mage::getUrl('*/*', ['_current' => true, '_use_rewrite' => true, '_query' => $_GET]);
echo "<script>window.location = '$url';</script>";
die();
}
parent::preDispatch();
}
/**
* Get OAuth consumer from session.
*
* @return Zend_Oauth_Consumer
*/
protected function _getConsumer(): ?Zend_Oauth_Consumer
{
return Mage::getSingleton('customer/session')->getOauthConsumer();
}
/**
* Entry point to OAuth.
*/
public function indexAction()
{
$session = Mage::getSingleton('customer/session');
$state = $session->getOauthConsumer() ? $session->getOauthState() : self::STATE_INIT;
switch ($state) {
case self::STATE_INIT:
$this->_init();
break;
case self::STATE_REQUEST_TOKEN:
$this->_requestToken();
break;
case self::STATE_ACCESS_TOKEN:
$this->callbackAction();
break;
case self::STATE_RESOURCE:
// Render resource page.
$this->_renderLayout($this->__('shooter REST Resources'), 'resource');
break;
}
}
/**
* Callback from OAuth host. Get access token from OAuth host and render resource page.
* http://openmage.site/shooter/rest/callback/?oauth_token=randonstring&oauth_verifier=randonstring
*/
public function callbackAction()
{
// Get access token from OAuth host.
$session = Mage::getSingleton('customer/session');
$session->setOauthAccessTokenGet($_GET);
if (!$session->getOauthAccessToken()) {
$consumer = $this->_getConsumer();
$requestToken = $consumer->getLastRequestToken() ?? $session->getOauthRequestToken();
try {
$accessToken = $consumer->getAccessToken($_GET, $requestToken);
} catch (Throwable $e) {
$session->addError($this->__('Problem getting access token from OAuth host: %s. Please try again.', $e->getMessage()));
return $this->_init();
}
$session->setOauthAccessToken($accessToken);
$session->setOauthState(self::STATE_RESOURCE);
}
$this->_renderLayout($this->__('shooter REST Resources'), 'resource');
}
/**
* Callback from OAuth host. User rejected the OAuth request.
* Configure the "Rejected Callback URL" in OM Backend > System > Configuration > Web Services > REST - OAuth Consumers > select a consumer.
* An example of the URL: https://openmage.site/shooter/rest/reject
*/
public function rejectAction()
{
Mage::getSingleton('customer/session')->addNotice($this->__('You have rejected the OAuth request.'));
$this->_init();
}
/**
* Save OAuth params to session.
*/
public function oauthPostAction()
{
$host = rtrim($this->getRequest()->getPost('url', ''), '/');
if (!$host) {
return $this->_redirect('*/*/new');
}
$session = Mage::getSingleton('customer/session');
$session->setOauthUrl($host);
$session->setOauthKey($this->getRequest()->getPost('key'));
$session->setOauthSecret($this->getRequest()->getPost('secret'));
$session->setOauthUserType($this->getRequest()->getPost('user_type'));
$session->setOauthState(self::STATE_REQUEST_TOKEN);
$consumer = new Zend_Oauth_Consumer([
'siteUrl' => "{$host}/oauth",
'requestTokenUrl' => "{$host}/oauth/initiate",
'accessTokenUrl' => "{$host}/oauth/token",
'authorizeUrl' => $session->getOauthUserType() === 'admin'
? "{$host}/admin/oauth_authorize"
: "{$host}/oauth/authorize",
'consumerKey' => $session->getOauthKey(),
'consumerSecret' => $session->getOauthSecret(),
//'callbackUrl' => Mage::getUrl('*/*/callback')
'callbackUrl' => Mage::getUrl('*/*/callback', ['ssid' => $session->getEncryptedSessionId()])
]);
$session->setOauthConsumer($consumer);
$this->_redirect('*/*');
}
/**
* Init session's OAuth data. Render OAuth form.
*/
protected function _init()
{
$session = Mage::getSingleton('customer/session');
foreach (Mage::getSingleton('customer/session')->getData() as $k => $v) {
if (strpos($k, 'oauth') === 0) {
$session->unsetData($k);
}
}
$session->setOauthState(self::STATE_INIT);
$this->_renderLayout($this->__('Test OAuth 1.0a'), 'oauth');
}
/**
* Get request token from OAuth host.
* https://openmage.site/oauth/authorize?oauth_token=9ac3d537fc0273b1f1a708b9cf0402bb
*/
protected function _requestToken()
{
$session = Mage::getSingleton('customer/session');
$session->setOauthRequestTokenGet($_GET);
$consumer = $this->_getConsumer();
try {
$requestToken = $consumer->getRequestToken();
} catch (Zend_Oauth_Exception $e) {
$url = $session->getOauthUrl();
$errMsg = $this->__('Problem getting request token from %s.<br>', $url);
$errMsg .= $e->getMessage();
if ($e->getPrevious()) {
$errMsg .= '<br><b>Previous error:</b> ' . $e->getPrevious()->getMessage();
}
$session->addError($errMsg);
return $this->_redirect('*/*/new');
} catch (Throwable $e) {
$url = $session->getOauthUrl();
$errMsg = $this->__('Problem getting request token from %s. Make sure you input the correct params.<br>', $url);
$errMsg .= $e->getMessage();
$session->addError($errMsg);
return $this->_redirect('*/*/new');
}
$session->setOauthRequestToken($requestToken);
$session->setOauthState(self::STATE_ACCESS_TOKEN);
$consumer->redirect(); // Redirect to host for authorization.
}
/**
* Get OAuth client from session.
*
* @return Zend_Oauth_Client
*/
protected function _getOauthClient()
{
$session = Mage::getSingleton('customer/session');
if (!$session->getOauthClient()) {
$session->setOauthAccessResourceGet($_GET);
$host = $session->getOauthUrl();
$oauthOptions = [
'siteUrl' => "$host/oauth",
'requestTokenUrl' => "$host/oauth/initiate",
'accessTokenUrl' => "$host/oauth/token",
'consumerKey' => $session->getOauthKey(),
'consumerSecret' => $session->getOauthSecret(),
];
$client = $this->_getConsumer()->getLastAccessToken()->getHttpClient($oauthOptions);
$client->setHeaders('Accept', 'application/json');
$session->setOauthClient($client);
}
return $session->getOauthClient();
}
/**
* Access resource from OAuth host.
*/
public function ajaxResourceAction()
{
$host = Mage::getSingleton('customer/session')->getOauthUrl();
if (!$host) {
return $this->_redirect('*/*/new');
}
$resource = $this->getRequest()->getParam('name', 'products');
$path = $this->getRequest()->getParam('path', '');
$method = $this->getRequest()->getParam('method', 'GET');
$params = $this->getRequest()->getParam('params');
if ($params && ($method === 'PUT' || $method === 'POST')) {
$params = json_decode($params, true);
}
$client = $this->_getOauthClient();
$client->setMethod($method);
if (is_array($params)) {
//$client->setParameterPost($params); // Mage_Api2_Exception: Server can not understand Content-Type HTTP header media type "application/x-www-form-urlencoded"
$client->setRawData(json_encode($params), 'application/json');
}
$client->setUri("$host/$path/$resource");
$response = $client->request();
$echo = json_encode([
'json_body' => json_decode($response->getBody(), true),
'headers' => $response->getHeaders(),
'status' => $response->getStatus(),
'message' => $response->getMessage(),
'raw_body' => $response->getRawBody(),
]);
$this->getResponse()
->setHeader('Content-Type', 'application/json')
->setBody($echo);
}
/**
* New OAuth session.
*/
public function newAction()
{
$this->_init();
}
/**
* @param string $title
* @param string $blockName
*/
protected function _renderLayout($title, $blockName)
{
$this->loadLayout(['default', 'page_one_column']);
$this->_initLayoutMessages('customer/session');
$layout = $this->getLayout();
$layout->getBlock('head')->setTitle($title);
$layout->getBlock('content')->append(
$layout->createBlock(
'core/template',
"shooter_rest_$blockName",
['template' => "shooter/rest/{$blockName}.phtml"]
)
);
/** @var Mage_Page_Block_Html $root */
$root = $layout->getBlock('root');
$root->unsetChild('header');
$root->unsetChild('footer');
$this->renderLayout();
}
/**
* Show session data.
*/
public function infoAction()
{
$data = ['sid' => Mage::getSingleton('core/session')->getEncryptedSessionId()];
foreach (Mage::getSingleton('customer/session')->getData() as $k => $v) {
if (strpos($k, 'oauth') === 0) {
$data[$k] = $v;
}
}
$this->_echo($data, 'Session Data');
}
/**
* Set OAuth state.
*/
public function stateAction()
{
$state = (int) $this->getRequest()->getParam('state', 1);
Mage::getSingleton('customer/session')->setOauthState($state);
$this->_redirect('*/*');
}
/**
* Test SSL connection to OAuth server
*/
public function testSslAction()
{
$session = Mage::getSingleton('customer/session');
$host = $session->getOauthUrl() ?: $this->getRequest()->getParam('url');
if (!$host) {
echo "Please provide a URL via parameter or OAuth session";
return;
}
$results = [];
// Test 1: Basic CURL connection
$results[] = $this->_testCurlConnection($host);
// Test 2: Try different SSL versions
$sslVersions = [
CURL_SSLVERSION_DEFAULT => 'Default',
CURL_SSLVERSION_TLSv1 => 'TLS 1.0',
CURL_SSLVERSION_TLSv1_1 => 'TLS 1.1',
CURL_SSLVERSION_TLSv1_2 => 'TLS 1.2'
];
foreach ($sslVersions as $version => $label) {
$results[] = $this->_testCurlConnection($host, [
CURLOPT_SSLVERSION => $version
], "CURL with $label");
}
// Test 3: Using Zend_Http_Client
try {
$client = new Zend_Http_Client($host);
$client->request();
$results[] = [
'test' => 'Zend_Http_Client',
'status' => 'Success',
'info' => $client->getLastResponse()->getStatus() . ' ' . $client->getLastResponse()->getMessage()
];
} catch (Exception $e) {
$results[] = [
'test' => 'Zend_Http_Client',
'status' => 'Failed',
'error' => $e->getMessage()
];
}
// Output results
echo "<pre>";
echo "SSL Connection Tests to: $host\n\n";
echo "PHP Version: " . phpversion() . "\n";
echo "CURL Version: " . curl_version()['version'] . "\n";
echo "OpenSSL Version: " . OPENSSL_VERSION_TEXT . "\n\n";
foreach ($results as $result) {
echo str_repeat("-", 50) . "\n";
echo "Test: {$result['test']}\n";
echo "Status: {$result['status']}\n";
if (isset($result['error'])) {
echo "Error: {$result['error']}\n";
}
if (isset($result['info'])) {
echo "Info: {$result['info']}\n";
}
echo "\n";
}
echo "</pre>";
}
/**
* Helper method to test CURL connection
*
* @param string $url
* @param array $extraOpts
* @param string $testName
* @return array
*/
protected function _testCurlConnection($url, $extraOpts = [], $testName = 'Basic CURL')
{
$ch = curl_init();
$opts = [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2, // Verify the certificate's name against host
CURLOPT_CERTINFO => true, // Get certificate info
CURLOPT_VERBOSE => true
];
// Capture CURL verbose output
$verbose = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_STDERR, $verbose);
curl_setopt_array($ch, $opts + $extraOpts);
$response = curl_exec($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
// Get certificate information
$certInfo = curl_getinfo($ch, CURLINFO_CERTINFO);
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
curl_close($ch);
if ($response === false) {
return [
'test' => $testName,
'status' => 'Failed',
'error' => $error,
'info' => "Verbose log:\n" . $verboseLog
];
}
// Format certificate chain information
$certChainInfo = '';
if (!empty($certInfo)) {
foreach ($certInfo as $key => $cert) {
$certChainInfo .= sprintf(
"\nCertificate #%d:\n" .
"Subject: %s\n" .
"Issuer: %s\n" .
"Valid Until: %s\n",
$key + 1,
$cert['Subject'] ?? 'N/A',
$cert['Issuer'] ?? 'N/A',
$cert['Expire date'] ?? 'N/A'
);
}
}
return [
'test' => $testName,
'status' => 'Success',
'info' => "HTTP {$info['http_code']}, SSL: {$info['ssl_verify_result']}\n" .
"Certificate Chain:" . $certChainInfo . "\n" .
"Verbose log:\n" . $verboseLog
];
}
}