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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
|
<?php
namespace MediaWiki\Extensions\OAuth\Frontend\SpecialPages;
/**
* (c) Chris Steipp, Aaron Schulz 2013, GPL
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* http://www.gnu.org/copyleft/gpl.html
*/
use Firebase\JWT\JWT;
use MediaWiki\Extensions\OAuth\Backend\Consumer;
use MediaWiki\Extensions\OAuth\Backend\ConsumerAcceptance;
use MediaWiki\Extensions\OAuth\Backend\MWOAuthException;
use MediaWiki\Extensions\OAuth\Backend\MWOAuthRequest;
use MediaWiki\Extensions\OAuth\Backend\MWOAuthToken;
use MediaWiki\Extensions\OAuth\Backend\Utils;
use MediaWiki\Extensions\OAuth\Control\ConsumerAcceptanceSubmitControl;
use MediaWiki\Extensions\OAuth\Control\ConsumerAccessControl;
use MediaWiki\Extensions\OAuth\Lib\OAuthException;
use MediaWiki\Extensions\OAuth\Lib\OAuthToken;
use MediaWiki\Extensions\OAuth\Lib\OAuthUtil;
use MediaWiki\Extensions\OAuth\UserStatementProvider;
use MediaWiki\Logger\LoggerFactory;
use Psr\Log\LoggerInterface;
/**
* Page that handles OAuth consumer authorization and token exchange
*/
class SpecialMWOAuth extends \UnlistedSpecialPage {
/** @var LoggerInterface */
protected $logger;
/** @var int Defaults to OAuth1 */
protected $oauthVersion = Consumer::OAUTH_VERSION_1;
public function __construct() {
parent::__construct( 'OAuth' );
$this->logger = LoggerFactory::getInstance( 'OAuth' );
}
public function doesWrites() {
return true;
}
public function getLocalName() {
// Force the canonical name when OAuth headers are present,
// otherwise SpecialPageFactory redirects and breaks the signature.
if ( Utils::hasOAuthHeaders( $this->getRequest() ) ) {
return $this->getName();
}
return parent::getLocalName();
}
public function execute( $subpage ) {
global $wgMWOAuthSecureTokenTransfer, $wgMWOAuthReadOnly, $wgBlockDisablesLogin;
$this->setHeaders();
$user = $this->getUser();
$request = $this->getRequest();
$format = $request->getVal( 'format', 'raw' );
try {
if ( $wgMWOAuthReadOnly &&
!in_array( $subpage, [ 'verified', 'grants', 'identify' ] )
) {
throw new MWOAuthException( 'mwoauth-db-readonly' );
}
$this->determineOAuthVersion( $request );
switch ( $subpage ) {
case 'initiate':
$this->assertOAuthVersion( Consumer::OAUTH_VERSION_1 );
$oauthServer = Utils::newMWOAuthServer();
$oauthRequest = MWOAuthRequest::fromRequest( $request );
$this->logger->debug( __METHOD__ . ": Getting temporary credentials" );
// fetch_request_token does the version, freshness, and sig checks
$token = $oauthServer->fetch_request_token( $oauthRequest );
$this->returnToken( $token, $format );
break;
case 'approve':
$this->assertOAuthVersion( Consumer::OAUTH_VERSION_2 );
$format = 'html';
$clientId = $request->getVal( 'client_id', '' );
$this->logger->debug( __METHOD__ . ": doing '$subpage' for OAuth2 with " .
"client_id '$clientId' for '{$user->getName()}'" );
if ( $user->isAnon() ) {
// Should not happen, as user login status will already be checked at this point
// Just redirect back to REST, it will then redirect to login
return $this->redirectToREST();
}
if ( $request->wasPosted() && $request->getCheck( 'cancel' ) ) {
$this->showCancelPage( $clientId );
} else {
$this->handleAuthorizationForm(
null, $clientId, true
);
}
break;
case 'authorize':
case 'authenticate':
$this->assertOAuthVersion( Consumer::OAUTH_VERSION_1 );
$format = 'html'; // for exceptions
$requestToken = $request->getVal( 'requestToken',
$request->getVal( 'oauth_token' ) );
$consumerKey = $request->getVal( 'consumerKey',
$request->getVal( 'oauth_consumer_key' ) );
$this->logger->debug( __METHOD__ . ": doing '$subpage' with " .
"'$requestToken' '$consumerKey' for '{$user->getName()}'" );
// TODO? Test that $requestToken exists in memcache
if ( $user->isAnon() ) {
// Login required on provider wiki
$this->requireLogin( 'mwoauth-login-required-reason' );
} else {
if ( $request->wasPosted() && $request->getCheck( 'cancel' ) ) {
// Show acceptance cancellation confirmation
$this->showCancelPage( $consumerKey );
} else {
// Show form and redirect on submission for authorization
$this->handleAuthorizationForm(
$requestToken, $consumerKey, $subpage === 'authenticate'
);
}
}
break;
case 'token':
$this->assertOAuthVersion( Consumer::OAUTH_VERSION_1 );
$oauthServer = Utils::newMWOAuthServer();
$oauthRequest = MWOAuthRequest::fromRequest( $request );
$isRsa = $oauthRequest->get_parameter( "oauth_signature_method" ) === 'RSA-SHA1';
// We want to use HTTPS when returning the credentials. But
// for RSA we don't need to return a token secret, so HTTP is ok.
if ( $wgMWOAuthSecureTokenTransfer && !$isRsa
&& $request->detectProtocol() == 'http'
&& substr( wfExpandUrl( '/', PROTO_HTTPS ), 0, 8 ) === 'https://'
) {
$redirUrl = str_replace(
'http://', 'https://', $request->getFullRequestURL()
);
$this->getOutput()->redirect( $redirUrl );
$this->getOutput()->addVaryHeader( 'X-Forwarded-Proto' );
break;
}
$token = $oauthServer->fetch_access_token( $oauthRequest );
if ( $isRsa ) {
// RSA doesn't use the token secret, so don't return one.
$token->secret = '__unused__';
}
$this->returnToken( $token, $format );
break;
case 'verified':
$this->assertOAuthVersion( Consumer::OAUTH_VERSION_1 );
$format = 'html'; // for exceptions
$verifier = $request->getVal( 'oauth_verifier' );
$requestToken = $request->getVal( 'oauth_token' );
if ( !$verifier || !$requestToken ) {
throw new MWOAuthException( 'mwoauth-bad-request-missing-params', [
\Message::rawParam( \Linker::makeExternalLink(
'https://www.mediawiki.org/wiki/Help:OAuth/Errors#E001',
'E001',
true
) )
] );
}
$this->getOutput()->addSubtitle( $this->msg( 'mwoauth-desc' )->escaped() );
$this->showResponse(
$this->msg( 'mwoauth-verified',
wfEscapeWikiText( $verifier ),
wfEscapeWikiText( $requestToken )
)->parse(),
$format
);
break;
case 'grants':
$this->assertOAuthVersion( Consumer::OAUTH_VERSION_1 );
// Backwards compatibility
$listGrants = \SpecialPage::getTitleFor( 'ListGrants' );
$this->getOutput()->redirect( $listGrants->getFullURL() );
break;
case 'identify':
$this->assertOAuthVersion( Consumer::OAUTH_VERSION_1 );
$format = 'json'; // we only return JWT, so we assume json
$server = Utils::newMWOAuthServer();
$oauthRequest = MWOAuthRequest::fromRequest( $request );
// verify_request throws an exception if anything isn't verified
list( $consumer, $token ) = $server->verify_request( $oauthRequest );
/** @var Consumer $consumer */
/** @var MWOAuthToken $token */
$wiki = wfWikiID();
$dbr = Utils::getCentralDB( DB_REPLICA );
$access = ConsumerAcceptance::newFromToken( $dbr, $token->key );
$localUser = Utils::getLocalUserFromCentralId( $access->getUserId() );
if ( !$localUser || !$localUser->isLoggedIn() ) {
throw new MWOAuthException( 'mwoauth-invalid-authorization-invalid-user', [
\Message::rawParam( \Linker::makeExternalLink(
'https://www.mediawiki.org/wiki/Help:OAuth/Errors#E008',
'E008',
true
) )
] );
} elseif ( $localUser->isLocked() ||
$wgBlockDisablesLogin && $localUser->isBlocked()
) {
throw new MWOAuthException( 'mwoauth-invalid-authorization-blocked-user' );
}
// Access token is for this wiki
if ( $access->getWiki() !== '*' && $access->getWiki() !== $wiki ) {
throw new MWOAuthException(
'mwoauth-invalid-authorization-wrong-wiki',
[ $wiki ]
);
} elseif ( !$consumer->isUsableBy( $localUser ) ) {
throw new MWOAuthException( 'mwoauth-invalid-authorization-not-approved',
$consumer->getName() );
}
// We know the identity of the user who granted the authorization
$this->outputJWT( $localUser, $consumer, $oauthRequest, $format, $access );
break;
case 'rest_redirect':
$query = $this->getRequest()->getQueryValues();
$restUrl = $query['rest_url'];
unset( $query['title'] );
unset( $query['rest_url'] );
$target = wfExpandUrl( $restUrl );
$this->getOutput()->redirect( wfAppendQuery( $target, $query ) );
break;
case '':
$output = $this->getOutput();
$this->addHelpLink( 'Help:OAuth' );
$output->addWikiMsg( 'mwoauth-nosubpage-explanation' );
break;
default:
$format = $request->getVal( 'format', 'html' );
$dbr = Utils::getCentralDB( DB_REPLICA );
$cmrAc = ConsumerAccessControl::wrap(
Consumer::newFromKey(
$dbr,
$request->getVal( 'oauth_consumer_key', null )
),
$this->getContext()
);
if ( !$cmrAc || !$cmrAc->userCanAccess( 'userId' ) ) {
$this->showError(
$this->msg( 'mwoauth-bad-request-invalid-action' )->rawParams(
\Linker::makeExternalLink(
'https://www.mediawiki.org/wiki/Help:OAuth/Errors#E002',
'E002',
true
)
),
$format
);
} else {
$owner = $cmrAc->getUserName( $this->getUser() );
$this->showError(
$this->msg( 'mwoauth-bad-request-invalid-action-contact',
Utils::getCentralUserTalk( $owner )
)->rawParams( \Linker::makeExternalLink(
'https://www.mediawiki.org/wiki/Help:OAuth/Errors#E003',
'E003',
true
) ),
$format
);
}
}
} catch ( MWOAuthException $exception ) {
$this->logger->warning( __METHOD__ . ": Exception " . $exception->getMessage(),
[ 'exception' => $exception ] );
$this->showError( $this->msg( $exception->msg, $exception->params ), $format );
} catch ( OAuthException $exception ) {
$this->logger->warning( __METHOD__ . ": Exception " . $exception->getMessage(),
[ 'exception' => $exception ] );
$this->showError(
$this->msg( 'mwoauth-oauth-exception', $exception->getMessage() ),
$format
);
}
$this->getOutput()->addModuleStyles( 'ext.MWOAuth.styles' );
}
/**
* @param string $consumerKey
* @throws MWOAuthException
*/
protected function showCancelPage( $consumerKey ) {
$dbr = Utils::getCentralDB( DB_REPLICA );
$cmrAc = ConsumerAccessControl::wrap(
Consumer::newFromKey( $dbr, $consumerKey ),
$this->getContext()
);
if ( !$cmrAc ) {
throw new MWOAuthException( 'mwoauth-invalid-consumer-key' );
}
if ( $cmrAc->getOAuthVersion() === Consumer::OAUTH_VERSION_2 ) {
// Respond to client with user approval denied error
$this->redirectToREST( [
'approval_cancel' => 1
] );
return;
}
$this->getOutput()->addSubtitle( $this->msg( 'mwoauth-desc' )->escaped() );
$this->getOutput()->addWikiMsg(
'mwoauth-acceptance-cancelled',
$cmrAc->getName()
);
$this->getOutput()->addReturnTo( \Title::newMainPage() );
}
/**
* Make statements about the user, and sign the json with
* a key shared with the Consumer.
* @param \User $user the user who is the subject of this request
* @param Consumer $consumer
* @param MWOAuthRequest $request
* @param string $format the format of the response: raw, json, or html
* @param ConsumerAcceptance $access
*/
protected function outputJWT( $user, $consumer, $request, $format, $access ) {
$grants = $access->getGrants();
$userStatementProvider = UserStatementProvider::factory( $user, $consumer, $grants );
$statement = $userStatementProvider->getUserStatement();
// String value used to associate a Client session with an ID Token, and to mitigate
// replay attacks. The value is passed through unmodified from the Authorization Request.
$statement['nonce'] = $request->get_parameter( 'oauth_nonce' );
$JWT = JWT::encode( $statement, $consumer->secret );
$this->showResponse( $JWT, $format );
}
protected function handleAuthorizationForm( $requestToken, $consumerKey, $authenticate ) {
$this->getOutput()->addSubtitle( $this->msg( 'mwoauth-desc' )->escaped() );
$user = $this->getUser();
$oauthServer = Utils::newMWOAuthServer();
if ( !$consumerKey && $this->oauthVersion === Consumer::OAUTH_VERSION_1 ) {
$consumerKey = $oauthServer->getConsumerKey( $requestToken );
}
$cmrAc = ConsumerAccessControl::wrap(
Consumer::newFromKey( Utils::getCentralDB( DB_REPLICA ), $consumerKey ),
$this->getContext()
);
if ( !$cmrAc || !$cmrAc->userCanAccess( [ 'name', 'userId', 'grants' ] ) ) {
throw new MWOAuthException( 'mwoauthserver-bad-consumer-key', [
\Message::rawParam( \Linker::makeExternalLink(
'https://www.mediawiki.org/wiki/Help:OAuth/Errors#E006',
'E006',
true
) )
] );
} elseif (
!$cmrAc->getDAO()->isUsableBy( $user ) ||
$cmrAc->getDAO()->getOAuthVersion() !== $this->oauthVersion
) {
throw new MWOAuthException(
'mwoauthserver-bad-consumer',
[
$cmrAc->getName(),
Utils::getCentralUserTalk( $cmrAc->getUserName() ),
]
);
}
$existing = $cmrAc->getDAO()->getCurrentAuthorization( $user, wfWikiID() );
// If only authentication was requested, and the existing authorization
// matches, and the only grants are 'mwoauth-authonly' or 'mwoauth-authonlyprivate',
// then don't bother prompting the user about it.
if ( $existing && $authenticate &&
$existing->getWiki() === $cmrAc->getDAO()->getWiki() &&
$existing->getGrants() === $cmrAc->getDAO()->getGrants() &&
!array_diff( $existing->getGrants(), [ 'mwoauth-authonly', 'mwoauth-authonlyprivate' ] )
) {
if ( $this->oauthVersion === Consumer::OAUTH_VERSION_2 ) {
$this->redirectToREST( [
'approval_pass' => true
] );
} else {
$callback = $cmrAc->getDAO()->authorize(
$user, false, $cmrAc->getDAO()->getGrants(), $requestToken
);
$this->getOutput()->redirect( $callback );
}
return;
}
$this->getOutput()->addModuleStyles(
[ 'mediawiki.ui', 'mediawiki.ui.button', 'ext.MWOAuth.Styles' ]
);
$this->getOutput()->addModules( 'ext.MWOAuth.AuthorizeDialog' );
$control = new ConsumerAcceptanceSubmitControl(
$this->getContext(), [], Utils::getCentralDB( DB_MASTER ), $this->oauthVersion
);
$form = \HTMLForm::factory( 'table',
$control->registerValidators( $this->getRequestValidators( [
'existing' => $existing,
'consumerKey' => $consumerKey,
'requestToken' => $requestToken
] ) ),
$this->getContext()
);
$form->setSubmitCallback(
function ( array $data, \IContextSource $context ) use ( $control ) {
if ( $context->getRequest()->getCheck( 'cancel' ) ) { // sanity
throw new \MWException( 'Received request for a form cancellation.' );
}
$control->setInputParameters( $data );
return $control->submit();
}
);
$form->setId( 'mw-mwoauth-authorize-form' );
// Possible messages are:
// * mwoauth-form-description-allwikis
// * mwoauth-form-description-onewiki
// * mwoauth-form-description-allwikis-nogrants
// * mwoauth-form-description-onewiki-nogrants
// * mwoauth-form-description-allwikis-privateinfo
// * mwoauth-form-description-onewiki-privateinfo
// * mwoauth-form-description-allwikis-privateinfo-norealname
// * mwoauth-form-description-onewiki-privateinfo-norealname
$msgKey = 'mwoauth-form-description';
$params = [
$this->getUser()->getName(),
$cmrAc->getName(),
$cmrAc->getUserName(),
];
if ( $cmrAc->getWiki() === '*' ) {
$msgKey .= '-allwikis';
} else {
$msgKey .= '-onewiki';
$params[] = $cmrAc->getWikiName();
}
$grants = $cmrAc->getGrants();
if ( $this->oauthVersion === Consumer::OAUTH_VERSION_2 ) {
$grants = $this->getRequestedGrants( $cmrAc );
}
$grantsText = \MWGrants::getGrantsWikiText( $grants, $this->getLanguage() );
if ( $grantsText === "\n" ) {
if ( in_array( 'mwoauth-authonlyprivate', $cmrAc->getGrants(), true ) ) {
$msgKey .= '-privateinfo';
if ( !$this->useRealNames() ) {
// If the wiki does not use real names, don't mention them in the authorization
// dialog to avoid scaring users. The wiki where the authorization dialog is
// shown and the wiki where the user is actually identified might be different;
// there's not much we can do about that here so it is left to the wiki
// administrator to set up the farm in a non-misleading way.
$msgKey .= '-norealname';
}
} else {
$msgKey .= '-nogrants';
}
} else {
$params[] = $grantsText;
}
$form->addHeaderText( $this->msg( $msgKey, $params )->parseAsBlock() );
$form->addHeaderText( $this->msg( 'mwoauth-form-legal' )->text() );
$form->suppressDefaultSubmit();
$form->addButton( [
'name' => 'accept',
'value' => $this->msg( 'mwoauth-form-button-approve' )->text(),
'id' => 'mw-mwoauth-accept',
'attribs' => [
'class' => 'mw-mwoauth-authorize-button mw-ui-button mw-ui-progressive'
]
] );
$form->addButton( [
'name' => 'cancel',
'value' => $this->msg( 'mwoauth-form-button-cancel' )->text(),
'attribs' => [
'class' => 'mw-mwoauth-authorize-button mw-ui-button mw-ui-quiet'
]
] );
$form->addFooterText( $this->getSkin()->privacyLink() );
$this->getOutput()->addHTML(
'<div id="mw-mwoauth-authorize-dialog" class="mw-ui-container">' );
$status = $form->show();
$this->getOutput()->addHTML( '</div>' );
if ( $status instanceof \Status && $status->isOK() ) {
if ( $this->oauthVersion === Consumer::OAUTH_VERSION_2 ) {
$this->redirectToREST( [
'approval_pass' => true
] );
} else {
// Redirect to callback url
// @phan-suppress-next-line PhanTypeArraySuspiciousNullable
$this->getOutput()->redirect( $status->value['result']['callbackUrl'] );
}
}
}
private function redirectToREST( $queryAppend = [] ) {
$redirectParams = [
'returnto' => $this->getRequest()->getText(
'returnto', $this->getRequest()->getText( 'returnto' )
),
'returntoquery' => wfCgiToArray(
$this->getRequest()->getText(
'returntoquery', $this->getRequest()->getText( 'returntoquery' )
)
)
];
$expanded = wfExpandUrl( $redirectParams['returnto'] );
if ( !$expanded ) {
return;
}
$returnToQuery = array_merge(
$redirectParams['returntoquery'],
$queryAppend
);
$returnToQuery = wfArrayToCgi( $returnToQuery );
$this->getOutput()->disable();
$this->getOutput()->getRequest()->response()->header(
'Location: ' . "$expanded?{$returnToQuery}"
);
}
private function getRequestValidators( $data = [] ) {
$validators = [
'action' => [
'type' => 'hidden',
'default' => 'accept',
],
'confirmUpdate' => [
'type' => 'hidden',
'default' => $data['existing'] ? 1 : 0,
],
'oauth_version' => [
'name' => 'oauth_version',
'type' => 'hidden',
'default' => $this->oauthVersion
],
];
if ( $this->oauthVersion === Consumer::OAUTH_VERSION_2 ) {
$validators += [
'client_id' => [
'name' => 'client_id',
'type' => 'hidden',
'default' => $this->getRequest()->getText( 'client_id' )
],
'scope' => [
'name' => 'scope',
'type' => 'hidden',
'default' => $this->getRequest()->getText( 'scope' )
],
'returnto' => [
'name' => 'returnto',
'type' => 'hidden',
'default' => $this->getRequest()->getText( 'returnto' )
],
'returntoquery' => [
'name' => 'returntoquery',
'type' => 'hidden',
'default' => $this->getRequest()->getText( 'returntoquery' )
],
];
} else {
$validators += [
'consumerKey' => [
'name' => 'consumerKey',
'type' => 'hidden',
'default' => $data['consumerKey']
],
'requestToken' => [
'name' => 'requestToken',
'type' => 'hidden',
'default' => $data['requestToken'],
],
];
}
return $validators;
}
/**
* OAuth 2.0 only
* Get only the grants (scopes) that were actually requested (and are allowed)
*
* @param ConsumerAccessControl $cmrAc
* @return array
*/
private function getRequestedGrants( $cmrAc ) {
$allowed = $cmrAc->getGrants();
$requested = explode( ' ', $this->getRequest()->getText( 'scope', '' ) );
return array_intersect( $requested, $allowed );
}
/**
* @param \Message $message to return to the user
* @param string $format the format of the response: html, raw, or json
*/
private function showError( $message, $format ) {
if ( $format == 'raw' ) {
$this->showResponse( 'Error: ' . $message->escaped(), 'raw' );
} elseif ( $format == 'json' ) {
$error = \FormatJson::encode( [
'error' => $message->getKey(),
'message' => $message->text(),
] );
$this->showResponse( $error, 'json' );
} elseif ( $format == 'html' ) {
$this->getOutput()->showErrorPage( 'mwoauth-error', $message );
}
}
/**
* @param OAuthToken $token
* @param string $format the format of the response: html, raw, or json
*/
private function returnToken( OAuthToken $token, $format ) {
if ( $format == 'raw' ) {
$return = 'oauth_token=' . OAuthUtil::urlencode_rfc3986( $token->key );
$return .= '&oauth_token_secret=' . OAuthUtil::urlencode_rfc3986( $token->secret );
$return .= '&oauth_callback_confirmed=true';
$this->showResponse( $return, 'raw' );
} elseif ( $format == 'json' ) {
$this->showResponse( \FormatJson::encode( $token ), 'json' );
} elseif ( $format == 'html' ) {
$html = \Html::element(
'li',
[],
'oauth_token = ' . OAuthUtil::urlencode_rfc3986( $token->key )
);
$html .= \Html::element(
'li',
[],
'oauth_token_secret = ' . OAuthUtil::urlencode_rfc3986( $token->secret )
);
$html .= \Html::element(
'li',
[],
'oauth_callback_confirmed = true'
);
$html = \Html::rawElement( 'ul', [], $html );
$this->showResponse( $html, 'html' );
}
}
/**
* @param string $data html or string to pass back to the user. Already escaped.
* @param string $format the format of the response: raw, json, or html
* @param-taint $data escaped
*/
private function showResponse( $data, $format ) {
$out = $this->getOutput();
if ( $format == 'raw' || $format == 'json' ) {
$this->getOutput()->disable();
// Cancel output buffering and gzipping if set
wfResetOutputBuffers();
// We must not allow the output to be Squid cached
$response = $this->getRequest()->response();
$response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
$response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
$response->header( 'Pragma: no-cache' );
$response->header( 'Content-length: ' . strlen( $data ) );
if ( $format == 'json' ) {
$response->header( 'Content-type: application/json' );
} else {
$response->header( 'Content-type: text/plain' );
}
print $data;
} elseif ( $format == 'html' ) { // html
$out->addHTML( $data );
}
}
/**
* Check whether the wiki is configured to use/show real names.
* We assume that either all or none of the OAuth wikis in a farm use real names.
* @return bool
*/
private function useRealNames() {
$config = $this->getContext()->getConfig();
return !in_array( 'realname', $config->get( 'HiddenPrefs' ), true );
}
/**
* Get the requested OAuth version from the request
*
* @param \WebRequest $request
* @return string
*/
private function determineOAuthVersion( \WebRequest $request ) {
$this->oauthVersion = $request->getInt( 'oauth_version', Consumer::OAUTH_VERSION_1 );
return $this->oauthVersion;
}
/**
* @param string $allowed Allowed version
* @throws MWOAuthException
*/
private function assertOAuthVersion( $allowed ) {
if ( $this->oauthVersion !== $allowed ) {
throw new MWOAuthException(
'mwoauth-oauth-unsupported-version',
$this->oauthVersion
);
}
}
}
|