Example #1
0
 public function createAdmin()
 {
     $attributes = array('username' => 'admin', 'email' => '*****@*****.**', 'password' => CPasswordHelper::hashPassword('iddqd3311'), 'email_verified' => 1);
     $user = new Users();
     $user->attributes = $attributes;
     $user->save();
 }
Example #2
0
 protected function beforeSave()
 {
     if (isset($this->senha)) {
         $this->senha = CPasswordHelper::hashPassword($this->senha);
     }
     return parent::beforeSave();
 }
 public function actionRegister()
 {
     $username = $_POST['username'];
     $password = $_POST['password'];
     if (strlen($username) < 3) {
         Helper::renderJSONErorr("Username must be at least 3 symbols: {$username} [" . strlen($username) . "]");
     }
     if (strlen($password) < 5) {
         Helper::renderJSONErorr("Password must be at least 5 symbols");
     }
     // Check user
     $user = User::model()->find('username=:username', array(':username' => $username));
     if ($user) {
         Helper::renderJSONErorr("Username occupated");
     }
     // Create new user
     $model = new User();
     $model->username = $username;
     $model->password = CPasswordHelper::hashPassword($password);
     if ($model->save()) {
         Helper::renderJSON($model);
     }
     // Catch errors
     $errors = [];
     foreach ($model->errors as $attribute => $attr_errors) {
         foreach ($attr_errors as $attr_error) {
             $errors[] = "Attribute {$attribute}: {$attr_error}";
         }
     }
     Helper::renderJSONErorr(implode("\n", $errors));
 }
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Propietario();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Propietario'])) {
         $model->attributes = $_POST['Propietario'];
         $usuario = new Usuario();
         $model->rut = Tools::removeDots($model->rut);
         $usuario->user = $model->rut;
         $arr = explode("-", $model->rut);
         $usuario->clave = CPasswordHelper::hashPassword($arr[0]);
         $usuario->rol = "propietario";
         $usuario->nombre = $_POST['Propietario']['nombre'];
         $usuario->email = $_POST['Propietario']['email'];
         $usuario->apellido = $_POST['Propietario']['apellido'];
         $model->usuario_id = 1;
         if ($model->validate()) {
             if ($usuario->validate()) {
                 if ($usuario->save()) {
                     $model->usuario_id = $usuario->id;
                     if ($model->save()) {
                         $auth = Yii::app()->authManager;
                         Authassignment::model()->deleteAllByAttributes(array('userid' => $usuario->id));
                         $auth->revoke($usuario->rol, $model->usuario_id);
                         $auth->assign($usuario->rol, $model->usuario_id);
                         $this->redirect(array('view', 'id' => $model->id));
                     }
                 }
             }
         }
     }
     $this->render('create', array('model' => $model));
 }
Example #5
0
 public function __set($name, $value)
 {
     if ($name === 'password') {
         $value = CPasswordHelper::hashPassword($value);
     }
     parent::__set($name, $value);
     // TODO: Change the autogenerated stub
 }
Example #6
0
 /**
  *
  * 某些系统不支持crypt加密。只能用md5加密了
  *
  *
  * @param password        客户端传递过来的密码
  *@param array $params
  * @return string
  */
 public function hashPassword($password, array $params = array())
 {
     if (!function_exists('crypt')) {
         return CPasswordHelper::hashPassword($password);
     } else {
         return md5($password);
     }
 }
 public function changePassword()
 {
     $user = Yii::app()->controller->user;
     $user->password = CPasswordHelper::hashPassword($this->newPassword);
     if ($user->save()) {
         return true;
     } else {
         return false;
     }
 }
 /**
  * Hashes a given password with the blowfish encryption algorithm.
  *
  * @param string $string       The string to hash
  * @param bool   $validateHash If you want to validate the just generated hash. Will throw an exception if
  *                             validation fails.
  *
  * @throws Exception
  * @return string The hash.
  */
 public function hashPassword($string, $validateHash = false)
 {
     $hash = \CPasswordHelper::hashPassword($string, $this->_blowFishHashCost);
     if ($validateHash) {
         if (!$this->checkPassword($string, $hash)) {
             throw new Exception(Craft::t('Could not hash the given string.'));
         }
     }
     return $hash;
 }
Example #9
0
 /**
  * Este método se llama cuando inserto o edito un registro.
  */
 public function beforeSave()
 {
     if (parent::beforeSave()) {
         if (!empty($this->newPassword) && $this->newPassword == $this->rePassword) {
             $this->password = CPasswordHelper::hashPassword($this->newPassword);
         }
         return true;
     }
     return false;
 }
 /**
  * Updates the users password.
  * @param bool $runValidation
  */
 public function save($runValidation = true)
 {
     if ($runValidation && !$this->validate()) {
         return false;
     }
     /** @var AccountModule $account */
     $account = Yii::app()->getModule('account');
     $this->user->{$account->passwordField} = CPasswordHelper::hashPassword($this->new_password);
     return $this->user->save(false);
 }
Example #11
0
 public function beforeSave()
 {
     if ($this->isNewRecord) {
         $this->created = new CDbExpression('NOW()');
     }
     $this->updated = new CDbExpression('NOW()');
     if ($this->pass != '') {
         $this->password = CPasswordHelper::hashPassword($this->pass);
     }
     return parent::beforeSave();
 }
Example #12
0
 /**
  * Password hashing
  * @return bool
  */
 protected function beforeSave()
 {
     if (parent::beforeSave()) {
         if ($this->isNewRecord) {
             $this->password = CPasswordHelper::hashPassword($this->password);
         }
         return true;
     } else {
         return false;
     }
 }
 /**
  * Updates the users password.
  * @param bool $runValidation
  */
 public function save($runValidation = true)
 {
     if ($runValidation && !$this->validate()) {
         return false;
     }
     /** @var AccountModule $account */
     $account = Yii::app()->getModule('account');
     //to avoid indirect modification error message
     $user = $this->user;
     $user->{$account->passwordField} = CPasswordHelper::hashPassword($this->new_password);
     return $user->save(false);
 }
Example #14
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionRegister()
 {
     $model = new User();
     $this->performAjaxValidation($model);
     if (isset($_POST['User'])) {
         $model->attributes = $_POST['User'];
         $model->password = CPasswordHelper::hashPassword($model->password);
         if ($model->save()) {
             $this->redirect(array('site/login'));
         }
     }
     $this->render('register', array('model' => $model));
 }
Example #15
0
 protected function beforeSave()
 {
     $this->username = trim(strtolower($this->username));
     if ($this->password === '') {
         $model2 = User::model()->findByPk($this->id);
         $this->password = $model2->password;
         $this->repeatPassword = $model2->password;
     } elseif ($this->repeatPassword !== null) {
         $this->unecryptedPassword = $this->password;
         $this->password = CPasswordHelper::hashPassword($this->password);
         $this->repeatPassword = CPasswordHelper::hashPassword($this->repeatPassword);
     }
     return true;
 }
 /**
  * Update password for the current user.
  */
 public function actionUpdatePassword()
 {
     $model = new UpdatePasswordForm();
     if (isset($_POST['UpdatePasswordForm'])) {
         $model->attributes = $_POST['UpdatePasswordForm'];
         if ($model->validate()) {
             Yii::app()->user->user->password = CPasswordHelper::hashPassword($model->new_password);
             Yii::app()->user->user->save();
             Yii::app()->user->setFlash('success', Yii::t("app", "Le mot de passe de votre compte a été modifié. Veuillez dès maintenant utiliser votre nouveau mot de passe pour vous identifier."));
             $this->redirect("index");
         }
     }
     $this->render('updatePassword', array('model' => $model));
 }
 /**
  * Updates a particular model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id the ID of the model to be updated
  */
 public function actionUpdate($id)
 {
     $model = $this->loadModel($id);
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Usuarios'])) {
         $model->attributes = $_POST['Usuarios'];
         $model->Contrasena = CPasswordHelper::hashPassword($model->Contrasena);
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->idUsuario));
         }
     }
     $this->render('update', array('model' => $model));
 }
 /**
  * Updates the users password.
  * @param bool $runValidation
  */
 public function save($runValidation = true)
 {
     if ($runValidation && !$this->validate()) {
         return false;
     }
     /** @var AccountModule $account */
     $account = Yii::app()->getModule('account');
     $this->user->{$account->passwordField} = CPasswordHelper::hashPassword($this->new_password);
     if (!$this->user->save(false)) {
         return false;
     }
     if (!$this->userIdentity->authenticate() || !Yii::app()->user->login($this->userIdentity)) {
         return false;
     }
     Yii::app()->tokenManager->useToken('AccountLostPassword', $this->user_id, $this->token);
     return true;
 }
Example #19
0
 public function authenticate()
 {
     $record = Employee::model()->findByAttributes(array('name' => $this->username));
     $hash = CPasswordHelper::hashPassword($record->password);
     if ($record === null) {
         $this->errorCode = self::ERROR_USERNAME_INVALID;
     } else {
         if (!CPasswordHelper::verifyPassword($this->password, $hash)) {
             $this->errorCode = self::ERROR_PASSWORD_INVALID;
         } else {
             $this->_id = $record->employee_id;
             $this->setState('title', $record->name);
             $this->errorCode = self::ERROR_NONE;
         }
     }
     return !$this->errorCode;
 }
Example #20
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Usuario();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Usuario'])) {
         $model->attributes = $_POST['Usuario'];
         $model->clave = CPasswordHelper::hashPassword($model->clave);
         if ($model->validate()) {
             if ($model->save()) {
                 $auth = Yii::app()->authManager;
                 $auth->assign($model->rol, $model->id);
                 $this->redirect(array('view', 'id' => $model->id));
             }
         }
     }
     $this->render('create', array('model' => $model));
 }
 /**
  * Updates a particular model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id the ID of the model to be updated
  */
 public function actionUpdate($id)
 {
     $model = $this->loadModel($id);
     if (!WebUser::isAdmin()) {
         if (WebUser::Id() != $id) {
             throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
         }
     }
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Users'])) {
         $model->attributes = $_POST['Users'];
         $model->password = CPasswordHelper::hashPassword(trim($model->password));
         if ($model->save()) {
             $this->setFlashSuccess('User password for <strong>' . $model->username . '</strong> successfully changed');
             $this->redirect(array('admin'));
         }
     }
     $this->render('update', array('model' => $model));
 }
 /**
  * Displays the login page
  */
 public function actionLogin()
 {
     $model = new LoginForm();
     // if it is ajax validation request
     if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
         $model->contrasena = CPasswordHelper::hashPassword($model->contrasena);
         echo CActiveForm::validate($model);
         Yii::app()->end();
     }
     // collect user input data
     if (isset($_POST['LoginForm'])) {
         $model->attributes = $_POST['LoginForm'];
         // validate user input and redirect to the previous page if valid
         if ($model->validate() && $model->login()) {
             $this->redirect("index.php?r=citas/index");
         }
     }
     // display the login form
     $this->render('login', array('model' => $model));
 }
Example #23
0
 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;
 }
Example #24
0
 public function save()
 {
     $app = Yii::app();
     $transaction = $app->db->beginTransaction();
     try {
         if (!$this->validate()) {
             throw new CDbException('参数出错', 0, []);
         }
         $user = User::model()->findByPk($this->id);
         if (!$user) {
             throw new CDbException('参数出错', 1, []);
         }
         if ($user->state == 1) {
             throw new CDbException('不能修改的用户', 0, []);
         }
         $attributes = [];
         if (!empty($this->password)) {
             $attributes['password'] = CPasswordHelper::hashPassword($this->password);
             $attributes['uuid'] = $app->getSecurityManager()->generateUUID($user->id . $attributes['password']);
         }
         if ($this->approved == true) {
             $attributes['approved'] = 5;
         }
         $attributes = array_merge($attributes, ['realname' => $this->realname, 'nickname' => $this->nickname, 'email' => $this->email]);
         if ($this->state >= 0) {
             $attributes['state'] = $this->state ? 2 : 0;
         }
         $user->attributes = $attributes;
         if ($user->save() === false) {
             throw new CDbException('更新用户出错', 30, $user->getErrors());
         }
         $transaction->commit();
     } catch (CDbException $e) {
         $transaction->rollback();
         $this->addErrors($e->errorInfo);
         return false;
     }
     return true;
 }
Example #25
0
 /**
  * Переопределенная функция сохранения пользователя.
  * Помимо сохранения данных пользователя, присваиваются выбранные права доступа
  * 
  * @param type $runValidation
  * @param type $attributes
  * @throws CHttpException
  */
 public function Save($runValidation = true, $attributes = null)
 {
     /* $selectedRows - массив выбранных ролей пользователя */
     $selectedRows = (string) filter_input(INPUT_POST, 'items') !== '' ? json_decode((string) filter_input(INPUT_POST, 'items'), true) : [];
     /* $_POST['oper'] может быть "edit" или "add", редактирование или добавление новой записи */
     if ((string) filter_input(INPUT_POST, 'oper') === '') {
         throw new CHttpException(500, 'Отсутствует POST переменная "oper"');
     }
     /* ИД пользователя, который редактируется, если необходим */
     $editid = (string) filter_input(INPUT_POST, 'editid');
     if ((string) filter_input(INPUT_POST, 'oper') === 'edit' && $editid === '') {
         throw new CHttpException(500, 'Отсутствует POST переменная "editid"');
     }
     /* Имя сценария, может быть "NewUser" - проверяет введеный пароль и подтверждение на совпадение.
      * Используется при добавлении нового пользотваеля, или смене пароля */
     $scenario = (string) filter_input(INPUT_POST, 'scenario');
     if ($scenario === 'NewUser') {
         $this->password = CPasswordHelper::hashPassword($this->password);
     }
     /* Хэшируем новый пароль */
     /* Сохраняем модель пользователя и присваиваем роли */
     if (parent::save($runValidation, $attributes) !== false) {
         $auth = Yii::app()->authManager;
         /* Удаляем все роли пользователя при сохранении изменений профиля пользователя */
         if ($editid !== '' && $scenario === '') {
             $assigned_roles = Yii::app()->authManager->getAuthAssignments($editid);
             foreach (array_keys($assigned_roles) as $AuthItem) {
                 $auth->revoke($AuthItem, $editid);
             }
         }
         /* Присваиваем выбранные роли пользователю */
         if (count((array) $selectedRows) > 0) {
             foreach (array_keys($selectedRows) as $AuthItem) {
                 $auth->assign($AuthItem, parent::getPrimaryKey());
             }
             Yii::app()->authManager->save();
         }
     }
 }
Example #26
0
 public function save()
 {
     $app = Yii::app();
     $transaction = $app->db->beginTransaction();
     try {
         if (!$this->validate()) {
             throw new CDbException('参数出错', 0, []);
         }
         $user = User::model()->findByPk(Yii::app()->user->getId());
         if (!$user) {
             throw new CDbException('参数出错', 1, []);
         }
         $user->attributes = array('password' => CPasswordHelper::hashPassword($this->password));
         if ($user->save() === false) {
             throw new CDbException('修改密码出错', 30, $user->getErrors());
         }
         $transaction->commit();
     } catch (CDbException $e) {
         $transaction->rollback();
         $this->addErrors($e->errorInfo);
         return false;
     }
     return true;
 }
 public function registerByAdmin()
 {
     $this->formAfterCheck();
     if (!$this->hasErrors()) {
         $user = new Users('create');
         $user->username = $this->username;
         $user->email = $this->email;
         $user->password = CPasswordHelper::hashPassword($this->password);
         $user->email_verified = intval($this->verified);
         if ($user->save()) {
             MailHelper::sendUserCredentials($this->username, $this->email, $this->password);
             if (!$this->verified) {
                 $url_maintenance = $user->getMaintenanceUrl();
                 $user->save();
                 MailHelper::sendRegisterConfirmMail($user->username, $user->email, $url_maintenance);
             }
             ListingNames::model()->getUserIgnoreList($user->id);
             return true;
         } else {
             $this->addErrors($user->getErrors());
         }
     }
     return false;
 }
 /**
  * Updates a particular model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id the ID of the model to be updated
  */
 public function actionUpdate($id)
 {
     $model = $this->loadModel($id);
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['UserDefn'])) {
         $model->attributes = $_POST['UserDefn'];
         if ($model->validate()) {
             //Check old password
             if ($model->validatePassword($model->oldPassword)) {
                 $model->username = strtolower($model->username);
                 $encryptedPassword = CPasswordHelper::hashPassword($model->password1);
                 $model->password = $encryptedPassword;
                 if ($model->save()) {
                     $this->redirect(array('view', 'id' => $model->user_id));
                 }
             } else {
                 Yii::app()->user->setFlash("error", 'Wrong old password');
                 $model->addError('oldPassword', 'Wrong old password');
             }
         }
     }
     $this->render('update', array('model' => $model));
 }
Example #29
0
 public function actionOlvidaste()
 {
     $model = new OlvidasteForm();
     if (isset($_POST['OlvidasteForm'])) {
         $model->attributes = $_POST['OlvidasteForm'];
         $rand = rand(1000, 10000);
         $usuario = Usuario::model()->findByAttributes(array('user' => $model->user));
         if ($usuario != null) {
             if (mail($usuario->email, "Cambio de Clave", "" . "Estimado, ha solicitado el cambio de clave para el usuario '" . $model->user . "' para la aplicación inmobiliaria\n" . "Su nueva clave es " . $rand . "\nPor favor cámbiela cuanto antes desde Mi Cuenta / Cambiar mi Clave.")) {
                 $usuario->clave = CPasswordHelper::hashPassword($rand);
                 $usuario->save();
                 Yii::app()->user->setFlash('profileMessage', 'Su nueva clave ha sido enviada a su correo.');
                 $this->refresh();
             }
         }
     }
     $this->render('olvidaste', array('model' => $model));
 }
Example #30
0
 /**
  * 生成密码
  * @return string
  */
 public static function createPassword($password = '')
 {
     //判断加密方式
     $settings = Setting::model()->find('scope = :scope AND variable = :variable', array(':scope' => 'base', ':variable' => 'encrypt'));
     switch ($settings->value) {
         case 'md5':
             $pwd = md5($password);
             break;
         case 'crypt':
             $pwd = CPasswordHelper::hashPassword($password, 8);
             break;
         default:
             throw new CHttpException(500, 'Unknown Encrypt Method!');
             break;
     }
     return $pwd;
 }