-
Notifications
You must be signed in to change notification settings - Fork 5
/
WSOAuth.php
296 lines (249 loc) · 9.21 KB
/
WSOAuth.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
<?php
/**
* Copyright 2020 Marijn van Wezel
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use AuthenticationProvider\FacebookAuth;
use AuthenticationProvider\MediaWikiAuth;
use Exception\InvalidAuthProviderClassException;
use Exception\UnknownAuthProviderException;
use MediaWiki\MediaWikiServices;
/**
* Class WSOAuth
*/
class WSOAuth extends AuthProviderFramework {
const DEFAULT_AUTH_PROVIDERS = [
"mediawiki" => MediaWikiAuth::class,
"facebook" => FacebookAuth::class
];
/**
* @var AuthProvider
*/
private $auth_provider;
/**
* WSOAuth constructor.
* @throws FatalError
* @throws InvalidAuthProviderClassException
* @throws MWException
* @throws UnknownAuthProviderException
* @internal
*/
public function __construct() {
parent::__construct();
if ( $GLOBALS['wgOAuthUri'] !== false && $GLOBALS['wgOAuthClientId'] !== false && $GLOBALS['wgOAuthClientSecret'] !== false ) {
$this->auth_provider = self::getAuthProvider();
}
}
/**
* @param int &$id
* @param string &$username
* @param string &$realname
* @param string &$email
* @param string &$errorMessage
* @return bool
* @throws FatalError
* @throws MWException
* @internal
*/
public function authenticate( &$id, &$username, &$realname, &$email, &$errorMessage ) {
if ( !isset( $this->auth_provider ) ) {
$errorMessage = wfMessage( "wsoauth-not-configured-message" )->parse();
return false;
}
if ( $this->doesSessionVariableExist( "request_key" ) && $this->doesSessionVariableExist( "request_secret" ) ) {
$key = $this->getSessionVariable( "request_key" );
$secret = $this->getSessionVariable( "request_secret" );
$this->removeSessionVariable( "request_key" );
$this->removeSessionVariable( "request_secret" );
$user_info = $this->auth_provider->getUser( $key, $secret, $errorMessage );
$hook = Hooks::run( 'WSOAuthAfterGetUser', [ &$user_info, &$errorMessage ] );
// Request failed or user is not authorised.
if ( $user_info === false || $hook === false ) {
$errorMessage = !empty( $errorMessage ) ? $errorMessage : wfMessage( 'wsoauth-authentication-failure' )->plain();
return false;
}
$user_info['name'] = ucfirst( $user_info['name'] );
if ( !isset( $user_info['name'] ) ) {
$errorMessage = wfMessage( 'wsoauth-invalid-username' )->plain();
return false;
}
$services = MediaWikiServices::getInstance();
if ( method_exists( $services, 'getUserNameUtils' ) ) {
// MW 1.35 +
$isValidUsername = $services->getUserNameUtils()->isValid( $user_info['name'] );
} else {
$isValidUsername = User::isValidUserName( $user_info['name'] );
}
if ( !$isValidUsername ) {
$errorMessage = wfMessage( 'wsoauth-invalid-username' )->plain();
return false;
}
// Required.
$username = $user_info['name'];
$realname = isset( $user_info['realname'] ) ? $user_info['realname'] : '';
$email = isset( $user_info['email'] ) ? $user_info['email'] : '';
$user = User::newFromName( $username );
$user_id = $user->idForName();
$id = $user_id === 0 ? null : $user_id;
if ( $user_id !== null && $user_id > 0 && !$this->userLoggedInThroughOAuth( $user_id ) ) {
// The user exists and has not logged in through OAuth
if ( $GLOBALS['wgOAuthMigrateUsersByUsername'] === false ) {
$errorMessage = wfMessage( 'wsoauth-user-already-exists-message', $username )->plain();
return false;
}
// Usurp the account
$this->saveExtraAttributes( $user_id );
}
return true;
}
$result = $this->auth_provider->login( $key, $secret, $auth_url );
if ( $result === false || empty( $auth_url ) ) {
$errorMessage = wfMessage( 'wsoauth-initiate-login-failure' )->plain();
return false;
}
$this->setSessionVariable( 'request_key', $key );
$this->setSessionVariable( 'request_secret', $secret );
$this->saveSession();
header( "Location: $auth_url" );
exit;
}
/**
* @param User &$user
* @return void
* @throws FatalError
* @throws MWException
* @internal
*/
public function deauthenticate( User &$user ) {
Hooks::run( 'WSOAuthBeforeLogout', [ &$user ] );
$this->auth_provider->logout( $user );
}
/**
* @param int $id
* @return void
* @throws DBError
* @internal
*/
public function saveExtraAttributes( $id ) {
$dbr = wfGetDB( DB_MASTER );
$dbr->insert( 'wsoauth_users', [ 'wsoauth_user' => $id ] );
$this->auth_provider->saveExtraAttributes( $id );
}
/**
* Returns true if and only if the given ID exists in the table `wsoauth_users`.
*
* @param int $id
* @return bool Whether or not this user was registered by WSOAuth.
* @throws MWException
*/
private function userLoggedInThroughOAuth( $id ) {
if ( !is_int( $id ) ) { throw new MWException( "Given user ID is not an integer." );
}
$dbr = wfGetDB( DB_REPLICA );
return $dbr->numRows( $dbr->select(
'wsoauth_users',
[ 'wsoauth_user' ],
'wsoauth_user = ' . $id
) ) === 1;
}
/**
* Returns an instance of the configured auth provider.
*
* @return AuthProvider
* @throws FatalError
* @throws MWException
* @throws InvalidAuthProviderClassException
* @throws UnknownAuthProviderException
* @internal
*/
public static function getAuthProvider() {
$auth_providers = array_merge( self::getAuthProviders(), (array)$GLOBALS['wgOAuthCustomAuthProviders'] );
$auth_provider = $GLOBALS['wgOAuthAuthProvider'];
if ( !isset( $auth_providers[$auth_provider] ) ) {
throw new Exception\UnknownAuthProviderException( wfMessage( 'wsoauth-unknown-auth-provider-exception-message' )->params( $auth_provider )->plain() );
}
if ( !class_exists( $auth_providers[$auth_provider] ) ) {
throw new Exception\InvalidAuthProviderClassException( wfMessage( 'wsoauth-unknown-auth-provider-class-exception-message' )->plain() );
}
if ( !class_implements( $auth_providers[$auth_provider] ) ) {
throw new Exception\InvalidAuthProviderClassException( wfMessage( 'wsoauth-invalid-auth-provider-class-exception-message' )->plain() );
}
return new $auth_providers[$auth_provider]();
}
/**
* Returns the list of available auth providers.
*
* @return array
* @throws FatalError
* @throws MWException
*/
public static function getAuthProviders() {
$auth_providers = self::DEFAULT_AUTH_PROVIDERS;
Hooks::run( "WSOAuthGetAuthProviders", [ &$auth_providers ] );
return $auth_providers;
}
/**
* Adds the user to the groups defined via $wgOAuthAutoPopulateGroups after authentication.
*
* @param User $user
* @return bool
* @throws FatalError
* @throws MWException
* @internal
*/
public static function onPluggableAuthPopulateGroups( User $user ) {
$result = Hooks::run( 'WSOAuthBeforeAutoPopulateGroups', [ &$user ] );
if ( $result === false ) {
return false;
}
if ( !isset( $GLOBALS['wgOAuthAutoPopulateGroups'] ) ) {
return false;
}
if ( method_exists( MediaWikiServices::class, 'getUserGroupManager' ) ) {
// MW 1.35+
$effectiveGroups = MediaWikiServices::getInstance()->getUserGroupManager()
->getUserEffectiveGroups( $user );
} else {
$effectiveGroups = $user->getEffectiveGroups();
}
// Subtract the groups the user already has from the list of groups to populate.
$populate_groups = array_diff( (array)$GLOBALS['wgOAuthAutoPopulateGroups'], $effectiveGroups );
if ( method_exists( MediaWikiServices::class, 'getUserGroupManager' ) ) {
// MW 1.35+
$userGroupManager = MediaWikiServices::getInstance()->getUserGroupManager();
foreach ( $populate_groups as $populate_group ) {
$userGroupManager->addUserToGroup( $user, $populate_group );
}
} else {
foreach ( $populate_groups as $populate_group ) {
$user->addGroup( $populate_group );
}
}
return true;
}
/**
* Fired when MediaWiki is updated to allow WSOAuth to register updates for the database schema.
*
* @param DatabaseUpdater $updater
* @throws MWException
* @internal
*/
public static function onLoadExtensionSchemaUpdates( DatabaseUpdater $updater ) {
$directory = $GLOBALS['wgExtensionDirectory'] . '/WSOAuth/sql';
$type = $updater->getDB()->getType();
$sql_file = sprintf( "%s/%s/table_wsoauth_users.sql", $directory, $type );
if ( !file_exists( $sql_file ) ) {
throw new MWException( "WSOAuth does not support database type `$type`." );
}
$updater->addExtensionTable( 'wsoauth_users', $sql_file );
}
}