-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLitusAuthPlugin.php
More file actions
284 lines (233 loc) · 10.9 KB
/
LitusAuthPlugin.php
File metadata and controls
284 lines (233 loc) · 10.9 KB
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
<?php
/*
* Copyright (C) 2012 Litus <https://github.com/LitusProject>
*
* 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.
*/
if ( !defined( 'MEDIAWIKI' ) ) exit;
/* The Litus API Server to use for authentication */
$wgLitusAPIServer = '';
/* The API key */
$wgLitusAPIKey = '';
/* The Litus server itself, for login/logout links */
$wgLitusServer = '';
/* Required status to be allowed to log in */
$wgLitusRequiredStatus = array(
'anyone_can_enter' => false,
'university_status' => false,
'organization_status' => false,
'in_workinggroup_status' => false
);
/* The web page to redirect to if the user has an invalid status. */
$wgLitusInvalidStatusRedirect = false;
/* The callback page for the login */
$wgLitusLoginCallback = array(
'title' => 'Special:UserLogin',
'returnto' => 'Main+Page'
);
/* The cookie to use for authentication */
$wgLitusAuthCookie = 'Litus_Auth_Session';
/* Allow the user with this user ID to login regardless of university and organization status */
$wgLitusAdminUserid = false;
/**
* Add extension information to Special:Version
*/
$wgExtensionCredits['other'][] = array(
'path' => __FILE__,
'name' => 'Litus Authentication Plugin',
'version' => '0.2',
'author' => '[https://github.com/LitusProject The Litus Project]',
'description' => 'Automatic login using a Litus API server.',
'url' => 'https://github.com/LitusProject/MediaWikiAuth'
);
class LitusApi {
public static function isLitusCookiePresent() {
global $wgLitusAuthCookie;
return array_key_exists( $wgLitusAuthCookie, $_COOKIE );
}
private static function sendApiRequest( $url, $postData = array() ) {
global $wgLitusAPIServer;
global $wgLitusAPIKey;
global $wgLitusAuthCookie;
// if there's no session cookie, we can't be logged in, return false
if ( !self::isLitusCookiePresent() )
return false;
// add the API key and session cookie to the POST data
$postData['key'] = $wgLitusAPIKey;
$postData['session'] = $_COOKIE[$wgLitusAuthCookie];
//$result = Http::post( $wgLitusAPIServer . $url, array( 'postData' => $postData ) );
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $wgLitusAPIServer.$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
if ( preg_match( '/error/', $result ) )
return false;
return $result;
}
public static function getUserInfo() {
$json = self::sendApiRequest( '/auth/getPerson' );
if ( !$json )
return false;
return json_decode( $json );
}
}
/* add auto-auth hook */
$wgHooks['UserLoadFromSession'][] = 'fnLitusAuthFromSession';
/* Disable password reset */
$wgPasswordResetRoutes = false;
function fnLitusAuthFromSession( $user, &$result ) {
global $wgLanguageCode, $wgRequest, $wgOut;
global $wgLitusServer, $wgLitusRequiredStatus;
global $wgLitusLoginCallback, $wgServer, $wgScript;
global $wgLitusAdminUserid, $wgAuth, $wgMemc;
if ( isset( $_REQUEST['title'] ) ) {
$title = Title::newFromText( $wgRequest->getVal( 'title' ) );
if ( $title->isSpecial( 'Userlogin' ) ) {
$litusUser = LitusApi::getUserInfo();
if ( !$litusUser ) {
$returnto = $wgRequest->getVal( 'returnto' );
if ( ! $returnto )
$returnto = $wgLitusLoginCallback['returnto'];
$callback = 'https:' . $wgServer . $wgScript
. '?title=' . $wgLitusLoginCallback['title']
. '&returnto=' . $returnto;
header( 'Location: ' . $wgLitusServer . '/wiki/auth/login/redirect/' . urlencode( $callback ) );
exit();
}
// if not a valid status, redirect to page set by user
$validRequest = false;
if ($wgLitusRequiredStatus['anyone_can_enter'] !== false
&& true === $wgLitusRequiredStatus['anyone_can_enter'])
$validRequest = true;
elseif ( $wgLitusRequiredStatus['university_status'] !== false
&& $litusUser->university_status === $wgLitusRequiredStatus['university_status'] )
$validRequest = true;
elseif ( $wgLitusRequiredStatus['organization_status'] !== false
&& $litusUser->organization_status === $wgLitusRequiredStatus['organization_status'] )
$validRequest = true;
elseif ($wgLitusRequiredStatus['in_workinggroup_status'] !== false
&& $litusUser->in_workinggroup === $wgLitusRequiredStatus['in_workinggroup_status'] )
$validRequest = true;
if ( $wgLitusAdminUserid !== false && $litusUser->username === $wgLitusAdminUserid )
$validRequest = true;
if ( !$validRequest ) {
global $wgLitusInvalidStatusRedirect;
header( 'Location: ' . ( $wgLitusInvalidStatusRedirect !== false
? $wgLitusInvalidStatusRedirect
: $wgLitusServer ) );
exit();
}
$username = ucfirst( $litusUser->username );
$u = User::newFromName( $username );
// Create a new user if it's the first time this user logs in
if ( $u->getID() == 0 ) {
// Check if the user already logged in using the "old" username
$u2 = User::newFromName( ucfirst( $litusUser->full_name ) );
if ( $u2->getID() != 0 ) {
// if user already logged in with the old system, rename the user
$u = $u2;
$old = $litusUser->full_name;
$new = $username;
$uid = $u->getID();
// we should really use a job to make this faster, but this will
// run on the user being changed, which makes running a job quite
// impossible.
$dbw = wfGetDB( DB_MASTER );
$dbw->begin();
$dbw->update( 'user', // UPDATE user
// SET user_name="...", user_touched=...
array( 'user_name' => $new, 'user_touched' => $dbw->timestamp() ),
// WHERE user_name="..." AND user_id=...
array( 'user_id' => $uid ),
__METHOD__
);
if ( !$dbw->affectedRows() ) {
die( 'Failed to change username from ' . $old . ' to ' . $new . '.' );
}
// clear authentication tokens
$u = User::newFromId( $uid );
$authUser = $wgAuth->getUserInstance( $u );
$authUser->resetAuthToken();
// delete memcache entry (if used?)
$wgMemc->delete( wfMemcKey( 'user', 'id', $uid ) );
// Update ipblock list if this user has a block in there.
$dbw->update( 'ipblocks',
array( 'ipb_address' => $new ),
array( 'ipb_user' => $uid, 'ipb_address' => $old ),
__METHOD__
);
// Update this users block/rights log. Ideally, the logs would be historical,
// but it is really annoying when users have "clean" block logs by virtue of
// being renamed, which makes admin tasks more of a pain...
$oldTitle = Title::makeTitle( NS_USER, $old );
$newTitle = Title::makeTitle( NS_USER, $new );
$dbw->update( 'logging',
array( 'log_title' => $newTitle->getDBkey() ),
array( 'log_type' => array( 'block', 'rights' ),
'log_namespace' => NS_USER,
'log_title' => $oldTitle->getDBkey() ),
__METHOD__
);
// commit
$dbw->commit();
$wgAuth->updateExternalDB( $u );
} else { // $u2 does not exist
// if the user has never logged in before, create user
$u->addToDatabase();
$u->setRealName( $litusUser->full_name );
$u->setEmail( $litusUser->email );
// set emailauthenticated
$u->mEmailAuthenticated = wfTimestampNow();
// set the password to an unexisting md5 hash:
$u->setPassword( '*' );
$u->setToken();
$u->saveSettings();
$ssUpdate = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
$ssUpdate->doUpdate();
}
}
$u->setOption( 'rememberpassword', 1 );
$u->setCookies();
$user = $u;
// Redirect if a returnto parameter exists, else go to main page
$returnto = $wgRequest->getVal( 'returnto' );
$url = Title::newMainPage()->getFullUrl();
if ( $returnto ) {
$target = Title::newFromText( $returnto );
if ( $target ) {
// make sure we don't loop to logout
if ( $target->getNameSpace() != NS_SPECIAL )
$url = $target->getFullUrl();
}
}
// action=purge is used to purge the cache
$wgOut->redirect( $url . '?action=purge' );
} else if ( $title->isSpecial( 'Userlogout' ) ) {
$user->logout();
}
} else
die( 'Title not set...' );
return true;
}