Skip to content

Commit

Permalink
Dev Refactorred authentication controller _doLogin as GCI refactor ex…
Browse files Browse the repository at this point in the history
…ample

git-svn-id: file:///Users/Shitiz/Downloads/lssvn/source/limesurvey_yii@11673 b72ed6b6-b9f8-46b5-92b4-906544132732
  • Loading branch information
Pieter Jan Speelmans committed Dec 17, 2011
1 parent d8be800 commit 5f575e6
Showing 1 changed file with 139 additions and 141 deletions.
280 changes: 139 additions & 141 deletions application/controllers/admin/authentication.php
Expand Up @@ -19,33 +19,33 @@
*
* This controller performs authentication
*
* @package LimeSurvey
* @subpackage Backend
* @package LimeSurvey
* @subpackage Backend
*/

class Authentication extends CAction
{
/**
* Executes the action based on given input
*
* @access public
* @return void
*/
public function run()
{
if (isset($_GET['login']))
$this->login();
elseif (isset($_GET['logout']))
$this->logout();
elseif (isset($_GET['forgotpassword']))
$this->forgotpassword();
else
$this->index();
}
/**
* Executes the action based on given input
*
* @access public
* @return void
*/
public function run()
{
if (isset($_GET['login']))
$this->login();
elseif (isset($_GET['logout']))
$this->logout();
elseif (isset($_GET['forgotpassword']))
$this->forgotpassword();
else
$this->index();
}

/**
* Default Controller Action
*
* Default Controller Action
*
* @access public
* @return void
*/
Expand All @@ -63,7 +63,7 @@ public function login()
{
$sIp = Yii::app()->request->getUserHostAddress();

$failed_login_attempts = Failed_login_attempts::model();
$failed_login_attempts = Failed_login_attempts::model();
$failed_login_attempts->cleanOutOldAttempts();

$bCannotLogin = $failed_login_attempts->isLockedOut($sIp);
Expand All @@ -81,16 +81,16 @@ public function login()
else
{
$failed_login_attempts->deleteAttempts($sIp);
$loginsummary = "<br />".sprintf($clang->gT("Welcome %s!"), Yii::app()->session['full_name'])."<br />&nbsp;";
if (!empty(Yii::app()->session['redirect_after_login']) && strpos(Yii::app()->session['redirect_after_login'], "logout") === FALSE)
$loginsummary = '<br />' . sprintf($clang->gT('Welcome %s!'), Yii::app()->session['full_name']) . '<br />&nbsp;';
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']."\" />";
$loginsummary = "<p><font size='1'><i>".$clang->gT("Reloading screen. Please wait.")."</i></font>\n";
Yii::app()->session['metaHeader'] = '<meta http-equiv="refresh"'
. ' content="1;URL=' . Yii::app()->session['redirect_after_login'].'" />';
$loginsummary = '<p><font size="1"><i>' . $clang->gT('Reloading screen. Please wait.') . '</i></font>\n';
unset(Yii::app()->session['redirect_after_login']);
}
$this->getController()->_GetSessionUserRights(Yii::app()->session['loginID']);
Yii::app()->session['just_logged_in'] = true;
Yii::app()->session['just_logged_in'] = true;
Yii::app()->session['loginsummary'] = $loginsummary;
$this->getController()->redirect($this->getController()->createUrl('/admin'));
}
Expand All @@ -102,12 +102,11 @@ public function login()
{
// wrong or unknown username
$data['errormsg']="";
$data['maxattempts'] = sprintf($this->getController()->lang->gT("You have exceeded you maximum login attempts. Please wait %d minutes before trying again"),(Yii::app()->getConfig("timeOutTime")/60))."<br />";
$data['clang'] = $this->getController()->lang;
$data['maxattempts'] = sprintf(
$this->getController()->lang->gT('You have exceeded you maximum login attempts. Please wait %d minutes before trying again'),
(Yii::app()->getConfig("timeOutTime")/60)) . '<br />';

$this->getController()->_getAdminHeader();
$this->getController()->render('/admin/authentication/error', $data);
$this->getController()->_getAdminFooter("http://docs.limesurvey.org", $data['clang']->gT("LimeSurvey online manual"));
$this->_renderTemplateWrappedInHeaderAndFooter('/admin/authentication/error', $data);
}
}
else
Expand All @@ -122,47 +121,36 @@ public function login()
public function logout()
{
Yii::app()->user->logout();
$this->_showLoginForm('<p>'.$this->getController()->lang->gT("Logout successful."));
$this->_showLoginForm('<p>'.$this->getController()->lang->gT('Logout successful.'));
}

/**
* Forgot Password screen
*/
public function forgotpassword()
{

$clang = Yii::app()->lang;
if(!(isset($_POST["action"])))
$clang = $this->getController()->lang;
if(!CHttpRequest::getPost('action'))
{
$data['clang'] = Yii::app()->lang;
$this->getController()->_getAdminHeader();
$this->getController()->render("/admin/authentication/forgotpassword", $data);
$this->getController()->_getAdminFooter("http://docs.limesurvey.org", Yii::app()->lang->gT("LimeSurvey online manual"));
$this->_renderTemplateWrappedInHeaderAndFooter("/admin/authentication/forgotpassword");
}
else
{

$postuser = $_POST["user"];
$emailaddr = $_POST["email"];

$postuser = CHttpRequest::getPost('user');
$emailaddr = CHttpRequest::getPost('email');

//$query = "SELECT users_name, password, uid FROM ".db_table_name('users')." WHERE users_name=".$connect->qstr($postuser)." AND email=".$connect->qstr($emailaddr);
//$result = db_select_limit_assoc($query, 1) or safe_die ($query."<br />".$connect->ErrorMsg()); // Checked
$query = User::model()->getSomeRecords(array("users_name, password, uid"),array("users_name"=>$postuser,"email"=>$emailaddr));

if (count($query) < 1)
{
// wrong or unknown username and/or email
$data['errormsg']=Yii::app()->lang->gT("User name and/or email not found!");
$data['errormsg'] = $this->getController()->lang->gT("User name and/or email not found!");
$data['maxattempts']="";
$data['clang']=Yii::app()->lang;

$this->getController()->_getAdminHeader();
$this->getController()->render("/admin/authentication/error", $data);
$this->getController()->_getAdminFooter("http://docs.limesurvey.org", Yii::app()->lang->gT("LimeSurvey online manual"));
$this->_renderTemplateWrappedInHeaderAndFooter("/admin/authentication/error", $data);

}
else
{
} else {
//$fields = $result->FetchRow();
$fields = $query;

Expand All @@ -182,129 +170,139 @@ public function forgotpassword()
//$query = "UPDATE ".db_table_name('users')." SET password='".SHA256::hashing($new_pass)."' WHERE uid={$fields['uid']}";
//$connect->Execute($query); //Checked
User::model()->updatePassword($fields[0]['uid'], hash('sha256', $new_pass));
$data['clang'] = $clang;
$data['message'] = "<br />".$clang->gT("Username").": {$fields[0]['users_name']}<br />".$clang->gT("Email").": {$emailaddr}<br />
<br />".$clang->gT("An email with your login data was sent to you.");
$this->getController()->_getAdminHeader();
$this->getController()->render('/admin/authentication/message', $data);
$this->getController()->_getAdminFooter("http://docs.limesurvey.org", Yii::app()->lang->gT("LimeSurvey online manual"));
$data['message'] = '<br />' . $clang->gT("Username") . ': ' . $fields[0]['users_name'] . '<br />' . $clang->gT("Email") . ': ' . $emailaddr . '<br />
<br />' . $clang->gT('An email with your login data was sent to you.');
$this->_renderTemplateWrappedInHeaderAndFooter('/admin/authentication/message', $data);
}
else
{
$tmp = str_replace("{NAME}", "<strong>".$fields[0]['users_name']."</strong>", $clang->gT("Email to {NAME} ({EMAIL}) failed."));
$data['clang'] = $clang;
$data['message'] = "<br />".str_replace("{EMAIL}", $emailaddr, $tmp) . "<br />";

$this->getController()->_getAdminHeader();
$this->getController()->render('/admin/authentication/message', $data);
$this->getController()->_getAdminFooter("http://docs.limesurvey.org", Yii::app()->lang->gT("LimeSurvey online manual"));
$tmp = str_replace("{NAME}", "<strong>" . $fields[0]['users_name'] . "</strong>", $clang->gT("Email to {NAME} ({EMAIL}) failed."));
$data['message'] = '<br />' . str_replace("{EMAIL}", $emailaddr, $tmp) . '<br />';
$this->_renderTemplateWrappedInHeaderAndFooter('/admin/authentication/message', $data);
}
}
}

}

/**
* Show login screen
* @param optional message
*/
protected function _showLoginForm($logoutsummary="")
protected function _showLoginForm( $logoutSummary = '' )
{
$data['clang'] = $this->getController()->lang;

if ($logoutsummary=="")
if ($logoutSummary === '' )
{
$data['summary'] = $this->getController()->lang->gT("You have to login first.");
$data['summary'] = $this->getController()->lang->gT('You have to login first.');
}
else
{
$data['summary'] = $logoutsummary;
$data['summary'] = $logoutSummary;
}
$this->_renderTemplateWrappedInHeaderAndFooter('/admin/authentication/login', $data);
}

$this->getController()->_getAdminHeader();
$this->getController()->render('/admin/authentication/login', $data);
$this->getController()->_getAdminFooter("http://docs.limesurvey.org", $this->getController()->lang->gT("LimeSurvey online manual"));
/**
* 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();
}
else
{
return $this->_setLoginSessions($identity);
}
}

/**
* 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
* @param string $sUsername The username to login with
* @param string $sPassword The password to login with
*/
protected function _doLogin($sUsername, $sPassword)
private function _setLoginSessions($identity)
{
$clang = $this->getController()->lang;
$sUsername = sanitize_user($sUsername);
$user = $identity->getUser();

$identity = new UserIdentity($sUsername, $sPassword);
Yii::app()->user->login($identity);
$this->_checkForUsageOfDefaultPassword();
$this->_setSessionData($user);
$this->_setLanguageSettings($user);

if (!$identity->authenticate())
return true;
}

private function _setSessionData($user)
{
Yii::app()->session['loginID'] = intval($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'] = sRandomChars(10);
}

private function _setLanguageSettings($user)
{
if (isset($_POST['loginlang']) && $_POST['loginlang'] !== 'default')
{
$query = Failed_login_attempts::model()->addAttempt(Yii::app()->request->getUserHostAddress());
$user->lang = sanitize_languagecode($_POST['loginlang']);
$user->save();
}

if ($query)
{
// wrong or unknown username
$data['errormsg']=$clang->gT("Incorrect username and/or password!");
$data['maxattempts']="";
if (Failed_login_attempts::model()->isLockedOut(Yii::app()->request->getUserHostAddress()))
$data['maxattempts']=sprintf($clang->gT("You have exceeded you maximum login attempts. Please wait %d minutes before trying again"),(Yii::app()->getConfig("timeOutTime")/60))."<br />";
Yii::app()->session['adminlang'] = $user->lang;
$this->getController()->lang->limesurvey_lang(array('langcode' => $user->lang));
}

$data['clang']=$clang;
return $data;
}
private function _checkForUsageOfDefaultPassword()
{
$clang = $this->getController()->lang;
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.');
}
// Log the user in
else
{
$user = $identity->getUser();
Yii::app()->session['pw_notify'] = false;
}
}

Yii::app()->user->login($identity);
private function _getAuthenticationFailedErrorMessage()
{
$clang = $this->getController()->lang;
$data = array();
$userHostAddress = Yii::app()->request->getUserHostAddress();
$isUserNotFound = Failed_login_attempts::model()->addAttempt($userHostAddress);

// Check if the user has changed his default password
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.");
}
else
Yii::app()->session['pw_notify'] = false;

$session_data = array(
'loginID' => intval($user->uid),
'user' => $user->users_name,
'full_name' => $user->full_name,
'htmleditormode' => $user->htmleditormode,
'templateeditormode' => $user->templateeditormode,
'questionselectormode' => $user->questionselectormode,
'dateformat' => $user->dateformat,
// Compute a checksession random number to test POSTs
'checksessionpost' => sRandomChars(10)
);

foreach ($session_data as $k => $v)
Yii::app()->session[$k] = $v;

$postloginlang = sanitize_languagecode($_POST['loginlang']);
if (isset($postloginlang) && $postloginlang != 'default')
{
Yii::app()->session['adminlang'] = $postloginlang;
$this->getController()->lang->limesurvey_lang(array("langcode"=>$postloginlang));
$clang = $this->getController()->lang;
if ( $isUserNotFound )
{
$data['errormsg'] = $clang->gT('Incorrect username and/or password!');
$data['maxattempts'] = '';

$user->lang = $postloginlang;
$user->save();
}
else
{
Yii::app()->session['adminlang'] = $user->lang;
$isLockedOut = Failed_login_attempts::model()->isLockedOut($userHostAddress);

$this->getController()->lang->limesurvey_lang(array("langcode"=>$user->lang));
$clang = $this->getController()->lang;
if ( $isLockedOut )
{
$data['maxattempts'] = sprintf(
$clang->gT('You have exceeded you maximum login attempts. Please wait %d minutes before trying again'),
Yii::app()->getConfig('timeOutTime') / 60
);
}
return true;
}

return $data;
}

private function _renderTemplateWrappedInHeaderAndFooter($szViewUrl, $data = NULL)
{
$clang = $this->getController()->lang;
$data['clang'] = $clang;
$this->getController()->_getAdminHeader();
$this->getController()->render($szViewUrl, $data);
$this->getController()->_getAdminFooter('http://docs.limesurvey.org', $clang->gT('LimeSurvey online manual'));
}
}

0 comments on commit 5f575e6

Please sign in to comment.