public function run() { $user = $this->getController()->user; $form = new ProfileForm(); $formAttributes = $form->getAttributes(); unset($formAttributes['avatar'], $formAttributes['verifyCode']); $form->setAttributes($user->getAttributes(array_keys($formAttributes))); // Если у нас есть данные из POST - получаем их: if (($data = Yii::app()->getRequest()->getPost('ProfileForm')) !== null) { $transaction = Yii::app()->getDb()->beginTransaction(); try { $form->setAttributes($data); if ($form->validate()) { // Удаляем ненужные данные: unset($data['avatar']); // Заполняем модель данными: $user->setAttributes($data); // Если есть ошибки в профиле - перекинем их в форму if ($user->hasErrors()) { $form->addErrors($user->getErrors()); } // Если у нас есть дополнительные профили - проверим их foreach ((array) $this->getController()->module->profiles as $p) { $p->validate() || $form->addErrors($p->getErrors()); } // Если нет ошибок валидации: if ($form->hasErrors() === false) { Yii::log(Yii::t('UserModule.user', 'Profile for #{id}-{nick_name} was changed', ['{id}' => $user->id, '{nick_name}' => $user->email]), CLogger::LEVEL_INFO, UserModule::$logCategory); Yii::app()->getUser()->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('UserModule.user', 'Your profile was changed successfully')); if (($uploadedFile = CUploadedFile::getInstance($form, 'avatar')) !== null) { $user->changeAvatar($uploadedFile); } elseif ($form->use_gravatar) { $user->removeOldAvatar(); } $user->save(); // И дополнительные профили, если они есть if (is_array($this->getController()->module->profiles)) { foreach ($this->getController()->module->profiles as $k => $p) { $p->save(false); } } Yii::app()->getUser()->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('UserModule.user', 'Profile was updated')); $transaction->commit(); $this->getController()->redirect(['/user/profile/profile']); } else { Yii::log(Yii::t('UserModule.user', 'Error when save profile! #{id}', ['{id}' => $user->id]), CLogger::LEVEL_ERROR, UserModule::$logCategory); } } } catch (Exception $e) { $transaction->rollback(); Yii::app()->getUser()->setFlash(yupe\widgets\YFlashMessages::ERROR_MESSAGE, $e->getMessage()); } } $this->getController()->render('profile', ['model' => $form, 'module' => Yii::app()->getModule('user'), 'user' => $user]); }
/** * @dataProvider invalidDataProvider */ public function testInvalid($scenario, $attributes, $errors) { $form = new ProfileForm($scenario); $form->userIdentityClass = 'UserIdentity'; $form->setAttributes($attributes); $this->assertFalse($form->validate()); $this->assertEquals($errors, $form->getErrors()); }
public function run() { if (Yii::app()->user->isAuthenticated() === false) { $this->controller->redirect(Yii::app()->user->loginUrl); } if (($user = Yii::app()->user->getProfile()) === null) { Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::ERROR_MESSAGE, Yii::t('UserModule.user', 'User not found.')); Yii::app()->user->logout(); $this->controller->redirect((array) '/user/account/login'); } $profile = $user->profile; $profile->scenario = 'edit-profile'; $form = new ProfileForm(); $formAttributes = $form->getAttributes(); $form->setAttributes($profile->getAttributes(array_keys($formAttributes))); $module = Yii::app()->getModule('user'); // Если у нас есть данные из POST - получаем их: if (($data = Yii::app()->getRequest()->getPost('ProfileForm')) !== null) { $transaction = Yii::app()->db->beginTransaction(); try { $form->setAttributes($data); if ($form->validate()) { // Заполняем модель данными: $profile->setAttributes($data); // Если есть ошибки в профиле - перекинем их в форму if ($profile->hasErrors()) { $form->addErrors($profile->getErrors()); } // Если нет ошибок валидации: if ($form->hasErrors() === false) { // Сохраняем профиль $profile->save(); Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('UserModule.user', 'Your profile was changed successfully')); $transaction->commit(); $this->controller->redirect(array('/user/account/profile')); } } } catch (Exception $e) { $transaction->rollback(); Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::ERROR_MESSAGE, $e->getMessage()); } } $this->controller->render('profile', array('model' => $form, 'user' => $user)); }
public function run() { if (($user = Yii::app()->user->getProfile()) === null) { Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::ERROR_MESSAGE, Yii::t('UserModule.user', 'User not found.')); Yii::app()->user->logout(); $this->controller->redirect(array('/user/account/login')); } $form = new ProfileForm(); $formAttributes = $form->getAttributes(); unset($formAttributes['avatar'], $formAttributes['verifyCode']); $form->setAttributes($user->getAttributes(array_keys($formAttributes))); // Очищаем необходимые поля: $form->password = $form->cPassword = null; $module = Yii::app()->getModule('user'); // Если у нас есть данные из POST - получаем их: if (($data = Yii::app()->getRequest()->getPost('ProfileForm')) !== null) { $transaction = Yii::app()->db->beginTransaction(); try { $form->setAttributes($data); if ($form->validate()) { // Новый пароль? - ок, запоминаем: $newPass = isset($data['password']) ? $data['password'] : null; // Удаляем ненужные данные: unset($data['password'], $data['avatar']); // Запоминаем старую почту, $oldEmail = $user->email; // Заполняем модель данными: $user->setAttributes($data); // Новый пароль? - Генерируем хеш: if ($newPass) { $user->hash = Yii::app()->userManager->hasher->hashPassword($newPass); } // Если есть ошибки в профиле - перекинем их в форму if ($user->hasErrors()) { $form->addErrors($user->getErrors()); } // Если у нас есть дополнительные профили - проверим их foreach ((array) $this->controller->module->profiles as $p) { $p->validate() || $form->addErrors($p->getErrors()); } // Если нет ошибок валидации: if ($form->hasErrors() === false) { Yii::log(Yii::t('UserModule.user', 'Profile for #{id}-{nick_name} was changed', array('{id}' => $user->id, '{nick_name}' => $user->nick_name)), CLogger::LEVEL_INFO, UserModule::$logCategory); Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('UserModule.user', 'Your profile was changed successfully')); if ($form->use_gravatar) { $user->avatar = null; } elseif (($uploadedFile = CUploadedFile::getInstance($form, 'avatar')) !== null) { $user->changeAvatar($uploadedFile); } // Сохраняем профиль $user->save(); // И дополнительные профили, если они есть if (is_array($this->controller->module->profiles)) { foreach ($this->controller->module->profiles as $k => $p) { $p->save(false); } } Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('UserModule.user', 'Profile was updated')); $transaction->commit(); // Если включена верификация при смене почты: if ($module->emailAccountVerification && $oldEmail != $form->email) { if (Yii::app()->userManager->changeUserEmail($user, $form->email)) { Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('UserModule.user', 'You need to confirm your e-mail. Please check the mail!')); } } $this->controller->redirect(array('/user/account/profile')); } else { Yii::log(Yii::t('UserModule.user', 'Error when save profile! #{id}', array('{id}' => $user->id)), CLogger::LEVEL_ERROR, UserModule::$logCategory); } } } catch (Exception $e) { $transaction->rollback(); Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::ERROR_MESSAGE, $e->getMessage()); } } $this->controller->render('profile', array('model' => $form, 'module' => $module, 'user' => $user)); }
protected function registerLocalProfile(ProfileForm $localProfile, HybridauthForm $remoteLogin, $localIdentity = false) { if (!isset($_POST['ProfileForm']) && $localIdentity === false) { $userIdentityClass = $localProfile->userIdentityClass; $remoteProfile = $remoteLogin->getHybridAuthAdapter()->getUserProfile(); $localProfile->setAttributes($userIdentityClass::getRemoteAttributes($remoteProfile)); $localProfile->validate(); return $localProfile; } if ($localIdentity !== false) { $userIdentityClass = $localProfile->userIdentityClass; $remoteProfile = $remoteLogin->getHybridAuthAdapter()->getUserProfile(); $localProfile->setAttributes($userIdentityClass::getRemoteAttributes($remoteProfile)); } if (isset($_POST['ProfileForm']) && is_array($_POST['ProfileForm'])) { $localProfile->setAttributes($_POST['ProfileForm']); } if (!$localProfile->validate()) { return $localProfile; } $trx = Yii::app()->db->beginTransaction(); if (!$localProfile->save($this->module->requireVerifiedEmail)) { $trx->rollback(); Yii::app()->user->setFlash('error', Yii::t('UsrModule.usr', 'Failed to register a new user.') . ' ' . Yii::t('UsrModule.usr', 'Try again or contact the site administrator.')); return $localProfile; } $trx->commit(); if ($this->module->requireVerifiedEmail) { if ($this->sendEmail($localProfile, 'verify')) { Yii::app()->user->setFlash('success', Yii::t('UsrModule.usr', 'An email containing further instructions has been sent to the provided email address.')); } else { Yii::app()->user->setFlash('error', Yii::t('UsrModule.usr', 'Failed to send an email.') . ' ' . Yii::t('UsrModule.usr', 'Try again or contact the site administrator.')); } } // don't forget to associate the new profile with remote provider if (!$remoteLogin->associate($localProfile->getIdentity()->getId())) { Yii::app()->user->setFlash('error', Yii::t('UsrModule.usr', 'Failed to associate current user with {provider}.', array('{provider}' => $remoteLogin->provider))); $this->redirect(array('login', 'provider' => $remoteLogin->provider)); } if ($localProfile->getIdentity()->isActive()) { // don't use the $localProfile->login() method because there is no password set so we can't authenticate this identity if (Yii::app()->user->login($localProfile->getIdentity(), 0)) { $this->afterLogin(); } else { Yii::app()->user->setFlash('error', Yii::t('UsrModule.usr', 'Failed to log in.') . ' ' . Yii::t('UsrModule.usr', 'Try again or contact the site administrator.')); } } else { if (!Yii::app()->user->hasFlash('success')) { Yii::app()->user->setFlash('success', Yii::t('UsrModule.usr', 'Please wait for the account to be activated. A notification will be send to provided email address.')); } $this->redirect(array('login', 'provider' => $remoteLogin->provider)); } return $localProfile; }
public function actionProfile($update = false) { if (Yii::app()->user->isGuest) { $this->redirect(array('login')); } $model = new ProfileForm(); $model->setAttributes($model->getIdentity()->getAttributes()); $passwordForm = new PasswordForm(); if (isset($_POST['ajax']) && $_POST['ajax'] === 'profile-form') { $models = array($model); if (isset($_POST['PasswordForm']) && trim($_POST['PasswordForm']['newPassword']) !== '') { $models[] = $passwordForm; } echo CActiveForm::validate($models); Yii::app()->end(); } $flashes = array('success' => array(), 'error' => array()); if (isset($_POST['PasswordForm']) && trim($_POST['PasswordForm']['newPassword']) !== '') { $passwordForm->setAttributes($_POST['PasswordForm']); if ($passwordForm->validate()) { if ($passwordForm->resetPassword($model->getIdentity())) { $flashes['success'][] = Yii::t('UsrModule.usr', 'Changes have been saved successfully.'); } else { $flashes['error'][] = Yii::t('UsrModule.usr', 'Failed to change password.'); } } } if (isset($_POST['ProfileForm']) && empty($flashes['error'])) { $model->setAttributes($_POST['ProfileForm']); if ($model->validate()) { $oldEmail = $model->getIdentity()->getEmail(); if ($model->save()) { if ($this->module->requireVerifiedEmail && $oldEmail != $model->email) { if ($this->sendEmail($model, 'verify')) { $flashes['success'][] = Yii::t('UsrModule.usr', 'An email containing further instructions has been sent to provided email address.'); } else { $flashes['error'][] = Yii::t('UsrModule.usr', 'Failed to send an email.') . ' ' . Yii::t('UsrModule.usr', 'Try again or contact the site administrator.'); } } $flashes['success'][] = Yii::t('UsrModule.usr', 'Changes have been saved successfully.'); if (!empty($flashes['success'])) { Yii::app()->user->setFlash('success', implode('<br/>', $flashes['success'])); } if (!empty($flashes['error'])) { Yii::app()->user->setFlash('error', implode('<br/>', $flashes['error'])); } $this->redirect(array('profile')); } else { $flashes['error'][] = Yii::t('UsrModule.usr', 'Failed to update profile.') . ' ' . Yii::t('UsrModule.usr', 'Try again or contact the site administrator.'); } } } if (!empty($flashes['success'])) { Yii::app()->user->setFlash('success', implode('<br/>', $flashes['success'])); } if (!empty($flashes['error'])) { Yii::app()->user->setFlash('error', implode('<br/>', $flashes['error'])); } if ($update) { $this->render('updateProfile', array('model' => $model, 'passwordForm' => $passwordForm)); } else { $this->render('viewProfile', array('model' => $model)); } }
protected function registerLocalProfile(ProfileForm $localProfile, HybridauthForm $remoteLogin) { if (isset($_POST['ProfileForm'])) { $localProfile->setAttributes($_POST['ProfileForm']); if ($localProfile->register()) { if ($this->module->requireVerifiedEmail) { if ($this->sendEmail($localProfile, 'verify')) { Yii::app()->user->setFlash('success', Yii::t('UsrModule.usr', 'An email containing further instructions has been sent to provided email address.')); } else { Yii::app()->user->setFlash('error', Yii::t('UsrModule.usr', 'Failed to send an email.') . ' ' . Yii::t('UsrModule.usr', 'Try again or contact the site administrator.')); } } // don't forget to associate the new profile with remote provider if (!$remoteLogin->associate($localProfile->getIdentity()->getId())) { Yii::app()->user->setFlash('error', Yii::t('UsrModule.usr', 'Failed to associate current user with {provider}.', array('{provider}' => $remoteLogin->provider))); $this->redirect('login'); } if ($localProfile->getIdentity()->isActive()) { // don't use the $localProfile->login() method because there is no password set so we can't authenticate this identity if (Yii::app()->user->login($localProfile->getIdentity(), 0)) { $this->afterLogin(); } else { Yii::app()->user->setFlash('error', Yii::t('UsrModule.usr', 'Failed to log in.') . ' ' . Yii::t('UsrModule.usr', 'Try again or contact the site administrator.')); } } else { if (!Yii::app()->user->hasFlash('success')) { Yii::app()->user->setFlash('success', Yii::t('UsrModule.usr', 'Please wait for the account to be activated. A notification will be send to provided email address.')); } $this->redirect(array('login')); } } } else { $profile = $remoteLogin->getHybridAuthAdapter()->getUserProfile(); $email = $profile->emailVerifier !== null ? $profile->emailVerifier : $profile->email; $localProfile->setAttributes(array('username' => $email, 'email' => $email, 'firstName' => $profile->firstName, 'lastName' => $profile->lastName)); } return $localProfile; }