-
Notifications
You must be signed in to change notification settings - Fork 988
/
authentication.php
376 lines (331 loc) · 12.4 KB
/
authentication.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
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
/*
* LimeSurvey
* Copyright (C) 2007-2011 The LimeSurvey Project Team / Carsten Schmitz
* All rights reserved.
* License: GNU/GPL License v2 or later, see LICENSE.php
* LimeSurvey is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*
* $Id$
*/
/**
* Authentication Controller
*
* This controller performs authentication
*
* @package LimeSurvey
* @subpackage Backend
*/
class Authentication extends Survey_Common_Action
{
/**
* Show login screen and parse login data
*/
public function index()
{
$this->_redirectIfLoggedIn();
$sIp = Yii::app()->request->getUserHostAddress();
$bCanLogin = $this->_userCanLogin($sIp);
if ($bCanLogin && !is_array($bCanLogin))
{
if (Yii::app()->request->getPost('action'))
{
$aData = $this->_doLogin(Yii::app()->request->getPost('user'), Yii::app()->request->getPost('password'));
if (!isset($aData['errormsg']))
{
Failed_login_attempts::model()->deleteAttempts($sIp);
$this->getController()->_GetSessionUserRights(Yii::app()->session['loginID']);
Yii::app()->session['just_logged_in'] = true;
Yii::app()->session['loginsummary'] = $this->_getSummary();
$this->_doRedirect();
die();
}
else
{
$this->_renderWrappedTemplate('authentication', 'error', $aData);
}
}
else
{
$this->_showLoginForm();
}
}
else
{
$this->_renderWrappedTemplate('authentication', 'error', $bCanLogin);
}
}
/**
* Logout user
*/
public function logout()
{
Yii::app()->user->logout();
$this->_showLoginForm($this->getController()->lang->gT('Logout successful.'));
}
/**
* Forgot Password screen
*/
public function forgotpassword()
{
$this->_redirectIfLoggedIn();
if (!Yii::app()->request->getPost('action'))
{
$this->_renderWrappedTemplate('authentication', 'forgotpassword');
}
else
{
$sUserName = Yii::app()->request->getPost('user');
$sEmailAddr = Yii::app()->request->getPost('email');
$aFields = User::model()->findAllByAttributes(array('users_name' => $sUserName, 'email' => $sEmailAddr));
if (count($aFields) < 1)
{
// wrong or unknown username and/or email
$aData['errormsg'] = $this->getController()->lang->gT('User name and/or email not found!');
$aData['maxattempts'] = '';
$this->_renderWrappedTemplate('authentication', 'error', $aData);
}
else
{
$aData['message'] = $this->_sendPasswordEmail($sEmailAddr, $aFields);
$this->_renderWrappedTemplate('authentication', 'message', $aData);
}
}
}
/**
* Send the forgot password email
*
* @param string $sEmailAddr
* @param array $aFields
*/
private function _sendPasswordEmail($sEmailAddr, $aFields)
{
$clang = $this->getController()->lang;
$sFrom = Yii::app()->getConfig('siteadminemail');
$sTo = $sEmailAddr;
$sSubject = $clang->gT('User data');
$sNewPass = createPassword();
$sSiteName = Yii::app()->getConfig('sitename');
$sSiteAdminBounce = Yii::app()->getConfig('siteadminbounce');
$username = sprintf($clang->gT('Username: %s'), $aFields[0]['users_name']);
$email = sprintf($clang->gT('Email: %s'), $sEmailAddr);
$password = sprintf($clang->gT('New password: %s'), $sNewPass);
$body = array();
$body[] = sprintf($clang->gT('Your user data for accessing %s'), Yii::app()->getConfig('sitename'));
$body[] = $username;
$body[] = $password;
$body = implode("\n", $body);
if (SendEmailMessage($body, $sSubject, $sTo, $sFrom, $sSiteName, false, $sSiteAdminBounce))
{
User::model()->updatePassword($aFields[0]['uid'], hash('sha256', $sNewPass));
$sMessage = $username . '<br />' . $email . '<br /><br />' . $clang->gT('An email with your login data was sent to you.');
}
else
{
$sTmp = str_replace("{NAME}", '<strong>' . $aFields[0]['users_name'] . '</strong>', $clang->gT("Email to {NAME} ({EMAIL}) failed."));
$sMessage = str_replace("{EMAIL}", $sEmailAddr, $sTmp) . '<br />';
}
return $sMessage;
}
/**
* Show login screen
* @param optional message
*/
protected function _showLoginForm($sLogoutSummary = '')
{
$aData['summary'] = $this->_getSummary('logout', $sLogoutSummary);
$this->_renderWrappedTemplate('authentication', 'login', $aData);
}
/**
* Get's the summary
* @param string $sMethod login|logout
* @param string $sSummary Default summary
* @return string Summary
*/
private function _getSummary($sMethod = 'login', $sSummary = '')
{
if (!empty($sSummary))
{
return $sSummary;
}
$clang = $this->getController()->lang;
switch ($sMethod) {
case 'logout' :
$sSummary = $clang->gT('You have to login first.');
break;
case 'login' :
default :
$sSummary = '<br />' . sprintf($clang->gT('Welcome %s!'), Yii::app()->session['full_name']) . '<br /> ';
if (!empty(Yii::app()->session['redirect_after_login']) && strpos(Yii::app()->session['redirect_after_login'], 'logout') === FALSE)
{
Yii::app()->session['metaHeader'] = '<meta http-equiv="refresh"'
. ' content="1;URL=' . Yii::app()->session['redirect_after_login'] . '" />';
$sSummary = '<p><font size="1"><i>' . $clang->gT('Reloading screen. Please wait.') . '</i></font>';
unset(Yii::app()->session['redirect_after_login']);
}
break;
}
return $sSummary;
}
/**
* Redirects a logged in user to the administration page
*/
private function _redirectIfLoggedIn()
{
if (!Yii::app()->user->getIsGuest())
{
Yii::app()->request->redirect($this->getController()->createUrl('/admin'));
}
}
/**
* Check if a user can log in
* @param string $sIp IP Address
* @return bool|array
*/
private function _userCanLogin($sIp = '')
{
if (empty($sIp))
{
$sIp = Yii::app()->request->getUserHostAddress();
}
$failed_login_attempts = Failed_login_attempts::model();
$failed_login_attempts->cleanOutOldAttempts();
if ($failed_login_attempts->isLockedOut($sIp))
{
return $this->_getAuthenticationFailedErrorMessage();
}
else
{
return true;
}
}
/**
* Redirect after login
*/
private function _doRedirect()
{
if (strlen(Yii::app()->session['redirectopage']) > 1)
{
Yii::app()->request->redirect(Yii::app()->session['redirectopage']);
}
else
{
Yii::app()->request->redirect($this->getController()->createUrl('/admin'));
}
}
/**
* Do the actual login work
* Note: This function is replicated in parts in remotecontrol.php controller - if you change this don't forget to make according changes there, too (which is why we should make a login helper)
* @param string $sUsername The username to login with
* @param string $sPassword The password to login with
* @return Array of data containing errors for the view
*/
private function _doLogin($sUsername, $sPassword)
{
$identity = new UserIdentity(sanitize_user($sUsername), $sPassword);
if (!$identity->authenticate())
{
return $this->_getAuthenticationFailedErrorMessage();
}
return $this->_setLoginSessions($identity);
}
/**
* Sets the login sessions
* @param UserIdentity $identity
* @return bool True
*/
private function _setLoginSessions($identity)
{
$user = $identity->getUser();
Yii::app()->user->login($identity);
$this->_checkForUsageOfDefaultPassword();
$this->_setSessionData($user);
$this->_setLanguageSettings($user);
return true;
}
/**
* Sets the session data
* @param CActiveRecord $user
*/
private function _setSessionData($user)
{
Yii::app()->session['loginID'] = (int) $user->uid;
Yii::app()->session['user'] = $user->users_name;
Yii::app()->session['full_name'] = $user->full_name;
Yii::app()->session['htmleditormode'] = $user->htmleditormode;
Yii::app()->session['templateeditormode'] = $user->templateeditormode;
Yii::app()->session['questionselectormode'] = $user->questionselectormode;
Yii::app()->session['dateformat'] = $user->dateformat;
Yii::app()->session['checksessionpost'] = randomChars(10);
}
/**
* Sets the language settings for the user
* @param CActiveRecord $user
*/
private function _setLanguageSettings($user)
{
if (Yii::app()->request->getPost('loginlang') !== 'default')
{
$user->lang = sanitize_languagecode(Yii::app()->request->getPost('loginlang'));
$user->save();
}
Yii::app()->session['adminlang'] = $user->lang;
$this->getController()->lang->limesurvey_lang(array('langcode' => $user->lang));
}
/**
* Checks if the user is using default password
*/
private function _checkForUsageOfDefaultPassword()
{
$clang = $this->getController()->lang;
Yii::app()->session['pw_notify'] = false;
if (strtolower($_POST['password']) === 'password')
{
Yii::app()->session['pw_notify'] = true;
Yii::app()->session['flashmessage'] = $clang->gT('Warning: You are still using the default password (\'password\'). Please change your password and re-login again.');
}
}
/**
* Get the authentication failed error messages
* @return array Data
*/
private function _getAuthenticationFailedErrorMessage()
{
$clang = $this->getController()->lang;
$aData = array();
$userHostAddress = Yii::app()->request->getUserHostAddress();
$bUserNotFound = Failed_login_attempts::model()->addAttempt($userHostAddress);
if ($bUserNotFound)
{
$aData['errormsg'] = $clang->gT('Incorrect username and/or password!');
$aData['maxattempts'] = '';
}
$bLockedOut = Failed_login_attempts::model()->isLockedOut($userHostAddress);
if ($bLockedOut)
{
$aData['maxattempts'] = sprintf(
$clang->gT('You have exceeded you maximum login attempts. Please wait %d minutes before trying again'),
Yii::app()->getConfig('timeOutTime') / 60
);
}
return $aData;
}
/**
* Renders template(s) wrapped in header and footer
*
* @param string $sAction Current action, the folder to fetch views from
* @param string|array $aViewUrls View url(s)
* @param array $aData Data to be passed on. Optional.
*/
protected function _renderWrappedTemplate($sAction = 'authentication', $aViewUrls = array(), $aData = array())
{
$aData['display']['menu_bars'] = false;
parent::_renderWrappedTemplate($sAction, $aViewUrls, $aData);
}
}