コード例 #1
0
ファイル: ModelValidatorTest.php プロジェクト: solve/database
 public function testBasic()
 {
     $user = new \User(array('name' => '  Alex', 'email' => 'invalid-email'));
     $this->assertFalse($user->save(), 'Save result is false for invalid email');
     $this->assertArrayHasKey('email', $user->getErrors(), 'Has an email error');
     $this->assertArrayHasKey('name', $user->getErrors(), 'Has error on name');
     $this->assertEquals(array('invalid name'), $user->getErrors('name'), 'Custom error description works');
     $user->name = 'Alexandr Viniychuk   ';
     $user->email = '*****@*****.**';
     $this->assertTrue($user->save(), 'Saving correct values');
     $this->assertEquals('Alexandr Viniychuk', $user->name, 'Trim process rule worked');
 }
コード例 #2
0
 private function createUser($login)
 {
     $model = new User();
     $tmpname = array();
     preg_match('/^([^\\s]+)\\s*(.*)?$/', $this->service->getAttribute('name'), $tmpname);
     //разделение имени по запчастям
     //$newUser->firstname = $tmpname[1];
     //$newUser->lastname = $tmpname[2];
     $model->login = $login;
     $model->username = $this->service->getAttribute('username');
     $model->avatar = $this->service->getAttribute('photo_small');
     $model->timezone = $this->service->getAttribute('timezone');
     $model->gender = $this->service->getAttribute('gender');
     $model->service = $this->service->serviceName;
     $model->subscribe = 0;
     $model->active = true;
     $model->last_login = date('Y-m-d H:i:s');
     $model->date_registration = date('Y-m-d H:i:s');
     if ($model->validate()) {
         $model->save(false, false);
     } else {
         print_r($model->getErrors());
         die;
     }
     return $model;
 }
コード例 #3
0
ファイル: UserTest.php プロジェクト: youprofit/Zurmo
 public function testEmailUniquenessValidation()
 {
     $user = User::getByUsername('super');
     Yii::app()->user->userModel = $user;
     $user = new User();
     $user->username = '******';
     $user->lastName = 'UserA';
     $user->setPassword('myuser');
     $emailAddress = '*****@*****.**';
     $user->primaryEmail->emailAddress = $emailAddress;
     $saved = $user->save();
     $this->assertTrue($saved);
     $user2 = new User();
     $user2->username = '******';
     $user2->lastName = 'UserB';
     $user2->setPassword('myuser');
     $emailAddress = '*****@*****.**';
     $user2->primaryEmail->emailAddress = $emailAddress;
     $saved = $user2->save();
     $this->assertFalse($saved);
     $validationErrors = $user2->getErrors();
     $this->assertTrue(count($validationErrors) > 0);
     // Todo: fix array keys below
     $this->assertTrue(isset($validationErrors['primaryEmail']));
     $this->assertTrue(isset($validationErrors['primaryEmail']['emailAddress']));
     $this->assertEquals('Email address already exists in system.', $validationErrors['primaryEmail']['emailAddress'][0]);
     // Try to save user without email address
     $user3 = new User();
     $user3->username = '******';
     $user3->lastName = 'UserC';
     $user3->setPassword('myuser');
     $saved = $user3->save();
     $this->assertTrue($saved);
 }
コード例 #4
0
ファイル: UserController.php プロジェクト: chenyongze/d-a-m
 /**
  * 创建卡牌库
  * @author gentle
  */
 public function actionCreate()
 {
     $model = new User();
     if (isset($_POST['User'])) {
         //admin管理员不能手动添加
         if ($_POST['User']['username'] == 'admin') {
             $this->redirect_back();
             exit;
         }
         //添加默认密码
         if ($_POST['User']['password'] == '') {
             $_POST['User']['password'] = Yii::app()->params['def_password'];
         }
         //接收范围权限并预处理
         $_POST['User']['scope'] = User::model()->makeScope();
         $_POST['User']['password'] = md5($_POST['User']['password']);
         $model->attributes = $_POST['User'];
         if ($model->save()) {
             $this->addLog('user', $model->id, '添加了名为“' . $model->username . '”的“' . Yii::app()->params["role"][$model->role]["name"] . '”');
             Yii::app()->user->setFlash("success", "新建 <b>{$model->username}</b> 用户成功!");
         } else {
             $errorMsg = '';
             $errorErr = $model->getErrors();
             foreach ($errorErr as $value) {
                 $errorMsg .= "\t" . $value[0];
             }
             $errorMsg = trim($errorMsg, ',');
             Yii::app()->user->setFlash("error", $errorMsg);
         }
         $this->redirect(array('user/index'));
     }
     $yxlist = User::model()->getScope();
     $this->renderPartial('_form', array('model' => $model, 'yxlist' => $yxlist));
 }
コード例 #5
0
ファイル: RegistrationAction.php プロジェクト: RSol/yupe
 public function run()
 {
     $form = new RegistrationForm();
     if (Yii::app()->request->isPostRequest && !empty($_POST['RegistrationForm'])) {
         $module = Yii::app()->getModule('user');
         $form->setAttributes($_POST['RegistrationForm']);
         // проверка по "черным спискам"
         // проверить на email
         if (!$module->isAllowedEmail($form->email)) {
             // перенаправить на экшн для фиксации невалидных email-адресов
             $this->controller->redirect(array(Yii::app()->getModule('user')->invalidEmailAction));
         }
         if (!$module->isAllowedIp(Yii::app()->request->userHostAddress)) {
             // перенаправить на экшн для фиксации невалидных ip-адресов
             $this->controller->redirect(array(Yii::app()->getModule('user')->invalidIpAction));
         }
         if ($form->validate()) {
             // если требуется активация по email
             if ($module->emailAccountVerification) {
                 $registration = new Registration();
                 // скопируем данные формы
                 $registration->setAttributes($form->getAttributes());
                 if ($registration->save()) {
                     // отправка email с просьбой активировать аккаунт
                     $mailBody = $this->controller->renderPartial('application.modules.user.views.email.needAccountActivationEmail', array('model' => $registration), true);
                     Yii::app()->mail->send($module->notifyEmailFrom, $registration->email, Yii::t('user', 'Регистрация на сайте {site} !', array('{site}' => Yii::app()->name)), $mailBody);
                     // запись в лог о создании учетной записи
                     Yii::log(Yii::t('user', "Создана учетная запись {nick_name}!", array('{nick_name}' => $registration->nick_name)), CLogger::LEVEL_INFO, UserModule::$logCategory);
                     Yii::app()->user->setFlash(YFlashMessages::NOTICE_MESSAGE, Yii::t('user', 'Учетная запись создана! Инструкции по активации аккаунта отправлены Вам на email!'));
                     $this->controller->refresh();
                 } else {
                     $form->addErrors($registration->getErrors());
                     Yii::log(Yii::t('user', "Ошибка при создании  учетной записи!"), CLogger::LEVEL_ERROR, UserModule::$logCategory);
                 }
             } else {
                 // если активации не требуется - сразу создаем аккаунт
                 $user = new User();
                 $user->createAccount($form->nick_name, $form->email, $form->password);
                 if ($user && !$user->hasErrors()) {
                     Yii::log(Yii::t('user', "Создана учетная запись {nick_name} без активации!", array('{nick_name}' => $user->nick_name)), CLogger::LEVEL_INFO, UserModule::$logCategory);
                     // отправить email с сообщением о успешной регистрации
                     $emailBody = $this->controller->renderPartial('application.modules.user.views.email.accountCreatedEmail', array('model' => $user), true);
                     Yii::app()->mail->send($module->notifyEmailFrom, $user->email, Yii::t('user', 'Регистрация на сайте {site} !', array('{site}' => Yii::app()->name)), $emailBody);
                     Yii::app()->user->setFlash(YFlashMessages::NOTICE_MESSAGE, Yii::t('user', 'Учетная запись создана! Пожалуйста, авторизуйтесь!'));
                     $this->controller->redirect(array('/user/account/login/'));
                 } else {
                     $form->addErrors($user->getErrors());
                     Yii::log(Yii::t('user', "Ошибка при создании  учетной записи без активации!"), CLogger::LEVEL_ERROR, UserModule::$logCategory);
                 }
             }
         }
     }
     $this->controller->render('registration', array('model' => $form));
 }
コード例 #6
0
ファイル: RegisterForm.php プロジェクト: syxoasis/wakfu-sae
 public function save()
 {
     $app = Yii::app();
     $transaction = $app->db->beginTransaction();
     try {
         if ($this->validate() == false) {
             throw new CDbException('参数出错', 0, []);
         }
         preg_match('/^(.*)@/', $this->username, $match);
         $password = CPasswordHelper::hashPassword($this->password);
         $result = Fraudmetrix::register($this->username, $this->username, $password);
         if ($result['success'] == true && $result['final_decision'] == 'Reject') {
             throw new CDbException('注册用户失败', 100, []);
         }
         $user = new User();
         $user->attributes = ['username' => $this->username, 'realname' => isset($match[1]) ? $match[1] : '无', 'nickname' => isset($match[1]) ? $match[1] : '无', 'email' => $this->username, 'password' => $password, 'sign_up_time' => time(), 'sign_up_ip' => Yii::app()->request->getUserHostAddress(), 'approved' => 5, 'state' => 0];
         if ($user->save() === false) {
             throw new CDbException('注册用户失败', 10, $user->getErrors());
         }
         $user->uuid = $app->getSecurityManager()->generateUUID($user->id . $user->password);
         if ($user->save() === false) {
             throw new CDbException('注册用户失败', 10, $user->getErrors());
         }
         //写入service
         $service = new Service();
         $service->attributes = ['uid' => $user->id, 'email' => $user->username, 'status' => 1, 'traffic' => 100 * 100];
         if ($service->save()) {
             Queue::apiCreate($user->id);
         }
         $transaction->commit();
     } catch (CDbException $e) {
         $transaction->rollback();
         $this->addErrors($e->errorInfo);
         return false;
     }
     $email = $app->getComponent('email');
     if (!empty($email)) {
         $email->quickSend($this->username, '欢迎您注册夸父', "请妥善保管好您的登录密码:" . $this->password);
     }
     return true;
 }
コード例 #7
0
ファイル: UserController.php プロジェクト: bigbol/ziiwo
 public function actionForm()
 {
     $model = new User();
     if (isset($_POST['User'])) {
         $model->attributes = $_POST['User'];
         if ($model->save()) {
             $this->redirect('./index.php?r=user');
         } else {
             $model->getErrors();
         }
     }
     $this->render('form', array('model' => $model));
 }
コード例 #8
0
ファイル: Action.php プロジェクト: CHILMEX/amocasion
 protected function returnOrRenderView(User $model, $view)
 {
     if ($this->isAjax()) {
         // Flatten errors
         $errors = array();
         foreach ($model->getErrors() as $attribute => $att_errors) {
             $errors = array_merge($errors, $att_errors);
         }
         echo CJSON::encode(array('result' => -1, 'message' => $model->hasErrors() ? $errors[0] : "No data"));
         Yii::app()->end();
     } else {
         $this->getController()->render($view, array('model' => $model));
     }
 }
コード例 #9
0
 public function actionIndex()
 {
     $user = new User();
     if (!empty($_POST['User'])) {
         $user->attributes = $_POST['User'];
         if ($user->save()) {
             Yii::app()->user->login(UserIdentity::createAuthenticatedIdentity($user->username, $user->id), 0);
             echo json_encode(array('errors' => ''));
         } else {
             $errors = $user->getErrors();
             echo json_encode(array('errors' => $errors));
         }
         exit;
     }
     $this->render('index', array('model' => $user));
 }
コード例 #10
0
ファイル: RegisterForm.php プロジェクト: tonci/phonebook
 public function register()
 {
     $this->username = htmlspecialchars(strip_tags($this->username));
     if ($this->validate()) {
         $user = new User();
         $user->username = $this->username;
         $user->password = $this->password;
         if ($user->save()) {
             return true;
         } else {
             // print_r($user->getErrors());
             $this->_errors += $user->getErrors();
             return false;
         }
     }
     return false;
 }
コード例 #11
0
ファイル: UserService.php プロジェクト: kl0428/urtime
 public function register($params = array())
 {
     extract($params);
     if (isset($nickname) && isset($password) && isset($mobile)) {
         $cache = Yii::app()->cache;
         $save_code = strtolower($cache->hget($mobile, 'register'));
         if (isset($code) && $save_code == strtolower($code)) {
             //查询手机是否注册过
             $user = User::model()->exists(array('condition' => 'mobile=:mobile', 'params' => array(':mobile' => isset($mobile) ? $mobile : 0)));
             if (!$user) {
                 Yii::import("application.extensions.Emchat.*");
                 $h = new Easemob();
                 if (isset($mobile) && $mobile) {
                     $ur_name = 'ur_' . $mobile;
                     $pwd = isset($password) ? $password : '******';
                     $res = $h->createUser($ur_name, $pwd);
                 }
                 $result = array('nickname' => $nickname, 'sex' => isset($sex) ? $sex : 0, 'mobile' => isset($mobile) ? $mobile : 0, 'image' => isset($image) ? $image : '', 'password' => md5($mobile . md5($password)));
                 if ($uuid = $res['entities'][0]['uuid']) {
                     $result['uuid'] = $uuid;
                 }
                 $model = new User();
                 $model->attributes = $result;
                 if ($model->validate() && $model->save()) {
                     $id = $model->getPrimaryKey();
                     $res = array('id' => $id, 'nickname' => $nickname, 'uuid' => $uuid);
                     $ret = $this->notice('OK', 0, '成功', $res);
                 } else {
                     $ret = $this->notice('ERR', 307, '', $model->getErrors());
                 }
             } else {
                 $ret = $this->notice('ERR', 306, '该号码已经注册过了', []);
             }
         } else {
             $ret = $this->notice('ERR', 305, '验证码错误', ['code' => $code, 'save_code' => $save_code]);
         }
     } else {
         $ret = $this->notice('ERR', 307, '', []);
     }
     $result = array('password' => $params['password']);
     $ret = $this->notice('ERR', 307, '', $result);
     return $ret;
 }
コード例 #12
0
 public function actionCreate()
 {
     $data = CJSON::decode(file_get_contents('php://input'));
     $model = new User();
     $model->fname = $data['fname'];
     $model->lname = $data['lname'];
     $model->email = $data['email'];
     $model->username = $data['username'];
     $model->password = $data['password'];
     $model->role = $data['role'];
     if (!$model->save()) {
         $errors = array();
         foreach ($model->getErrors() as $e) {
             $errors = array_merge($errors, $e);
         }
         $this->sendResponse(500, implode("<br />", $errors));
     }
     $model = User::model()->noPassword()->findByPk($model->id);
     $this->sendResponse(200, CJSON::encode($model));
 }
コード例 #13
0
ファイル: UsersController.php プロジェクト: air-talk/Air-Talk
 public function store()
 {
     $user = new User();
     // populate the model with the form data
     $user->email = Input::get('email');
     $user->password = Input::get('password');
     $user->first_name = Input::get('first_name');
     $user->last_name = Input::get('last_name');
     if (!$user->save()) {
         $errors = $user->getErrors();
         return Redirect::action('UsersController@create')->with('errors', $errors)->withInput();
     }
     // success!
     // Mail::send('emailTemplate', array('firstname'=>Input::get('first_name')), function($message){
     //        $message->to(Input::get('email'), Input::get('firstname').' '.Input::get('lastname'))->subject('Welcome to Airtalk!');
     //    });
     $email = Input::get('email');
     $password = Input::get('password');
     Auth::attempt(array('email' => $email, 'password' => $password));
     return Redirect::action('UsersController@index', Auth::id())->with('message', 'Account with email of ' . $user->email . ' has been created!');
 }
コード例 #14
0
 /**
  * Lists all models.
  */
 public function actionAdd()
 {
     $model = new User();
     $model->setScenario('add');
     $errores = array();
     // If form is submitted and data is correct...
     // collect user input data
     if (isset($_POST['User'])) {
         $_POST['User']['role'] = Yii::app()->params['subAdminRole'];
         $model->attributes = $_POST['User'];
         // validate user input and redirect to the previous page if valid
         if ($model->validate()) {
             $model->save();
             $this->redirect(array('post/index'));
         } else {
             $errores = $model->getErrors();
         }
     }
     // else, show the form again
     $this->render('add', ['model' => $model]);
 }
コード例 #15
0
ファイル: RegistrationForm.php プロジェクト: jayrulez/yiisns
 public function process()
 {
     $this->validate();
     if (!$this->hasErrors()) {
         $user = new User();
         $user->username = $this->username;
         $user->password = $this->password;
         if (!$user->save()) {
             foreach ($user->getErrors() as $errors) {
                 foreach ($errors as $field => $message) {
                     if (in_array($field, $this->attributes)) {
                         $this->addError($field, $message);
                     }
                 }
             }
             return false;
         }
         return true;
     }
     return false;
 }
コード例 #16
0
 public function actionIndex($email, $password)
 {
     /** @var $auth CAuthManager */
     $auth = Yii::app()->authManager;
     $existingRoles = $auth->getRoles();
     if (!array_key_exists('admin', $existingRoles)) {
         $auth->createRole('admin');
     }
     $newAdmin = User::model()->findByAttributes(array('email' => $email));
     if (empty($newAdmin)) {
         $newAdmin = new User();
     }
     $newAdmin->email = $email;
     $newAdmin->password = $password;
     if (!$newAdmin->save()) {
         throw new CException(print_r($newAdmin->getErrors(), true));
     }
     $userRoles = $auth->getRoles($newAdmin->id);
     if (!array_key_exists('admin', $userRoles)) {
         $auth->assign('admin', $newAdmin->id);
     }
 }
コード例 #17
0
ファイル: RegisterCompanyForm.php プロジェクト: asopin/portal
 public function register()
 {
     $user = new User();
     $user->first_name = $this->first_name;
     $user->last_name = $this->last_name;
     $user->email = $this->email;
     $user->position = $this->position;
     $user->phone = $this->phone;
     $user->password = $this->password;
     $user->username = $this->username;
     $user->role = User::ROLE_EMPL;
     $user->status = User::STATUS_DISABLED;
     $user->additional_contact = $this->additional_contact;
     $user->hash = md5(microtime(true) . rand());
     if (!$user->save()) {
         $this->addError('username', 'Can`t create user ' . serialize($user->getErrors()));
         return false;
     }
     UserHelper::sendEmailConfirmation($user);
     $company = new Company();
     $company->name = $this->name;
     $company->site_url = $this->site_url;
     $company->address = $this->address;
     $company->created_at = new CDbExpression('NOW()');
     $company->updated_at = new CDbExpression('NOW()');
     if (!$company->save()) {
         $this->addError('name', 'Can`t create company ' . serialize($company->getErrors()));
         return false;
     }
     $bind = new UserToCompany();
     $bind->user_id = $user->id;
     $bind->company_id = $company->id;
     if (!$bind->save()) {
         $this->addError('name', 'Can`t bind company ' . serialize($bind->getErrors()));
         return false;
     }
     return true;
 }
コード例 #18
0
ファイル: UserService.php プロジェクト: vikaanet/v5
 /**
  * @param $openid
  * @param null $userData
  * @return User|static
  * @throws Exception
  */
 public function save($openid, $userData = null)
 {
     $user = User::model()->findByPk($openid);
     if (!empty($user)) {
         if (!empty($userData['nickname'])) {
             $user->nickname = $userData['nickname'];
         }
         if (!empty($userData['headimgurl'])) {
             $user->avatar = $userData['headimgurl'];
         }
     } else {
         $ip = YII_DEBUG ? '121.32.52.217' : CommonTool::getClientIp();
         $info = CommonTool::getCity($ip);
         $count = User::model()->count();
         $user = new User();
         $user->attributes = array('user_id' => $openid, 'nickname' => empty($userData['nickname']) ? '微信用户' . (25874 + $count) : CommonTool::emojiFilter($userData['nickname']), 'avatar' => !empty($userData['headimgurl']) ? $userData['headimgurl'] : 'http://appmcdn.m0.hk/avatar.jpg', 'ip' => $ip, 'city' => $info['city'], 'created_at' => time());
     }
     if (!$user->save()) {
         CommonTool::log($user->getErrors());
         throw new Exception('创建用户失败!');
     }
     return $user;
 }
コード例 #19
0
 public function registerGuest()
 {
     if (Yii::app()->user->isGuest && $this->registerGuest) {
         $user = new User('registerFast');
         $user->password = $this->_password;
         $user->username = $this->name;
         $user->email = $this->email;
         $user->login = $this->email;
         $user->address = $this->address;
         $user->phone = $this->phone;
         $user->group_id = 2;
         if ($user->validate()) {
             $user->save();
             $this->sendRegisterMail();
             Yii::app()->user->setFlash('success_register', Yii::t('app', 'SUCCESS_REGISTER'));
         } else {
             $this->addError('registerGuest', 'Ошибка регистрации');
             Yii::app()->user->setFlash('error_register', Yii::t('CartModule.default', 'ERROR_REGISTER'));
             print_r($user->getErrors());
             die('error register');
         }
     }
 }
コード例 #20
0
ファイル: UserForm.php プロジェクト: song-yuan/wymenujp
 public function save()
 {
     if ($this->lid) {
         $model = User::model()->find('lid=:id', array(':id' => $this->lid));
     } else {
         $model = new User();
         $se = new Sequence("user");
         $model->lid = $se->nextval();
         $model->create_at = date('Y-m-d H:i:s', time());
         $model->delete_flag = '0';
         //$model->lid = $this->getPkValue();
     }
     $model->username = $this->username;
     $model->mobile = $this->mobile;
     $model->staff_no = $this->staff_no;
     $model->email = $this->email;
     $model->role = $this->role;
     $model->dpid = $this->dpid;
     $model->status = 1;
     if ($this->password_old != $this->password) {
         $model->password_hash = $this->password;
     }
     if ($model->validate()) {
         if ($this->password_old != $this->password) {
             $model->password_hash = Helper::genPassword($this->password);
         }
         //var_dump($model);exit;
         $model->save();
         return true;
     } else {
         $this->addErrors($model->getErrors());
         if ($passwordError = $model->getError('password_hash')) {
             $this->addError('password', $passwordError);
         }
         return false;
     }
 }
コード例 #21
0
 public function safeUp()
 {
     $admin = new User();
     $admin->username = '******';
     $admin->email = '*****@*****.**';
     $admin->password = '******';
     $admin->password_strategy = 'bcrypt';
     $admin->superuser = true;
     $admin->activation_time = 1;
     if (!$admin->save()) {
         $msg = print_r($admin->getErrors(), 1);
         echo $msg;
         // throw Exception(400,'data not saving: '.$msg );
     }
     $demo = new User();
     $demo->username = '******';
     $demo->email = '*****@*****.**';
     $demo->password = '******';
     $demo->password_strategy = 'bcrypt';
     $demo->activation_time = 1;
     if (!$demo->save()) {
         $msg = print_r($demo->getErrors(), 1);
         echo $msg;
         //throw Exception(400,'data not saving: '.$msg );
     }
     $demo = new User();
     $demo->username = '******';
     $demo->email = '*****@*****.**';
     $demo->password = '******';
     $demo->password_strategy = 'bcrypt';
     $demo->activation_time = 1;
     if (!$demo->save()) {
         $msg = print_r($demo->getErrors(), 1);
         echo $msg;
         //throw Exception(400,'data not saving: '.$msg );
     }
 }
コード例 #22
0
ファイル: UserController.php プロジェクト: visavi/rotorcms
 /**
  * Регистрация
  */
 public function register()
 {
     if (User::check()) {
         App::redirect('/');
     }
     if (Request::isMethod('post') && !Request::has('token')) {
         $captcha = Request::input('captcha');
         $login = Request::input('login');
         $email = Request::input('email');
         $password = Request::input('password');
         $gender = Request::input('gender');
         $user = new User();
         $user->captcha = $captcha;
         $user->login = $login;
         $user->new_password = $password;
         $user->email = $email;
         $user->gender = $gender;
         if ($user->save()) {
             $message = 'Добро пожаловать, ' . e($login) . '<br>Теперь вы зарегистрированный пользователь сайта ' . Setting::get('sitelink') . ' , сохраните ваш пароль в надежном месте<br>Ваши данные для входа на сайт<br>Email: ' . e($email) . '<br>Пароль: ' . e($password) . '<br>Если это письмо попало к вам по ошибке, то просто проигнорируйте его';
             $to = [$email => $login];
             $subject = 'Регистрация на сайте';
             $body = App::view('mailer.register', compact('subject', 'message'), true);
             // Отправка письма
             App::sendMail($to, $subject, $body);
             // Авторизация
             User::login($email, $password);
             App::setFlash('success', 'Добро пожаловать, ' . e($user->login) . '! Вы успешно зарегистрированы!');
             App::redirect('/');
         } else {
             App::setFlash('danger', $user->getErrors());
             App::setInput($_POST);
             App::redirect('/register');
         }
     }
     if (Request::has('token')) {
         User::socialAuth(Request::input('token'));
     }
     App::view('users.register');
 }
コード例 #23
0
ファイル: User_tests.php プロジェクト: bennilyn/examples
<h2>It should create a valid User object when all input is provided</h2>
<?php 
$validTest = array("userName" => "krobbins", "password" => "123");
$s1 = new User($validTest);
echo "The object is: {$s1}<br>";
$test1 = is_object($s1) ? '' : 'Failed:It should create a valid object when valid input is provided<br>';
echo $test1;
$test2 = empty($s1->getErrors()) ? '' : 'Failed:It not have errors when valid input is provided<br>';
echo $test2;
?>

<h2>It should extract the parameters that went in</h2>
<?php 
$props = $s1->getParameters();
print_r($props);
?>

<h2>It should have an error when the user name contains invalid characters</h2>
<?php 
$invalidTest = array("userName" => "krobbins\$");
$s1 = new User($invalidTest);
$test2 = empty($s1->getErrors()) ? '' : 'Failed:It should have errors when invalid input is provided<br>';
echo $test2;
echo "The error for userName is: " . $s1->getError('userName') . "<br>";
echo "The error for password is: " . $s1->getError('password') . "<br>";
echo "The object is: {$s1}<br>";
?>
</body>
</html>
コード例 #24
0
 public function testValidation()
 {
     $user = new User();
     $user->password = '******';
     $this->assertFalse($user->hasErrors());
     $this->assertEquals(array(), $user->errors);
     $this->assertEquals(array(), $user->getErrors('username'));
     $this->assertFalse($user->save());
     $this->assertNull($user->id);
     $this->assertTrue($user->isNewRecord);
     $this->assertTrue($user->hasErrors());
     $this->assertTrue($user->hasErrors('username'));
     $this->assertTrue($user->hasErrors('email'));
     $this->assertFalse($user->hasErrors('password'));
     $this->assertEquals(1, count($user->getErrors('username')));
     $this->assertEquals(1, count($user->getErrors('email')));
     $this->assertEquals(2, count($user->errors));
     $user->clearErrors();
     $this->assertFalse($user->hasErrors());
     $this->assertEquals(array(), $user->errors);
 }
コード例 #25
0
 /**
  * 	postSignup.
  *
  *	Handles POST requests for users signing up natively through Madison
  *		Fires MadisonEvent::NEW_USER_SIGNUP Event
  *
  *	@param void
  *
  *	@return Illuminate\Http\RedirectResponse
  */
 public function postSignup()
 {
     //Retrieve POST values
     $email = Input::get('email');
     $password = Input::get('password');
     $fname = Input::get('fname');
     $lname = Input::get('lname');
     //Create user token for email verification
     $token = str_random();
     //Create new user
     $user = new User();
     $user->email = $email;
     $user->password = $password;
     $user->fname = $fname;
     $user->lname = $lname;
     $user->token = $token;
     if (!$user->save()) {
         return Redirect::to('user/signup')->withInput()->withErrors($user->getErrors());
     }
     Event::fire(MadisonEvent::NEW_USER_SIGNUP, $user);
     //Send email to user for email account verification
     Mail::queue('email.signup', array('token' => $token), function ($message) use($email, $fname) {
         $message->subject('Welcome to the Madison Community');
         $message->from('*****@*****.**', 'Madison');
         $message->to($email);
         // Recipient address
     });
     return Redirect::to('user/login')->with('message', 'An email has been sent to your email address.  Please follow the instructions in the email to confirm your email address before logging in.');
 }
コード例 #26
0
ファイル: DefaultController.php プロジェクト: kot-ezhva/ygin
 public function actionCreateUser()
 {
     $dbSettings = $this->getDbSettingsModel();
     $dbConnection = $dbSettings->getDbConnection();
     Yii::app()->setComponent('db', $dbConnection);
     $userSettings = $this->getUserSettingsModel();
     $trans = $dbConnection->beginTransaction();
     $userModel = new User();
     $userModel->name = $userSettings->name;
     $userModel->mail = $userSettings->email;
     $userModel->user_password = $userSettings->password;
     $userModel->full_name = $userSettings->fullName;
     if (!$userModel->save()) {
         $errors = $userModel->getErrors();
         $trans->rollback();
         throw new CHttpException(500, "Не удалось добавить пользователя:\n" . print_r($errors, true));
     } else {
         Yii::app()->authManager->assign(DaWebUser::ROLE_DEV, $userModel->id_user);
         $this->saveConfigFile($dbSettings);
         $this->setDbSettingsModel(null);
         $this->setUserSettingsModel(null);
         $trans->commit();
         echo CJSON::encode(array('success' => true));
     }
 }
コード例 #27
0
 public function actionAddUser()
 {
     $user = new User();
     $request = Yii::app()->getRequest();
     if ($request->getIsPostRequest()) {
         $userAtt = $request->getPost('User');
         $user->attributes = $userAtt;
         if (!$user->validate()) {
             $errors = $user->getErrors();
         } else {
             if (!$user->save()) {
                 throw new Exception("Unable to save user: " . print_r($user->getErrors(), true));
             }
             Audit::add('admin-User', 'add', $user->id);
             if (!isset($userAtt['roles'])) {
                 $userAtt['roles'] = array();
             }
             $user->saveRoles($userAtt['roles']);
             $this->redirect('/admin/users/' . ceil($user->id / $this->items_per_page));
         }
     }
     $user->password = '';
     $this->render('/admin/adduser', array('user' => $user, 'errors' => @$errors));
 }
コード例 #28
0
 /**
  * Экшен создания учетной записи администратора:
  *
  * @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]]);
 }
コード例 #29
0
ファイル: HLdap.php プロジェクト: luizreginaldo/humhub
 /**
  * Updates or creates user by given ldap node
  * 
  * @param Zend_Ldap_Node $node
  * @return User User Object
  */
 public function handleLdapUser($node)
 {
     $username = $node->getAttribute(HSetting::Get('usernameAttribute', 'authentication_ldap'), 0);
     $email = $node->getAttribute('mail', 0);
     $guid = $this->binToStrGuid($node->getAttribute('objectGUID', 0));
     // Try to load User:
     $userChanged = false;
     $user = null;
     if ($guid != "") {
         $user = User::model()->findByAttributes(array('guid' => $guid, 'auth_mode' => User::AUTH_MODE_LDAP));
     } else {
         // Fallback use e-mail
         $user = User::model()->findByAttributes(array('email' => $email, 'auth_mode' => User::AUTH_MODE_LDAP));
     }
     if ($user === null) {
         $user = new User();
         if ($guid != "") {
             $user->guid = $guid;
         }
         $user->status = User::STATUS_ENABLED;
         $user->auth_mode = User::AUTH_MODE_LDAP;
         $user->group_id = 1;
         Yii::log('Create ldap user ' . $username . '!', CLogger::LEVEL_INFO, 'authentication_ldap');
     }
     // Update Group Mapping
     foreach (Group::model()->findAll('ldap_dn != ""') as $group) {
         if (in_array($group->ldap_dn, $node->getAttribute('memberOf'))) {
             if ($user->group_id != $group->id) {
                 $userChanged = true;
                 $user->group_id = $group->id;
             }
         }
     }
     // Update Users Field
     if ($user->username != $username) {
         $userChanged = true;
         $user->username = $username;
     }
     if ($user->email != $email) {
         $userChanged = true;
         $user->email = $email;
     }
     if ($user->validate()) {
         // Only Save user when something is changed
         if ($userChanged || $user->isNewRecord) {
             $user->save();
         }
         // Update Profile Fields
         foreach (ProfileField::model()->findAll('ldap_attribute != ""') as $profileField) {
             $ldapAttribute = $profileField->ldap_attribute;
             $profileFieldName = $profileField->internal_name;
             $user->profile->{$profileFieldName} = $node->getAttribute($ldapAttribute, 0);
         }
         if ($user->profile->validate()) {
             $user->profile->save();
             // Update Space Mapping
             foreach (Space::model()->findAll('ldap_dn != ""') as $space) {
                 if (in_array($space->ldap_dn, $node->getAttribute('memberOf'))) {
                     $space->addMember($user->id);
                 }
             }
         } else {
             Yii::log('Could not create or update ldap user profile! (' . print_r($user->profile->getErrors(), true) . ")", CLogger::LEVEL_ERROR, 'authentication_ldap');
         }
     } else {
         Yii::log('Could not create or update ldap user! (' . print_r($user->getErrors(), true) . ")", CLogger::LEVEL_ERROR, 'authentication_ldap');
     }
     return $user;
 }
コード例 #30
0
 /**
  * register user
  * Enter description here ...
  */
 function actionUpdateProfile()
 {
     header('Content-type: application/json');
     //	    if(!Yii::app()->request->isPostRequest){
     //	   		 IjoyPlusServiceUtils::exportServiceError(Constants::METHOD_NOT_SUPPORT);
     //	   		 return ;
     //	   	}
     if (!IjoyPlusServiceUtils::validateAPPKey()) {
         IjoyPlusServiceUtils::exportServiceError(Constants::APP_KEY_INVALID);
         return;
     }
     $nickname = Yii::app()->request->getParam("nickname");
     $pwd = Yii::app()->request->getParam("password");
     $username = Yii::app()->request->getParam("username");
     $sourceid = Yii::app()->request->getParam("source_id");
     $source_type = Yii::app()->request->getParam("source_type");
     if (!IjoyPlusServiceUtils::validateThirdPartSource($source_type)) {
         IjoyPlusServiceUtils::exportServiceError(Constants::THIRD_PART_SOURCE_TYPE_INVALID);
         return;
     }
     if (!(isset($nickname) && !is_null($nickname) && strlen($nickname) > 0)) {
         IjoyPlusServiceUtils::exportServiceError(Constants::NICKNAME_IS_NULL);
         return;
     }
     if (!(isset($pwd) && !is_null($pwd) && strlen($pwd) > 0)) {
         IjoyPlusServiceUtils::exportServiceError(Constants::PWD_IS_NULL);
         return;
     }
     if (isset($username) && !is_null($username) && strlen($username) > 0) {
         $emailValidator = new CEmailValidator();
         if (!$emailValidator->validateValue($username)) {
             IjoyPlusServiceUtils::exportServiceError(Constants::EMAIL_INVALID);
             return;
         } else {
             $record = User::model()->find('LOWER(username)=?', array(strtolower($username)));
             if ($record !== null) {
                 IjoyPlusServiceUtils::exportServiceError(Constants::USERNAME_EXIST);
                 return;
             }
         }
     }
     try {
         $record = User::model()->find('LOWER(nickname)=?', array(strtolower($nickname)));
         if ($record !== null) {
             IjoyPlusServiceUtils::exportServiceError(Constants::NICKNAME_IS_EXSTING);
             return;
         } else {
             $model = new User();
             $model->nickname = $nickname;
             $model->password = md5($pwd);
             $model->username = $username;
             $model->status = Constants::USER_APPROVAL;
             $model->create_date = new CDbExpression('NOW()');
             switch ($source_type) {
                 case Constants::THIRD_PART_ACCOUNT_DOUBAN:
                     $model->douban_user_id = $sourceid;
                     break;
                 case Constants::THIRD_PART_ACCOUNT_QQ:
                     $model->qq_wb_user_id = $sourceid;
                     break;
                 case Constants::THIRD_PART_ACCOUNT_REN_REN:
                     $model->ren_user_id = $sourceid;
                     break;
                 case Constants::THIRD_PART_ACCOUNT_SINA:
                     $model->sina_wb_user_id = $sourceid;
                     break;
             }
             if ($model->save()) {
                 $identity = new IjoyPlusUserIdentity($username, $pwd);
                 $identity->setId($model->id);
                 $identity->setState('nickname', $model->nickname);
                 Yii::app()->user->login($identity);
                 UserManager::followPrestiges($model->id);
                 IjoyPlusServiceUtils::exportServiceError(Constants::SUCC);
                 //
             } else {
                 Yii::log(CJSON::encode($model->getErrors()), "warning");
                 //   		    	var_dump();
                 IjoyPlusServiceUtils::exportServiceError(Constants::SYSTEM_ERROR);
             }
         }
     } catch (Exception $e) {
         Yii::log(CJSON::encode($e), "error");
         IjoyPlusServiceUtils::exportServiceError(Constants::SYSTEM_ERROR);
     }
 }