/** * @param RegistrationForm $form * @return bool|User */ public function createUser(RegistrationForm $form) { $transaction = Yii::app()->getDb()->beginTransaction(); try { $user = new User(); $user->setAttributes(['nick_name' => $form->nick_name, 'email' => $form->email]); if (!$this->userModule->emailAccountVerification) { $user->setAttributes(['status' => User::STATUS_ACTIVE, 'email_confirm' => User::EMAIL_CONFIRM_YES]); } $user->setAttribute('hash', $this->hasher->hashPassword($form->password)); if ($user->save() && ($token = $this->tokenStorage->createAccountActivationToken($user)) !== false) { if (!$this->userModule->emailAccountVerification) { Yii::app()->eventManager->fire(UserEvents::SUCCESS_REGISTRATION, new UserRegistrationEvent($form, $user, $token)); } else { Yii::app()->eventManager->fire(UserEvents::SUCCESS_REGISTRATION_NEED_ACTIVATION, new UserRegistrationEvent($form, $user, $token)); } $transaction->commit(); return $user; } throw new CException(Yii::t('UserModule.user', 'Error creating account!')); } catch (Exception $e) { Yii::log(Yii::t('UserModule.user', 'Error {error} account creating!', ['{error}' => $e->__toString()]), CLogger::LEVEL_INFO, UserModule::$logCategory); $transaction->rollback(); Yii::app()->eventManager->fire(UserEvents::FAILURE_REGISTRATION, new UserRegistrationEvent($form, $user)); return false; } }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model = new User(); if (Yii::app()->request->isPostRequest && !empty($_POST['User'])) { $model->setAttributes($_POST['User']); $model->setAttributes(array('salt' => Registration::model()->generateSalt(), 'password' => Registration::model()->hashPassword($model->password, $model->salt), 'registration_ip' => Yii::app()->request->userHostAddress)); if ($model->save()) { Yii::app()->user->setFlash(YFlashMessages::NOTICE_MESSAGE, Yii::t('user', 'Новый пользователь добавлен!')); $this->redirect(array('view', 'id' => $model->id)); } } $this->render('create', array('model' => $model)); }
public function createUser(RegistrationForm $form) { $transaction = Yii::app()->db->beginTransaction(); try { $user = new User('registration'); $profile = new Profile('registration'); $data = $form->getAttributes(); // Устанавливаем атрибуты пользователя $user->setAttributes(array('email' => $data['email'])); // Генерируем для пользователя новый пароль $password = $this->hasher->generateRandomPassword(); $user->hash = $this->hasher->hashPassword($password); // Устанавливаем роль пользователя $user->role = User::USER_ROLE; $profile->setAttributes(array('name' => $data['name'], 'gender' => $data['gender'], 'birth_date' => $data['date'], 'birth_time' => $form->getTime(), 'city_id' => $data['city_id'])); $profile->subscriber = Profile::SUBSCRIBER_YES; if ($user->save() && ($token = $this->tokenStorage->createAccountActivationToken($user)) !== false) { $profile->user_id = $user->id; if (!$profile->save()) { throw new CException(Yii::t('UserModule.user', 'Error creating profile!')); } $event = new CEvent($this, array('user' => $user, 'password' => $password, 'token' => $token, 'programId' => $data['programId'], 'subscriptionType' => $data['subscriptionType'])); $this->onSuccessRegistration($event); Yii::log(Yii::t('UserModule.user', 'Account {nick_name} was created', array('{nick_name}' => $user->email)), CLogger::LEVEL_INFO, UserModule::$logCategory); $transaction->commit(); return $user; } throw new CException(Yii::t('UserModule.user', 'Error creating account!')); } catch (Exception $e) { Yii::log(Yii::t('UserModule.user', 'Error {error} account creating!', array('{error}' => $e->__toString())), CLogger::LEVEL_INFO, UserModule::$logCategory); $transaction->rollback(); return false; } }
public function createUser(RegistrationForm $form) { $transaction = Yii::app()->db->beginTransaction(); try { $user = new User(); $data = $form->getAttributes(); unset($data['cPassword'], $data['verifyCode']); $user->setAttributes($data); $user->hash = $this->hasher->hashPassword($form->password); if ($user->save() && ($token = $this->tokenStorage->createAccountActivationToken($user)) !== false) { Yii::app()->eventManager->fire(UserEvents::SUCCESS_REGISTRATION, new UserRegistrationEvent($form, $user)); Yii::log(Yii::t('UserModule.user', 'Account {nick_name} was created', array('{nick_name}' => $user->nick_name)), CLogger::LEVEL_INFO, UserModule::$logCategory); //@TODO Отправка почты при создании пользователя Yii::app()->notify->send($user, Yii::t('UserModule.user', 'Registration on {site}', array('{site}' => Yii::app()->getModule('yupe')->siteName)), '//user/email/needAccountActivationEmail', array('token' => $token)); $transaction->commit(); return $user; } throw new CException(Yii::t('UserModule.user', 'Error creating account!')); } catch (Exception $e) { Yii::log(Yii::t('UserModule.user', 'Error {error} account creating!', array('{error}' => $e->__toString())), CLogger::LEVEL_INFO, UserModule::$logCategory); $transaction->rollback(); Yii::app()->eventManager->fire(UserEvents::FAILURE_REGISTRATION, new UserRegistrationEvent($form, $user)); return false; } }
public function createUser(RegistrationForm $form) { $transaction = Yii::app()->getDb()->beginTransaction(); try { $user = new User(); $userData = $form->getAttributes(); foreach (['cPassword', 'password', 'verifyCode', 'disableCaptcha'] as $attribute) { unset($userData[$attribute]); } $user->setAttributes($userData); $user->setAttribute('hash', $this->hasher->hashPassword($form->password)); if ($user->save() && ($token = $this->tokenStorage->createAccountActivationToken($user)) !== false) { Yii::app()->eventManager->fire(UserEvents::SUCCESS_REGISTRATION, new UserRegistrationEvent($form, $user, $token)); Yii::log(Yii::t('UserModule.user', 'Account {nick_name} was created', ['{nick_name}' => $user->nick_name]), CLogger::LEVEL_INFO, UserModule::$logCategory); $transaction->commit(); return $user; } throw new CException(Yii::t('UserModule.user', 'Error creating account!')); } catch (Exception $e) { Yii::log(Yii::t('UserModule.user', 'Error {error} account creating!', ['{error}' => $e->__toString()]), CLogger::LEVEL_INFO, UserModule::$logCategory); $transaction->rollback(); Yii::app()->eventManager->fire(UserEvents::FAILURE_REGISTRATION, new UserRegistrationEvent($form, $user)); return false; } }
public function createUser(RegistrationForm $form, Profile $profile) { $transaction = Yii::app()->db->beginTransaction(); try { $user = new User('registration'); $data = $form->getAttributes(); unset($data['cPassword'], $data['verifyCode']); $user->setAttributes($data); $user->hash = $this->hasher->hashPassword($form->password); $user->role = User::USER_ROLE; if ($user->save() && ($token = $this->tokenStorage->createAccountActivationToken($user)) !== false) { $profile->user_id = $user->id; if (!$profile->save()) { throw new CException(Yii::t('UserModule.user', 'Error creating profile!')); } Yii::log(Yii::t('UserModule.user', 'Account {nick_name} was created', array('{nick_name}' => $user->email)), CLogger::LEVEL_INFO, UserModule::$logCategory); //@TODO Yii::app()->notify->send($user, Yii::t('UserModule.user', 'Registration on {site}', array('{site}' => Yii::app()->getModule('yupe')->siteName)), '//user/email/needAccountActivationEmail', array('token' => $token)); Yii::app()->notify->sendAdmin('Новый пользователь на сайте ' . CHtml::encode(Yii::app()->getModule('yupe')->siteName), '//user/email/newUserEmail', array('user' => $user)); $transaction->commit(); return $user; } throw new CException(Yii::t('UserModule.user', 'Error creating account!')); } catch (Exception $e) { Yii::log(Yii::t('UserModule.user', 'Error {error} account creating!', array('{error}' => $e->__toString())), CLogger::LEVEL_INFO, UserModule::$logCategory); $transaction->rollback(); return false; } }
public function save() { if ($this->_userModel) { $attributes = $this->attributes; if (empty($this->password)) { unset($attributes['password']); } $this->_userModel->setAttributes($attributes); $this->_userModel->save(); } else { $user = new User(); $user->role = WebUser::ROLE_USER; $user->attributes = $this->attributes; $user->save(); } }
public function register($attr, $image) { $check = User::model()->findByAttributes(array('email' => $attr['email'])); if ($check) { return 'USER_EXIST'; } else { $model = new User(); $model->setAttributes($attr); $model->password = md5($attr['password']); if ($model->save(FALSE)) { $image_url = NULL; if (isset($image)) { $image_url = $image; } $model->avatar = $image_url; $model->save(FALSE); $subjects = Subject::model()->findAll(); foreach ($subjects as $subject) { $user_subject = new UserSubject(); $user_subject->subject_id = $subject->subject_id; $user_subject->user_id = $model->userid; $user_subject->save(FALSE); } return 'SUCCESS'; } return 'SERVER_ERROR'; } }
public function actionAdmin() { $model = new User('search'); $model->unsetAttributes(); if (isset($_GET['User'])) { $model->setAttributes($_GET['User']); } $this->render('admin', array('model' => $model)); }
public function test_should_request_valid_password() { $Alicia = new User(array('email' => '*****@*****.**', 'login' => 'alicia', 'password' => 'abcd1234')); $this->assertFalse($Alicia->save()); $this->assertEqual("can't be blank", $Alicia->getErrorsOn('password_confirmation')); $Alicia->setAttributes(array('password' => 'abcd1234', 'password_confirmation' => 'abcd1234')); $this->assertTrue($Alicia->save()); $this->assertNotEqual($Alicia->get('password'), 'abcd1234'); $this->assertTrue(strlen($Alicia->get('password_salt')) == 16); }
public function actionSignup() { $model = new User(); $model->scenario = 'registration'; // collect user input data if (isset($_POST['User'])) { $usr = $_POST['User']; $attr = array('name_user' => strstr($usr['email'], '@', true), 'regdate' => date('Y-m-d H:i:s'), 'end_pay_day' => date('Y-m-d H:i:s', mktime(23, 59, 59, date("m") + 1, date("d"), date("Y"))), 'spam' => $usr['spam'], 'confirm_code' => substr(md5(uniqid(rand(), true)), 16, 16)); $model->setAttributes($attr, false); $model->attributes = $usr; if ($model->save()) { Yii::app()->user->setFlash('registration', Yii::t('signup_view', 'success')); $email = $usr['email']; $subj = Yii::t('signup_view', 'mail_subject'); $body = ' <body style="margin: 0;"> <table style="width: 100%;background: #f2f2f2;font-family: Helvetica,Arial,sans-serif; color: #606060;"> <tr> <td style="width: 10%;"></td> <td style="width: 80%;text-align: center;"> <img src="http://timeman.org/images/logo_grey_75.png" alt="TIMEMAN" style="margin: 20px 0;" /> <table style="background-color: #fff; width: 100%; height: 200px;margin-bottom: 15px;border-radius: 6px;"> <tr> <td><h1 style="font-size: 40px;font-weight: bold;letter-spacing: -1px;line-height: 115%;margin: 15px 0;"> ' . Yii::t('signup_view', 'mail_header') . ' </h1></td> </tr> <tr> <td style="padding: 0 20px;"> <p style="margin: 0; padding: 0;font-size: 15px;line-height: 150%;"> ' . Yii::t('signup_view', 'mail_descr') . ' </p> </td> </tr> <tr> <td style="padding: 0;"> <a href="' . Yii::app()->request->getBaseUrl(true) . '/site/confirm?code=' . $attr['confirm_code'] . '" style="padding: 10px 16px;font-size: 18px;line-height: 1.33;border-radius: 6px;color: #fff;background-color: #5cb85c;text-decoration: none;display: inline-block;margin: 25px 0;"> ' . Yii::t('signup_view', 'mail_activate') . ' </a> </td> </tr> </table> <p style="padding: 0;margin: 20px 0;">' . Yii::t('signup_view', 'mail_footer') . '</p> </td> <td style="width: 10%;"></td> </tr> </table></body>'; $header = 'Content-type: text/html; charset=utf8' . "\r\n" . 'From: Timeman <*****@*****.**>' . "\r\n" . 'Reply-To: support@timeman.org' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($email, $subj, $body, $header); Yii::app()->db->createCommand()->insert('user_project_group', array('id_user' => $model->id, 'id_project' => 1, 'admin' => 0, 'cost' => 0)); } } // display the login form $this->render('signup_view', array('model' => $model)); }
public function actionCreate() { $model = new User(); $model->setAttributes($this->getJsonInput()); if (!$model->validate()) { $this->sendResponse(400, CHtml::errorSummary($model)); } elseif (!$model->save(false)) { throw new CException('Cannot create a record'); } $model->refresh(); $this->sendResponse(200, JSON::encode($model)); }
public function actionList() { $model = new User('search'); $model->unsetAttributes(); if (isset($_GET['User'])) { $model->setAttributes($_GET['User']); } $dataProvider = $model->search(); if (isset($_GET['page']) && preg_match("/^\\d+\$/", $_GET['page'])) { $dataProvider->pagination->setCurrentPage($_GET['page'] - 1); } $this->_sendResponse($dataProvider->getData(), 200, $dataProvider->pagination->getItemCount()); }
public function register($attr) { $check = User::model()->findByAttributes(array('email' => $attr['email'])); if ($check) { return 'USER_EXIST'; } else { $model = new User(); $model->setAttributes($attr); $model->password = md5($attr['password']); if ($model->save(FALSE)) { return 'SUCCESS'; } return 'SERVER_ERROR'; } }
public function actionCreate() { $storage = new YiiUserDataStorage(); if (is_null($storage)) { throw new APIException('Could not create data storage', APIResponseCode::API_INVALID_METHOD_PARAMS); } try { $obj = new User(); $data = Parameters::getRaw('data', 'post'); $attr = $storage->decodeResponse($data); $obj->setAttributes($attr); $storage->save($obj); } catch (Exception $e) { throw new APIException('Can not save resource object', APIResponseCode::API_SHEMA_CREATE_ERROR); } }
/** * Create user form */ public function actionCreate() { // Check Access checkAccessThrowException('op_users_create'); $model = new User(); if (isset($_POST['User'])) { $model->setAttributes($_POST['User']); if ($model->save()) { if (isset($_POST['UserCustomField'])) { UserCustomField::model()->processCustomFields($_POST['UserCustomField'], $model->id); } // Loop through the roles and assign them $types = array('roles', 'tasks', 'operations'); $lastID = Yii::app()->db->lastInsertID; foreach ($types as $type) { if (isset($_POST[$type]) && count($_POST[$type])) { foreach ($_POST[$type] as $others) { // assign if not assigned yet if (!Yii::app()->authManager->isAssigned($others, $lastID)) { $authItem = Yii::app()->authManager->getAuthItem($others); Yii::app()->authManager->assign($others, $lastID, $authItem->bizrule, $authItem->data); } } } } fok(at('User Created!')); // Log Message alog(at("Created new user: '******'.", array('{name}' => $model->name))); $this->redirect(array('index')); } } $temp = Yii::app()->authManager->getAuthItems(); $items = array(CAuthItem::TYPE_ROLE => array(), CAuthItem::TYPE_TASK => array(), CAuthItem::TYPE_OPERATION => array()); if (count($temp)) { foreach ($temp as $item) { $items[$item->type][$item->name] = $item->name; } } $items_selected = array(); $items_selected['roles'] = isset($_POST['roles']) ? $_POST['roles'] : ''; $items_selected['tasks'] = isset($_POST['tasks']) ? $_POST['tasks'] : ''; $items_selected['operations'] = isset($_POST['operations']) ? $_POST['operations'] : ''; $this->title[] = at('Create User'); // Add Breadcrumb $this->addBreadCrumb(at('Create User')); $this->render('form', array('model' => $model, 'items_selected' => $items_selected, 'items' => $items)); }
/** * @dataProvider dataProvider_Search */ public function testSearch_WithValidTerms_ReturnsExpectedResults($searchTerms, $numResults, $expectedKeys) { $user = new User(); $searchTerms['global_firm_rights'] = null; // ignore what setting global_firm_rights has $user->setAttributes($searchTerms, true); $results = $user->search(); $data = $results->getData(); $expectedResults = array(); if (!empty($expectedKeys)) { foreach ($expectedKeys as $key) { $expectedResults[] = $this->users($key); } } $this->assertEquals($numResults, $results->getItemCount()); $this->assertEquals($expectedResults, $data); }
/** * @test */ public function create() { $this->assertInstanceOf('User', User::model()); $model = new User(); $attributes = array('username' => 'test', 'password' => '21232f297a57a5a743894a0e4a801fc3', 'email' => '*****@*****.**', 'activkey' => '9a24eff8c15a6a141ece27eb6947da0f', 'superuser' => 1, 'status' => 1, 'lastvisit_at' => '2013-10-15 18:24:55'); $model->setAttributes($attributes, false); $this->assertTrue($model->save()); $model = new User(); $attributes = array('username' => 'test', 'password' => '21232f297a57a5a743894a0e4a801fc3', 'email' => '*****@*****.**', 'activkey' => '9a24eff8c15a6a141ece27eb6947da0f', 'superuser' => 1, 'status' => 1, 'lastvisit_at' => '2013-10-15 18:24:55'); $model->setAttributes($attributes, false); try { $model->save(); $this->fail("On devrait avoir une exception"); } catch (Exception $x) { $this->assertInstanceOf('CDbException', $x); } }
public function actionIndex() { $models = array(); if (!empty($_POST['User'])) { foreach ($_POST['User'] as $postData) { $model = new User(); $model->setAttributes($postData); if ($model->validate()) { $models[] = $model; } } } if (!empty($models)) { } else { $models[] = new User(); } $this->render("index", array('models' => $models)); }
public function run($code) { $code = trim($code); // пытаемся сделать выборку из таблицы регистраций $registration = Registration::model()->find('code = :code', array(':code' => $code)); if (is_null($registration)) { Yii::app()->user->setFlash(YFlashMessages::ERROR_MESSAGE, Yii::t('user', 'Ошибка активации! Возможно данный аккаунт уже активирован! Попробуете зарегистрироваться вновь?')); $this->controller->redirect(array(Yii::app()->getModule('user')->accountActivationFailure)); } // процедура активации // проверить параметры пользователя по "черным спискам" if (!Yii::app()->getModule('user')->isAllowedIp(Yii::app()->request->userHostAddress)) { // перенаправить на экшн для фиксации невалидных ip адресов $this->controller->redirect(array(Yii::app()->getModule('user')->invalidIpAction)); } // проверить на email if (!Yii::app()->getModule('user')->isAllowedEmail($registration->email)) { // перенаправить на экшн для фиксации невалидных ip адресов $this->controller->redirect(array(Yii::app()->getModule('user')->invalidEmailAction)); } // все проверки прошли - активируем аккаунт $transaction = Yii::app()->db->beginTransaction(); try { // создать запись в таблице пользователей и удалить запись в таблице регистраций $user = new User(); $user->setAttributes($registration->getAttributes()); if ($registration->delete() && $user->save()) { $transaction->commit(); Yii::log(Yii::t('user', "Активирован аккаунт с code = {code}!", array('{code}' => $code)), CLogger::LEVEL_INFO, UserModule::$logCategory); Yii::app()->user->setFlash(YFlashMessages::NOTICE_MESSAGE, Yii::t('user', 'Вы успешно активировали аккаунт! Теперь Вы можете войти!')); // отправить сообщение о активации аккаунта $emailBody = $this->controller->renderPartial('application.modules.user.views.email.accountActivatedEmail', array('model' => $user), true); Yii::app()->mail->send(Yii::app()->getModule('user')->notifyEmailFrom, $user->email, Yii::t('user', 'Аккаунт активирован!'), $emailBody); $this->controller->redirect(array(Yii::app()->getModule('user')->accountActivationSuccess)); } throw new CDbException(Yii::t('user', 'При активации аккаунта произошла ошибка!')); } catch (CDbException $e) { $transaction->rollback(); Yii::app()->user->setFlash(YFlashMessages::ERROR_MESSAGE, Yii::t('user', 'При активации аккаунта произошла ошибка! Попробуйте позже!')); Yii::log(Yii::t('user', "При активации аккаунта c code => {code} произошла ошибка {error}!", array('{code}' => $code, '{error}' => $e->getMessage())), CLogger::LEVEL_ERROR, UserModule::$logCategory); $this->controller->redirect(array(Yii::app()->getModule('user')->accountActivationFailure)); } }
public function actionIndex() { if (Yii::app()->user->isGuest) { if (Yii::app()->request->isPostRequest && isset($_POST["login"])) { $user = new User("login"); $user->setAttributes($_POST["login"]); $user->remember = true; if ($user->login()) { $this->redirect("/"); } else { Yii::app()->user->setFlash("error", $user->getError("pass")); } } if (p()['registerType'] == "INVITE") { $this->layout = "empty"; $this->render("index_guest"); return; } } $this->layout = "column1"; $hot_key = sprintf("hot.%d.%d.%d", Yii::app()->user->ini["hot.s_lang"], Yii::app()->user->ini["hot.t_lang"], Yii::app()->user->ini["hot.img"]); if (!($hot = Yii::app()->cache->get($hot_key))) { $C = new CDbCriteria(array("condition" => "t.ac_read = 'a'", "order" => "t.last_tr DESC NULLS LAST")); $C->limit = Yii::app()->user->ini["hot.img"] ? 12 : 36; if (Yii::app()->user->ini["hot.s_lang"]) { $C->addCondition("t.s_lang = " . Yii::app()->user->ini["hot.s_lang"]); } if (Yii::app()->user->ini["hot.t_lang"]) { $C->addCondition("t.t_lang = " . Yii::app()->user->ini["hot.t_lang"]); } $hot = Book::model()->findAll($C); Yii::app()->cache->set($hot_key, $hot, 60); } if (!($announces = Yii::app()->cache->get("announces"))) { $announces = Announce::model()->with("book.cat", "book.owner", "seen")->findAll(array("condition" => "t.topics BETWEEN 80 AND 89 AND book.ac_read = 'a'", "order" => "t.cdate desc", "limit" => 5)); Yii::app()->cache->set("announces", $announces, 90); } if (!($blog = Yii::app()->cache->get("blog"))) { $blog = BlogPost::model()->common()->findAll(["limit" => 10]); Yii::app()->cache->set("blog", $blog, 105); } $this->render('index', array("hot" => $hot, "searchTop" => $this->getSearchTop(), "announces" => $announces, "blog" => $blog)); }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model = new User('create'); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); // trigger event created $event = new UserCreatedEvent($model); $model->onUserCreated = [$event, 'sendNotification']; if (isset($_POST['User'])) { $model->setAttributes($_POST['User']); $model->setAttribute('created', date('Y-m-d H:i:s')); if ($model->validate(null, false)) { $model->setPassword($model->password); if ($model->save()) { $this->redirect(['view', 'id' => $model->id]); } } } $this->render('create', ['model' => $model]); }
public function reg_authenticate() { if (strlen($this->password) > 0) { $this->password = sha1(sha1($this->password)); } $user = User::model()->findByAttributes(array('account' => $this->account)); $loginbac = new LoginBac(); if ($user == null) { $loginbac->code = "1"; $newUser = new User(); $newUser->setAttributes(array('account' => $this->account, 'psw' => $this->password, 'nick' => $this->nick, 'sex' => $this->sex)); $newUser->save(true); $loginbac->account_id = $newUser->id; $loginbac->nick = $newUser->nick; } else { $loginbac->code = "0"; $loginbac->account_id = ""; $loginbac->nick = ""; } return $loginbac; }
/** * Update user's company and role information * * @param void * @return null */ function edit_company_and_role() { $this->wireframe->print_button = false; if ($this->active_user->isNew()) { $this->httpError(HTTP_ERR_NOT_FOUND); } // if if (!$this->active_user->canChangeRole($this->logged_user)) { $this->httpError(HTTP_ERR_FORBIDDEN); } // if $last_administrator = $this->active_user->isAdministrator() && Users::countAdministrators() <= 1; if ($last_administrator) { $this->wireframe->addPageMessage(lang('This user is the last adminstrator on the system. His role cannot be changed')); } // if $user_data = $this->request->post('user'); if (!is_array($user_data)) { $user_data = array('company_id' => $this->active_user->getCompanyId(), 'role_id' => $this->active_user->getRoleId()); } // if $this->smarty->assign(array('user_data' => $user_data, 'last_administrator' => $last_administrator)); if ($this->request->isSubmitted()) { db_begin_work(); $this->active_user->setAttributes($user_data); $save = $this->active_user->save(); if ($save && !is_error($save)) { db_commit(); flash_success(":display's company and role information has been updated", array('display' => $this->active_user->getDisplayName())); $this->redirectToUrl($this->active_user->getViewUrl()); } else { db_rollback(); $this->smarty->assign('errors', $save); } // if } // if }
public function createUser(RegistrationForm $form) { $transaction = Yii::app()->db->beginTransaction(); try { $user = new User(); $data = $form->getAttributes(); $user->setAttributes($data, false); $user->password = $this->hasher->hashPassword($form->password); $user->session = Yii::app()->session->sessionID; $user->md5 = md5(time()); $user->registerDate = date('Y-m-d', time()); if ($user->save()) { if ($this->stateStorage->create($user, $form)) { $transaction->commit(); return $user; } } throw new CException(Yii::t('UserModule.user', 'Error creating account!')); } catch (Exception $e) { $transaction->rollback(); return false; } }
/** * Экшен создания учетной записи администратора: * * @return nothing **/ public function actionCreateuser() { $model = new InstallForm('createUser'); if (isset($this->session['InstallForm']['createUser'])) { $model->setAttributes($this->session['InstallForm']['createUser']); if ($model->validate() && $this->session['InstallForm']['createUserStep'] === true) { $this->session['InstallForm'] = array_merge($this->session['InstallForm'], ['createUser' => $model->attributes, 'createUserStep' => false]); $this->_markFinished('createuser'); $this->_setSession(); $this->redirect(['/install/default/sitesettings']); } } if (($data = Yii::app()->getRequest()->getPost('InstallForm')) !== null) { // Сбрасываем сессию текущего пользователя, может поменяться id Yii::app()->getUser()->clearStates(); $model->setAttributes($data); if ($model->validate()) { $user = new User(); $user->deleteAll(); $user->setAttributes(['nick_name' => $model->userName, 'email' => $model->userEmail, 'gender' => User::GENDER_THING, 'access_level' => User::ACCESS_LEVEL_ADMIN, 'status' => User::STATUS_ACTIVE, 'email_confirm' => User::EMAIL_CONFIRM_YES, 'hash' => Yii::app()->userManager->hasher->hashPassword($model->userPassword), 'birth_date' => null]); if ($user->save()) { //@TODO заменить на обработку через событие if (Yii::app()->hasModule('rbac')) { Yii::import('application.modules.rbac.models.*'); $assign = new AuthAssignment(); $assign->itemname = AuthItem::ROLE_ADMIN; $assign->userid = $user->id; $assign->save(); } $login = new LoginForm(); $login->email = $model->userEmail; $login->password = $model->userPassword; Yii::app()->authenticationManager->login($login, Yii::app()->user, Yii::app()->request); Yii::app()->getUser()->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('InstallModule.install', 'The administrator has successfully created!')); $this->session['InstallForm'] = array_merge($this->session['InstallForm'], ['createUser' => $model->attributes, 'createUserStep' => true]); $this->_setSession(); $this->redirect(['/install/default/createuser']); } else { $model->addErrors($user->getErrors()); } } } $this->render('_view', ['data' => ['model' => $model]]); }
/** * Управление Сотрудниками. * * @return void */ public function actionIndex() { $model = new User('search'); $model->unsetAttributes(); // clear any default values if (Yii::app()->getRequest()->getParam('User') !== null) { $model->setAttributes(Yii::app()->getRequest()->getParam('User')); } $this->render('index', ['model' => $model]); }
/** * Manages all models. * * @return void */ public function actionIndex() { $model = new User('search'); $model->unsetAttributes(); // clear any default values $model->setAttributes(Yii::app()->getRequest()->getParam('User', array())); $this->render('index', array('model' => $model)); }
/** * Экшен создания учетной записи администратора: * * @return nothing **/ public function actionCreateuser() { $model = new InstallForm('createUser'); if (isset($this->session['InstallForm']['createUser'])) { $model->setAttributes($this->session['InstallForm']['createUser']); if ($model->validate() && $this->session['InstallForm']['createUserStep'] === true) { $this->session['InstallForm'] = array_merge($this->session['InstallForm'], array('createUser' => $model->attributes, 'createUserStep' => false)); $this->_markFinished('createuser'); $this->_setSession(); $this->redirect(array('/install/default/sitesettings')); } } if (($data = Yii::app()->getRequest()->getPost('InstallForm')) !== null) { // Сбрасываем сессию текущего пользователя, может поменяться id Yii::app()->user->clearStates(); $model->setAttributes($data); if ($model->validate()) { $user = new User(); $user->deleteAll(); $user->setAttributes(array('nick_name' => $model->userName, 'email' => $model->userEmail, 'gender' => 0, 'access_level' => User::ACCESS_LEVEL_ADMIN, 'status' => User::STATUS_ACTIVE, 'email_confirm' => User::EMAIL_CONFIRM_YES, 'hash' => Yii::app()->userManager->hasher->hashPassword($model->userPassword), 'birth_date' => null)); if ($user->save()) { $login = new LoginForm(); $login->email = $model->userEmail; $login->password = $model->userPassword; Yii::app()->authenticationManager->login($login, Yii::app()->user, Yii::app()->request); Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, Yii::t('InstallModule.install', 'The administrator has successfully created!')); $this->session['InstallForm'] = array_merge($this->session['InstallForm'], array('createUser' => $model->attributes, 'createUserStep' => true)); $this->_setSession(); $this->redirect(array('/install/default/createuser')); } else { $model->addErrors($user->getErrors()); } } } $this->render('_view', array('data' => array('model' => $model))); }
public function createUserNew($attr) { if (isset($attr['facebook_id'])) { $user_exist_facebook = User::model()->findByAttributes(array('facebook_id' => $attr['facebook_id'])); } if (isset($attr['google_id'])) { $user_exist_google = User::model()->findByAttributes(array('google_id' => $attr['google_id'])); } if (isset($user_exist_facebook) && $user_exist_facebook->facebook_id != NULL && $attr['facebook_id'] != NULL) { $user_exist_facebook->setAttributes($attr); $user_exist_facebook->last_updated = time(); if ($user_exist_facebook->save(FALSE)) { return array('user' => $user_exist_facebook, 'other' => $this->getPatientData($user_exist_facebook->user_id)); } } else { if (isset($user_exist_google) && $user_exist_google->google_id != NULL && $attr['google_id'] != NULL) { $user_exist_google->setAttributes($attr); $user_exist_google->last_updated = time(); if ($user_exist_google->save(FALSE)) { return array('user' => $user_exist_google, 'other' => $this->getPatientData($user_exist_google->user_id)); } } else { $user_model = new User(); $user_model->setAttributes($attr); $user_model->last_updated = time(); if ($user_model->save(FALSE)) { return array('user' => $user_model, 'other' => $this->getPatientData($user_model->user_id)); } } } }