/** * Display profile start page */ public function actionIndex() { Yii::import('application.modules.users.forms.ChangePasswordForm'); $request = Yii::app()->request; $user = Yii::app()->user->getModel(); $profile = $user->profile; $changePasswordForm = new ChangePasswordForm(); $changePasswordForm->user = $user; if (Yii::app()->request->isPostRequest) { if ($request->getPost('UserProfile') || $request->getPost('User')) { $profile->attributes = $request->getPost('UserProfile'); $user->email = isset($_POST['User']['email']) ? $_POST['User']['email'] : null; $valid = $profile->validate(); $valid = $user->validate() && $valid; if ($valid) { $user->save(); $profile->save(); $this->addFlashMessage(Yii::t('UsersModule.core', 'Изменения успешно сохранены.')); $this->refresh(); } } if ($request->getPost('ChangePasswordForm')) { $changePasswordForm->attributes = $request->getPost('ChangePasswordForm'); if ($changePasswordForm->validate()) { $user->password = User::encodePassword($changePasswordForm->new_password); $user->save(false); $this->addFlashMessage(Yii::t('UsersModule.core', 'Пароль успешно изменен.')); $this->refresh(); } } } $this->render('index', array('user' => $user, 'profile' => $profile, 'changePasswordForm' => $changePasswordForm)); }
public function run() { $this->controller->layout = 'admin'; $form = new ChangePasswordForm(); if (!empty($_POST['ChangePasswordForm']) && is_array($_POST['ChangePasswordForm'])) { $form->attributes = $_POST['ChangePasswordForm']; if ($form->validate()) { $loggedUser = Yii::app()->user; /* * Save new password. */ $user = User::model()->findByAttributes(array('username' => $loggedUser->name)); if ($user === null) { throw new CException('User not found.'); } $user->password = md5($form->newPassword); $user->save(); $loggedUser->setFlash('generalMessage', 'New password was set successfully.'); $this->controller->refresh(); } else { $form->currentPassword = ''; $form->newPassword = ''; $form->newPasswordConfirm = ''; } } $this->controller->render('changePassword', array('form' => $form)); }
/** * Стартуем экшен сброса пароля * @param string $token - токен-сброса пароля * @throws CHttpException */ public function run($token) { if (Yii::app()->user->isAuthenticated()) { $this->controller->redirect(Yii::app()->user->returnUrl); } $module = Yii::app()->getModule('user'); // Если запрещено восстановление - печалька ;) if ($module->recoveryDisabled) { throw new CHttpException(404, Yii::t('UserModule.user', 'requested page was not found!')); } // Если включено автоматическое восстановление пароля: if ((int) $module->autoRecoveryPassword === WebModule::CHOICE_YES) { if (Yii::app()->userManager->activatePassword($token)) { Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('UserModule.user', 'New password was sent to your email')); $this->controller->redirect(array('/user/account/backendlogin')); } else { Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::ERROR_MESSAGE, Yii::t('UserModule.user', 'Error when changing password!')); $this->controller->redirect(array('/user/account/recovery')); } } // Форма смены пароля: $changePasswordForm = new ChangePasswordForm(); // Получаем данные POST если таковые имеются: if (($data = Yii::app()->getRequest()->getPost('ChangePasswordForm')) !== null) { $changePasswordForm->setAttributes($data); // Проводим валидацию формы: if ($changePasswordForm->validate() && Yii::app()->userManager->activatePassword($token, $changePasswordForm->password)) { Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('UserModule.user', 'Password recover successfully')); $this->controller->redirect(array('/user/account/backendlogin')); } } // Отрисовываем форму: $this->controller->render('changePassword', array('model' => $changePasswordForm)); }
/** * Redirect the user to the change password form. * * @return SS_HTTPResponse */ protected function redirectToChangePassword() { // Since this form is loaded via an iframe, this redirect must be performed via javascript $changePasswordForm = new ChangePasswordForm($this->controller, 'ChangePasswordForm'); $changePasswordForm->sessionMessage(_t('Member.PASSWORDEXPIRED', 'Your password has expired. Please choose a new one.'), 'good'); // Get redirect url $changePasswordURL = $this->getExternalLink('changepassword'); if ($backURL = $this->controller->getRequest()->requestVar('BackURL')) { Session::set('BackURL', $backURL); $changePasswordURL = Controller::join_links($changePasswordURL, '?BackURL=' . urlencode($backURL)); } $changePasswordURLATT = Convert::raw2att($changePasswordURL); $changePasswordURLJS = Convert::raw2js($changePasswordURL); $message = _t('CMSMemberLoginForm.PASSWORDEXPIRED', '<p>Your password has expired. <a target="_top" href="{link}">Please choose a new one.</a></p>', 'Message displayed to user if their session cannot be restored', array('link' => $changePasswordURLATT)); // Redirect to change password page $this->controller->getResponse()->setStatusCode(200); $this->controller->getResponse()->setBody(<<<PHP <!DOCTYPE html> <html><body> {$message} <script type="application/javascript"> setTimeout(function(){top.location.href = "{$changePasswordURLJS}";}, 0); </script> </body></html> PHP ); return $this->controller->getResponse(); }
public function run($code) { $recovery = RecoveryPassword::model()->with('user')->find('code = :code', array(':code' => $code)); if (!$recovery) { Yii::log(Yii::t('user', 'Код восстановления пароля {code} не найден!', array('{code}' => $code)), CLogger::LEVEL_ERROR, UserModule::$logCategory); Yii::app()->user->setFlash(YFlashMessages::ERROR_MESSAGE, Yii::t('user', 'Код восстановления пароля не найден! Попробуйте еще раз!')); $this->controller->redirect(array('/user/account/recovery')); } // автоматическое восстановление пароля if (Yii::app()->getModule('user')->autoRecoveryPassword) { $newPassword = Registration::model()->generateRandomPassword(); $recovery->user->password = Registration::model()->hashPassword($newPassword, $recovery->user->salt); $transaction = Yii::app()->db->beginTransaction(); try { if ($recovery->user->save() && RecoveryPassword::model()->deleteAll('user_id = :user_id', array(':user_id' => $recovery->user->id))) { $transaction->commit(); $emailBody = $this->controller->renderPartial('application.modules.user.views.email.passwordAutoRecoverySuccessEmail', array('model' => $recovery->user, 'password' => $newPassword), true); Yii::app()->mail->send(Yii::app()->getModule('user')->notifyEmailFrom, $recovery->user->email, Yii::t('user', 'Успешное восстановление пароля!'), $emailBody); Yii::app()->user->setFlash(YFlashMessages::NOTICE_MESSAGE, Yii::t('user', 'Новый пароль отправлен Вам на email!')); Yii::log(Yii::t('user', 'Успешное восстановление пароля!'), CLogger::LEVEL_ERROR, UserModule::$logCategory); $this->controller->redirect(array('/user/account/login')); } } catch (CDbException $e) { $transaction->rollback(); Yii::app()->user->setFlash(YFlashMessages::ERROR_MESSAGE, Yii::t('user', 'Ошибка при смене пароля!')); Yii::log(Yii::t('user', 'Ошибка при автоматической смене пароля {error}!', array('{error}' => $e->getMessage())), CLogger::LEVEL_ERROR, UserModule::$logCategory); $this->controller->redirect(array('/user/account/recovery')); } } // выбор своего пароля $changePasswordForm = new ChangePasswordForm(); // если отправили фому с новым паролем if (Yii::app()->request->isPostRequest && isset($_POST['ChangePasswordForm'])) { $changePasswordForm->setAttributes($_POST['ChangePasswordForm']); if ($changePasswordForm->validate()) { $transaction = Yii::app()->db->beginTransaction(); try { // смена пароля пользователя $recovery->user->password = Registration::model()->hashPassword($changePasswordForm->password, $recovery->user->salt); // удалить все запросы на восстановление для данного пользователя if ($recovery->user->save() && RecoveryPassword::model()->deleteAll('user_id = :user_id', array(':user_id' => $recovery->user->id))) { $transaction->commit(); Yii::app()->user->setFlash(YFlashMessages::NOTICE_MESSAGE, Yii::t('user', 'Пароль изменен!')); Yii::log(Yii::t('user', 'Успешная смена пароля для пользоателя {user}!', array('{user}' => $recovery->user->id)), CLogger::LEVEL_INFO, UserModule::$logCategory); $emailBody = $this->controller->renderPartial('application.modules.user.views.email.passwordRecoverySuccessEmail', array('model' => $recovery->user), true); Yii::app()->mail->send(Yii::app()->getModule('user')->notifyEmailFrom, $recovery->user->email, Yii::t('user', 'Успешное восстановление пароля!'), $emailBody); $this->controller->redirect(array('/user/account/login')); } } catch (CDbException $e) { $transaction->rollback(); Yii::app()->user->setFlash(YFlashMessages::ERROR_MESSAGE, Yii::t('user', 'Ошибка при смене пароля!')); Yii::log(Yii::t('Ошибка при смене пароля {error}!', array('{error}' => $e->getMessage())), CLogger::LEVEL_ERROR, UserModule::$logCategory); $this->controller->redirect(array('/user/account/recovery')); } } } $this->controller->render('changePassword', array('model' => $changePasswordForm)); }
public function testCheckCurrentPassword() { $model = new ChangePasswordForm(); $model->currentPassword = 12345; $userIdentity = new UserIdentity('*****@*****.**', md5(12345)); $duration = 0; //Yii::app()->user->login($userIdentity, $duration); Yii::app()->user->id = 1; $this->assertTrue($model->checkCurrentPassword('arg1', 'arg2')); //Yii::app()->user->logout(); }
/** * Экшен смены пароля: * * @param int $id - record ID * * @return void */ public function actionChangepassword($id) { $model = $this->loadModel($id); $form = new ChangePasswordForm(); if (($data = Yii::app()->getRequest()->getPost('ChangePasswordForm')) !== null) { $form->setAttributes($data); if ($form->validate() && Yii::app()->userManager->changeUserPassword($model, $form->password)) { Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('UserModule.user', 'Пароль успешно изменен!')); $this->redirect(Yii::app()->user->getState('prevUrl')); } } $this->render('changepassword', array('model' => $model, 'changePasswordForm' => $form)); }
/** * Экшен смены пароля: * * @param int $id - record ID * * @return void */ public function actionChangepassword($id) { $model = $this->loadModel($id); $form = new ChangePasswordForm(); if (($data = Yii::app()->getRequest()->getPost('ChangePasswordForm')) !== null) { $form->setAttributes($data); if ($form->validate() && Yii::app()->userManager->changeUserPassword($model, $form->password)) { Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('UserModule.user', 'Password was changed successfully')); $this->redirect(array('/user/userBackend/view', 'id' => $model->id)); } } $this->render('changepassword', array('model' => $model, 'changePasswordForm' => $form)); }
public function actionChangepassword($id) { $model = $this->loadModel(); $form = new ChangePasswordForm(); if (Yii::app()->request->isPostRequest && !empty($_POST['ChangePasswordForm'])) { $form->setAttributes($_POST['ChangePasswordForm']); if ($form->validate() && $model->changePassword($form->password)) { $model->changePassword($form->password); Yii::app()->user->setFlash(YFlashMessages::NOTICE_MESSAGE, Yii::t('user', 'Пароль успешно изменен!')); $this->redirect(array('/user/default/view/', 'id' => $model->id)); } } $this->render('changepassword', array('model' => $model, 'changePasswordForm' => $form)); }
/** * Provides ability to change password and email address. * If user want to change email it will be changed after confirmation of * new email address. * * @throws CException */ public function actionEdit() { $identity = Identity::model()->findByAttributes(array('user_id' => Yii::app()->user->id)); $newPassword = new ChangePasswordForm(); if ($this->request->isPostRequest) { if ($identity->identity !== $_POST['Identity']['identity']) { $newEmail = $_POST['Identity']['identity']; $storedIdentity = clone $identity; $identity->identity = $newEmail; } $newPassword->attributes = $_POST['ChangePasswordForm']; $isFormValid = $newPassword->validate(); if ($isFormValid && $newEmail) { $isFormValid = $identity->validate(); } if ($isFormValid && isset($newEmail)) { $identity->status = Identity::STATUS_NEED_CONFIRMATION; $identity->isNewRecord = true; $identity->id = null; $identity->save(); $confirmation = $identity->startConfirmation(IdentityConfirmation::TYPE_EMAIL_REPLACE_CONFIRMATION); $activationUrl = $this->createAbsoluteUrl($this->module->confirmationUrl, array('key' => $confirmation->key)); $email = new YiiMailer('changeEmail', $data = array('activationUrl' => $activationUrl, 'description' => $description = 'Email change confirmation')); $email->setSubject($description); $email->setTo($identity->identity); $email->setFrom(Yii::app()->params['noreplyAddress'], Yii::app()->name, FALSE); Yii::log('Sendign email change confirmation to ' . $identity->identity . ' with data: ' . var_export($data, true)); // @TODO: catch mailing exceptions here, to give user right messages if ($email->send()) { Yii::log('Ok'); } else { Yii::log('Failed'); throw new CException('Failed to send the email'); } Yii::app()->user->setFlash('info', 'Your new email will be applied after confirmation. Please, check this email address ' . $newEmail . '. You should get confirmation mail there.'); } if ($isFormValid) { $user = $identity->userAccount; if ($newPassword->password && !$user->passwordEquals($newPassword->password)) { $user->setPassword($newPassword->password); $user->save(); Yii::app()->user->setFlash('success', 'Password has been changed successfully'); } } if ($isFormValid) { $this->redirect(array($this->module->afterIdentityEditedUrl)); } } $this->render('edit', array('identity' => $identity, 'newPassword' => $newPassword)); }
public function run() { $formModel = new ChangePasswordForm(); if (isset($_POST['ChangePasswordForm'])) { $formModel->attributes = $_POST['ChangePasswordForm']; if ($formModel->validate()) { $user = User::model()->findByPk(Yii::app()->user->getId()); $user->password = md5($formModel->password); $user->save(false); Utility::setFlash('Password changed successfully.', 'success'); } } $this->getController()->render('change_password', array('formModel' => $formModel)); }
public function actionChangePassword() { $changePasswordForm = new ChangePasswordForm(); if (($post = Yii::app()->getRequest()->getPost('ChangePasswordForm')) !== null) { $changePasswordForm->attributes = $post; if ($changePasswordForm->process()) { $this->redirect(Yii::app()->getRequest()->getUrlReferrer()); } } if (Yii::app()->getRequest()->getIsAjaxRequest()) { $this->renderPartial('changePassword', array('form' => $changePasswordForm)); } else { $this->render('changePassword', array('form' => $changePasswordForm)); } }
public function actionIndex() { $model = new ChangePasswordForm(); if (isset($_POST['ChangePasswordForm'])) { $model->setAttributes($_POST['ChangePasswordForm']); if ($model->validate()) { if ($model->changePassword()) { user()->setFlash(FlashConst::MESSAGE_SUCCESS, Yii::t('main', 'Пароль успешно изменен.')); $this->refresh(); } else { user()->setFlash(FlashConst::MESSAGE_ERROR, Yii::t('main', 'Произошла ошибка! Попробуйте повторить позже.')); } } } $this->render('//cabinet/change-password', array('model' => $model)); }
protected function logInUserAndRedirect($data) { Session::clear('SessionForms.MemberLoginForm.Email'); Session::clear('SessionForms.MemberLoginForm.Remember'); if (Member::currentUser()->isPasswordExpired()) { if (isset($_REQUEST['BackURL']) && ($backURL = $_REQUEST['BackURL'])) { Session::set('BackURL', $backURL); } $cp = new ChangePasswordForm($this->controller, 'ChangePasswordForm'); $cp->sessionMessage(_t('Member.PASSWORDEXPIRED', 'Your password has expired. Please choose a new one.'), 'good'); return $this->controller->redirect('Security/changepassword'); } // Absolute redirection URLs may cause spoofing if (!empty($_REQUEST['BackURL'])) { $url = $_REQUEST['BackURL']; if (Director::is_site_url($url)) { $url = Director::absoluteURL($url); } else { // Spoofing attack, redirect to homepage instead of spoofing url $url = Director::absoluteBaseURL(); } return $this->controller->redirect($url); } // If a default login dest has been set, redirect to that. if ($url = Security::config()->default_login_dest) { $url = Controller::join_links(Director::absoluteBaseURL(), $url); return $this->controller->redirect($url); } // Redirect the user to the page where they came from $member = Member::currentUser(); if ($member) { $firstname = Convert::raw2xml($member->FirstName); if (!empty($data['Remember'])) { Session::set('SessionForms.MemberLoginForm.Remember', '1'); $member->logIn(true); } else { $member->logIn(); } Session::set('Security.Message.message', _t('Member.WELCOMEBACK', "Welcome Back, {firstname}", array('firstname' => $firstname))); Session::set("Security.Message.type", "good"); } // Do checks of pagetypes to see where we were and where to go then for the rest redirect to baseurl // $url = "/resources/"; $url = "/resources/"; $url = Controller::join_links(Director::absoluteBaseURL(), $url); return $this->controller->redirect($url); }
/** * Action ChangePassword dùng để đổi mật khẩu cho user khi user quên mật khẩu với điều kiện user click url được gửi trong email */ public function actionChangePassword() { // Validate Code forgot password if (isset($_GET['code']) && isset($_GET['email'])) { $strForgotPasswordCode = $_GET['code']; $strEmail = $_GET['email']; $user = User::model()->notsafe()->findByAttributes(array('email' => $strEmail)); if (isset($user)) { // Check Code if ($strForgotPasswordCode == $user->activkey) { $model = new ChangePasswordForm(); // Submit form if (isset($_POST['ChangePasswordForm'])) { $model->attributes = $_POST['ChangePasswordForm']; // Validate new password if ($model->validate()) { // Create new Pasword $user->encryptPassword($model->password); // Delete forgot code in DB $user->activkey = $user->createCodeActivation(); // Save new password to DB if ($user->save()) { } /** * @todo Change message email */ $strMsgHTML = "Recovery Password Success"; Yii::import('application.extensions.phpmailer.HMailHelper'); HMailHelper::Send('Recovery Password', $strMsgHTML, array(array($user->email, $user->username))); // Notice Recovery Password success $this->setRedirectOptions(array("title" => UserModule::t('Recovery Password Success'), "message" => UserModule::t('The recovery password was successful!'))); $this->redirect(Yii::app()->user->loginUrl); } } $this->render('changepassword', array('model' => $model)); Yii::app()->end(); } else { // Notice recovery password failure $this->setRedirectOptions(array("title" => UserModule::t('Recovery Password Failure'), "message" => UserModule::t('Incorrect recovery URL or Recovery period has expired!'))); $this->redirect("/"); } } } // Notice recovery password failure $this->setRedirectOptions(array("title" => UserModule::t('Recovery Password Failure'), "message" => UserModule::t('Incorrect recovery URL!'))); $this->redirect("/"); }
public function actionChangePassword() { $model = new ChangePasswordForm(); if (isset($_POST['ChangePasswordForm'])) { $model->attributes = $_POST['ChangePasswordForm']; if ($model->validate()) { //change password $user = User::model()->findByPk(Yii::app()->user->id); $user->password = $user->createHash($model->password); $user->save(); //inform user $this->render('message', array('title' => 'Password Changed', 'message' => 'You have successfully changed your password.')); return; } } $this->render('changePassword', array('model' => $model)); }
/** * Updates a password */ public function actionChangePassword() { $model = new ChangePasswordForm(); if (isset($_POST['ChangePasswordForm'])) { $model->attributes = $_POST['ChangePasswordForm']; if ($model->validate()) { // Change the password $user = $this->loadModel(Yii::app()->user->id); $user->password = $model->newPassword; $user->save(); // Log and inform $this->log('"%s" updated his/her password', Yii::app()->user->name); Yii::app()->user->setFlash('success', Yii::t('User', 'Password successfully changed')); $this->redirect(array('movie/index')); } } $this->render('changePassword', array('model' => $model)); }
public function actionPassword() { $data = array(); $form = new ChangePasswordForm(); if ($_SERVER['REQUEST_METHOD'] == 'POST') { $form->attributes = $_POST['ChangePasswordForm']; if ($form->validate()) { $uid = Yii::app()->session['user']['id']; $query = "UPDATE {{users}} SET password = :password WHERE id = " . $uid; $this->db->createCommand($query)->bindValues(array(':password' => md5($form->password)))->execute(); Yii::app()->session['user']['password'] = md5($form->password); createMessage('Thay đổi mật khẩu thành công'); $this->redirect($this->createUrl('password')); } } $data['form'] = $form; $this->render('password', array('data' => $data)); }
/** * Change password action, Allow the User to change his password * @author EL GUENNUNI Sohaib s.elguennuni@gmail.com * @param <empty> * @return <empty> */ public function changepwAction() { $this->title = 'Change password'; $form = new ChangePasswordForm(); $user = Zend_Auth::getInstance()->getIdentity(); if ($user->id == 1) { $this->_redirect($this->view->url(array('module' => 'frontend', 'controller' => 'account', 'action' => 'display'), 'default', true)); } if ($this->getRequest()->isPost()) { $formData = $this->getRequest()->getPost(); if ($form->isValid($formData)) { ${$this}->_userModel->changePassword($form->getValue('password')); $this->_redirect($this->view->url(array('module' => 'frontend', 'controller' => 'account', 'action' => 'display'), 'default', true)); } else { $form->populate($formData); } } $this->view->form = $form; }
/** * Allows users to change their passwords * * @access public * @return void */ public function changePasswordAction() { $this->title = 'Change password'; $user = Zend_Auth::getInstance()->getIdentity(); if ($user->id == 1) { $this->_helper->FlashMessenger(array('msg-warn' => 'Please don\'t change the admin password in this release.')); $this->_redirect('/profile/'); } $form = new ChangePasswordForm(); $userModel = new BackofficeUser(); if ($this->getRequest()->isPost()) { if ($form->isValid($this->getRequest()->getPost())) { $userModel->changePassword($form->getValue('password')); $this->_helper->FlashMessenger(array('msg-success' => 'Your password was successfully changed.')); $this->_redirect('/profile/'); } } $this->view->form = $form; }
/** * Overidden, added call to redirectByGroup(). * * Login in the user and figure out where to redirect the browser. * * The $data has this format * array( * 'AuthenticationMethod' => 'MemberAuthenticator', * 'Email' => '*****@*****.**', * 'Password' => '1nitialPassword', * 'BackURL' => 'test/link', * [Optional: 'Remember' => 1 ] * ) * * * @param array $data * @return void */ protected function logInUserAndRedirect($data) { Session::clear('SessionForms.MemberLoginForm.Email'); Session::clear('SessionForms.MemberLoginForm.Remember'); if (Member::currentUser()->isPasswordExpired()) { if (isset($_REQUEST['BackURL']) && ($backURL = $_REQUEST['BackURL'])) { Session::set('BackURL', $backURL); } $cp = new ChangePasswordForm($this->controller, 'ChangePasswordForm'); $cp->sessionMessage('Your password has expired. Please choose a new one.', 'good'); return $this->controller->redirect('Security/changepassword'); } // Absolute redirection URLs may cause spoofing if (isset($_REQUEST['BackURL']) && $_REQUEST['BackURL'] && Director::is_site_url($_REQUEST['BackURL'])) { return $this->controller->redirect($_REQUEST['BackURL']); } // Spoofing attack, redirect to homepage instead of spoofing url if (isset($_REQUEST['BackURL']) && $_REQUEST['BackURL'] && !Director::is_site_url($_REQUEST['BackURL'])) { return $this->controller->redirect(Director::absoluteBaseURL()); } // If a default login dest has been set, redirect to that. if (Security::default_login_dest()) { return $this->controller->redirect(Director::absoluteBaseURL() . Security::default_login_dest()); } // redirect by group if (singleton('Group')->hasExtension('GroupLoginDataExtension')) { $this->redirectByGroup(); } // Redirect the user to the page where he came from $member = Member::currentUser(); if ($member) { $firstname = Convert::raw2xml($member->FirstName); if (!empty($data['Remember'])) { Session::set('SessionForms.MemberLoginForm.Remember', '1'); $member->logIn(true); } else { $member->logIn(); } Session::set('Security.Message.message', _t('Member.WELCOMEBACK', "Welcome Back, {firstname}", array('firstname' => $firstname))); Session::set("Security.Message.type", "good"); } Controller::curr()->redirectBack(); }
/** * Стартуем экшен сброса пароля * @param string $token - токен-сброса пароля * @throws CHttpException */ public function run($token) { if (Yii::app()->user->isAuthenticated()) { $this->controller->redirect(Yii::app()->user->returnUrl); } $module = Yii::app()->getModule('user'); // Если запрещено восстановление - печалька ;) if ($module->recoveryDisabled) { throw new CHttpException(404); } //Проверка токена $tokenModel = Yii::app()->userManager->tokenStorage->get($token, UserToken::TYPE_CHANGE_PASSWORD); if (null === $tokenModel) { throw new CHttpException(404); } // Если включено автоматическое восстановление пароля: if ((int) $module->autoRecoveryPassword === WebModule::CHOICE_YES) { if (Yii::app()->userManager->activatePassword($token, null, true)) { Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('UserModule.user', 'Пароль отправлен на ваш E-mail')); $this->controller->redirect(array('/user/account/login')); } else { Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::ERROR_MESSAGE, Yii::t('UserModule.user', 'Ошибка восстановления пароля!')); $this->controller->redirect(array('/user/account/recovery')); } } // Форма смены пароля: $changePasswordForm = new ChangePasswordForm(); // Получаем данные POST если таковые имеются: if (($data = Yii::app()->getRequest()->getPost('ChangePasswordForm')) !== null) { $changePasswordForm->setAttributes($data); // Проводим валидацию формы: if ($changePasswordForm->validate() && Yii::app()->userManager->activatePassword($token, $changePasswordForm->password, false)) { Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('UserModule.user', 'Пароль успешно изменен')); $this->controller->redirect(array('/user/account/login')); } } // Отрисовываем форму: $this->controller->render('changePassword', array('model' => $changePasswordForm)); }
/** * Action ChangePassword dùng để đổi mật khẩu của user */ public function actionChangePassword() { $model = new ChangePasswordForm('fullchange'); // Submit form if (isset($_POST['ChangePasswordForm'])) { $user = User::model()->notsafe()->findByPk(Yii::app()->user->id); $model->user = $user; $model->attributes = $_POST['ChangePasswordForm']; // Validate info if ($model->validate()) { // Save new password $user->encryptPassword($model->password); // Save new password to DB if ($user->save()) { // Notice Recovery Password success $this->setRedirectOptions(array("title" => UserModule::t('Change Password Success'), "message" => UserModule::t('The change password was successful!'))); $this->redirect('/user/profile'); } } } $this->render('changepassword', array('model' => $model)); }
/** * The sole purpose for overriding the constructor is surfacing the username to the user. */ public function __construct($controller, $name, $fields = null, $actions = null) { parent::__construct($controller, $name, $fields, $actions); // Obtain the Member object. If the user got this far, they must have already been synced. $member = Member::currentUser(); if (!$member) { if (Session::get('AutoLoginHash')) { $member = Member::member_from_autologinhash(Session::get('AutoLoginHash')); } // The user is not logged in and no valid auto login hash is available if (!$member) { Session::clear('AutoLoginHash'); return $this->controller->redirect($this->controller->Link('login')); } } // Get the username. $ldap = Injector::inst()->get('LDAPService')->getUserByGUID($member->GUID, array('samaccountname')); if (!empty($ldap['samaccountname'])) { $usernameField = new TextField('Username', 'Username', $ldap['samaccountname']); $usernameField = $usernameField->performDisabledTransformation(); $this->Fields()->unshift($usernameField); } }
/** Change a password * @access public * @return void */ public function changepasswordAction() { $form = new ChangePasswordForm(); $this->view->form = $form; if ($this->getRequest()->isPost() && $form->isValid($this->_request->getPost())) { if ($form->isValid($form->getValues())) { $password = SHA1($this->_helper->config()->auth->salt . $form->getValue('password')); $where = array(); $where[] = $this->_users->getAdapter()->quoteInto('id = ?', $this->getIdentityForForms()); $this->_users->update(array('password' => $password), $where); $this->getFlash()->addMessage('You have changed your password'); $this->redirect('/users/account/'); } else { $form->populate($form->getValues()); } } }
/** * Factory for generating a change password form. The form can be expanded * using an extension class and calling the updateChangePasswordForm method. * * @return Form */ public function ChangePasswordForm() { $form = ChangePasswordForm::create($this, "ChangePasswordForm"); $form->Actions()->find("name", "action_doChangePassword")->addExtraClass("btn")->addExtraClass("btn-green"); $cancel_btn = LiteralField::create("CancelLink", '<a href="' . $this->Link() . '" class="btn btn-red">' . _t("Users.CANCEL", "Cancel") . '</a>'); $form->Actions()->insertBefore($cancel_btn, "action_doChangePassword"); $this->extend("updateChangePasswordForm", $form); return $form; }
/** * Login form handler method * * This method is called when the user clicks on "Log in" * * @param array $data Submitted data */ public function dologin($data) { if ($this->performLogin($data)) { Session::clear('SessionForms.MemberLoginForm.Email'); Session::clear('SessionForms.MemberLoginForm.Remember'); if (Member::currentUser()->isPasswordExpired()) { if (isset($_REQUEST['BackURL']) && ($backURL = $_REQUEST['BackURL'])) { Session::set('BackURL', $backURL); } $cp = new ChangePasswordForm($this->controller, 'ChangePasswordForm'); $cp->sessionMessage('Your password has expired. Please choose a new one.', 'good'); Director::redirect('Security/changepassword'); } elseif (isset($_REQUEST['BackURL']) && $_REQUEST['BackURL'] && Director::is_site_url($_REQUEST['BackURL'])) { Director::redirect($_REQUEST['BackURL']); } elseif (Security::default_login_dest()) { Director::redirect(Director::absoluteBaseURL() . Security::default_login_dest()); } else { $member = Member::currentUser(); if ($member) { $firstname = Convert::raw2xml($member->FirstName); if (!empty($data['Remember'])) { Session::set('SessionForms.MemberLoginForm.Remember', '1'); $member->logIn(true); } else { $member->logIn(); } Session::set('Security.Message.message', sprintf(_t('Member.WELCOMEBACK', "Welcome Back, %s"), $firstname)); Session::set("Security.Message.type", "good"); } Director::redirectBack(); } } else { Session::set('SessionForms.MemberLoginForm.Email', $data['Email']); Session::set('SessionForms.MemberLoginForm.Remember', isset($data['Remember'])); if (isset($_REQUEST['BackURL'])) { $backURL = $_REQUEST['BackURL']; } else { $backURL = null; } if ($backURL) { Session::set('BackURL', $backURL); } if ($badLoginURL = Session::get("BadLoginURL")) { Director::redirect($badLoginURL); } else { // Show the right tab on failed login $loginLink = Director::absoluteURL(Security::Link("login")); if ($backURL) { $loginLink .= '?BackURL=' . urlencode($backURL); } Director::redirect($loginLink . '#' . $this->FormName() . '_tab'); } } }
/** * Save user's new password. * @param $args array * @param $request PKPRequest */ function savePassword($args, &$request) { $this->validate(); import('classes.user.form.ChangePasswordForm'); if (checkPhpVersion('5.0.0')) { // WARNING: This form needs $this in constructor $passwordForm = new ChangePasswordForm(); } else { $passwordForm =& new ChangePasswordForm(); } $passwordForm->readInputData(); $this->setupTemplate($request, true); if ($passwordForm->validate()) { $passwordForm->execute(); $request->redirect(null, $request->getRequestedPage()); } else { $passwordForm->display(); } }
function __construct($controller, $name, $fields = null, $actions = null) { parent::__construct($controller, $name, $fields, $actions); $this->fields->removeByName('OldPassword'); $this->password_manager = new PasswordManager(SapphireTransactionManager::getInstance()); }
public function actionPassword() { $model = new ChangePasswordForm(); $model->id = Yii::app()->user->id; if (isset($_POST) && isset($_POST['ChangePasswordForm'])) { $model->attributes = $_POST['ChangePasswordForm']; if ($model->validate()) { // Generate Password here and redirect $tempPass = $model->newPassword; $user = UserCredentials::model()->findByPk(Yii::app()->user->id); if ($user) { $user->salt = SecurityUtils::generateSalt($user->email_id); $user->password = SecurityUtils::encryptPassword($tempPass, $user->salt); if ($user->save()) { Yii::app()->user->setFlash('success', "Your password has been modified."); $this->redirect('/dashboard'); } } } } $this->render('password', array('model' => $model)); }