Ejemplo n.º 1
0
 /**
  * Регистрация пользователя
  *
  * @return User|null сохранить модель или null при ошибке сохранения
  */
 public function signup()
 {
     if ($this->validate()) {
         $user = new User();
         $user->username = $this->username;
         $user->email = $this->email;
         $user->setPassword($this->password);
         $user->generateAuthKey();
         $user->save();
         return $user;
     }
     return null;
 }
Ejemplo n.º 2
0
 /**
  * Finds user by [[phone]]
  *
  * @return User|null
  */
 public function getUser()
 {
     if ($this->_user === false) {
         $this->_user = User::findByPhone($this->phone);
     }
     return $this->_user;
 }
Ejemplo n.º 3
0
 /**
  * Finds user by [[username]]
  *
  * @return User|null
  */
 public function getUser()
 {
     if ($this->_user === false) {
         $this->_user = User::findByUsername($this->username);
     }
     return $this->_user;
 }
Ejemplo n.º 4
0
 public function getUser()
 {
     if ($this->_user === false) {
         $this->_user = User::findByProperties(['phone' => $this->phone]);
     }
     return $this->_user;
 }
Ejemplo n.º 5
0
 /**
  * Lists all Estate models.
  *
  * @return mixed
  */
 public function actionIndex()
 {
     $searchModel = new EstateSearch();
     $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
     $user = User::findOne(Yii::$app->user->id);
     $isManager = LinkManager::isAccessible($user->id);
     return $this->render('index', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'user' => $user, 'isManager' => $isManager]);
 }
Ejemplo n.º 6
0
 public function search($params)
 {
     $query = User::find();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     if (!($this->load($params) && $this->validate())) {
         return $dataProvider;
     }
     $query->andFilterWhere(['id' => $this->id, 'role' => $this->role, 'status' => $this->status, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, 'approve_newsletter' => $this->approve_newsletter]);
     $query->andFilterWhere(['like', 'username', $this->username])->andFilterWhere(['like', 'password', $this->password])->andFilterWhere(['like', 'auth_key', $this->auth_key])->andFilterWhere(['like', 'password_hash', $this->password_hash])->andFilterWhere(['like', 'password_reset_token', $this->password_reset_token])->andFilterWhere(['like', 'email', $this->email])->andFilterWhere(['like', 'phone', $this->phone]);
     return $dataProvider;
 }
Ejemplo n.º 7
0
 /**
  * Creates a form model given a token.
  *
  * @param  string                          $token
  * @param  array                           $config name-value pairs that will be used to initialize the object properties
  * @throws \yii\base\InvalidParamException if token is empty or not valid
  */
 public function __construct($token, $config = [])
 {
     if (empty($token) || !is_string($token)) {
         throw new InvalidParamException(Yii::t('app', 'RESET_WRONG_TOKEN_STRING'));
     }
     $this->_user = User::findByPasswordResetToken($token);
     if (!$this->_user) {
         throw new InvalidParamException(Yii::t('app', 'RESET_WRONG_TOKEN'));
     }
     parent::__construct($config);
 }
Ejemplo n.º 8
0
 /**
  * Creates a form model given a token.
  *
  * @param  string                          $token
  * @param  array                           $config name-value pairs that will be used to initialize the object properties
  * @throws \yii\base\InvalidParamException if token is empty or not valid
  */
 public function __construct($token, $config = [])
 {
     if (empty($token) || !is_string($token)) {
         throw new InvalidParamException('Password reset token cannot be blank.');
     }
     $this->_user = User::findByPasswordResetToken($token);
     if (!$this->_user) {
         throw new InvalidParamException('Wrong password reset token.');
     }
     parent::__construct($config);
 }
 /**
  * Sends an email with a link, for resetting the password.
  *
  * @return boolean whether the email was send
  */
 public function sendEmail()
 {
     /** @var User $user */
     $user = User::findOne(['status' => User::STATUS_ACTIVE, 'email' => $this->email]);
     if ($user) {
         $user->generatePasswordResetToken();
         if ($user->save()) {
             return \Yii::$app->mail->compose('passwordResetToken', ['user' => $user])->setFrom([\Yii::$app->params['supportEmail'] => \Yii::$app->name . ' robot'])->setTo($this->email)->setSubject('Password reset for ' . \Yii::$app->name)->send();
         }
     }
     return false;
 }
Ejemplo n.º 10
0
 /**
  * Поиск записей по переданным критериям.
  * @param array|null Массив с критериями для выборки.
  * @return ActiveDataProvider dataProvider с результатами поиска.
  */
 public function search($params)
 {
     $query = User::find();
     $dataProvider = new ActiveDataProvider(['query' => $query, 'pagination' => ['pageSize' => Yii::$app->getModule('user')->recordsPerPage]]);
     if (!($this->load($params) && $this->validate())) {
         return $dataProvider;
     }
     $this->addCondition($query, 'username', true);
     $this->addCondition($query, 'email', true);
     $this->addCondition($query, 'role');
     $this->addCondition($query, 'status');
     return $dataProvider;
 }
 public function testSendEmailCorrectUser()
 {
     $model = new PasswordResetRequestForm();
     $model->email = $this->user[0]['email'];
     $user = User::findOne(['password_reset_token' => $this->user[0]['password_reset_token']]);
     expect('email sent', $model->sendEmail())->true();
     expect('user has valid token', $user->password_reset_token)->notNull();
     $this->specify('message has correct format', function () use($model) {
         expect('message file exists', file_exists($this->getMessageFile()))->true();
         $message = file_get_contents($this->getMessageFile());
         expect('message "from" is correct', $message)->contains(Yii::$app->params['supportEmail']);
         expect('message "to" is correct', $message)->contains($model->email);
     });
 }
Ejemplo n.º 12
0
 /**
  * Sends an email with a link, for resetting the password.
  *
  * @return boolean whether the email was send
  */
 public function sendEmail()
 {
     /** @var $user User * */
     $user = User::findOne(['status' => User::STATUS_ACTIVE, 'phone' => $this->phone]);
     if ($user && !($this->haveEmail = mb_strlen($user->getEmail()) > 5)) {
         return false;
     }
     if (!User::isPasswordResetTokenValid($user->password_reset_token)) {
         $user->generatePasswordResetToken();
     }
     if ($user->save()) {
         $headers = "MIME-Version: 1.0\r\n";
         $headers .= "Content-type: text/html; charset=UTF-8\r\n";
         $headers .= "From: Bulk.kz ROBOT <*****@*****.**>\r\n";
         return mail($user->getEmail(), Yii::t('app', 'RESET_EMAIL_SUBJECT') . $user->getUsername(), Yii::t('app', 'RESET_EMAIL_MESSAGE') . Html::a(Yii::t('app', 'RESET_EMAIL_LINK'), 'http://bulk.kz/reset-password?token=' . $user->getPasswordResetToken()), $headers);
     }
     return false;
 }
Ejemplo n.º 13
0
 public function actionDelete($email)
 {
     $exitCode = 0;
     $this->stdout("Deleting {$email}: ");
     $deleteCounter = User::deleteAll(['email' => $email]);
     if (1 === $deleteCounter) {
         $this->msgSuccess();
     } else {
         //Error Handling
         if ($deleteCounter === 0) {
             $exitCode = 1;
             $this->msgError("Account Not Found");
         } else {
             $this->msgError("Multiple Accounts Deleted - DB may be in Inconsistent State");
             $this->stderr("Multiple Accounts Deleted - DB may be in Inconsistent State", Console::BG_BLUE);
             $exitCode = 2;
         }
     }
     $this->stdout("\n");
     return $exitCode;
 }
Ejemplo n.º 14
0
 /**
  * Signs user up.
  *
  * @return User|null the saved model or null if saving fails
  */
 public function signup()
 {
     if ($this->validate()) {
         $user = new User();
         $user->username = $this->username;
         $user->phone = $this->phone;
         $this->password = rand(100000, 999999);
         //Yii::$app->security->generateRandomString(6);
         $user->setTempPassword($this->password);
         $user->setPassword($this->password);
         $user->generateAuthKey();
         if ($user->save()) {
             return $user;
         } else {
             die($user);
         }
     }
     return null;
 }
Ejemplo n.º 15
0
<?php

/**
 * Created by PhpStorm.
 * User: developer
 * Date: 18.08.14
 * Time: 17:31
 */
use yii\web\View;
use yii\helpers\Html;
use common\modules\user\models\User;
?>

<noindex>
    <?php 
if (Yii::$app->user->isGuest) {
    echo Html::a('Вход', ['/login'], ['rel' => 'nofollow', 'class' => 'login']);
    echo " &nbsp;|&nbsp; ";
    echo Html::a('Регистрация', ['/registration'], ['rel' => 'nofollow', 'class' => 'registration']);
} else {
    echo Html::a(\common\helpers\CString::subStr(User::getUserName(), 0, 18, ' '), ['/cabinet'], ['rel' => 'nofollow', 'class' => 'welcome-link']);
    echo " &nbsp;|&nbsp; ";
    echo Html::a('Выход', ['/logout'], ['rel' => 'nofollow', 'class' => 'logout']);
}
?>
    <div class="user-content-block">
    </div>
</noindex>

Ejemplo n.º 16
0
 /**
  * Getter current User
  *
  * @return User
  */
 public function getUser()
 {
     return User::findOne($this->user_id);
 }
Ejemplo n.º 17
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getCommentAuthor()
 {
     return $this->hasOne(User::className(), ['id' => 'comment_author']);
 }
Ejemplo n.º 18
0
 /**
  * Display list of all users in json format
  *
  * @param string $search - username
  * @return mixed
  */
 public function actionUserList($search = null, $id = null)
 {
     $out = ['more' => false];
     if (!is_null($search)) {
         $query = new Query();
         $query->select('id, username AS text')->from(User::tableName())->where(['like', 'username', $search])->limit(20);
         $command = $query->createCommand();
         $data = $command->queryAll();
         $out['results'] = array_values($data);
     } elseif ($id > 0) {
         $out['results'] = ['id' => $id, 'text' => $this->findModel($id)->username];
     } else {
         $out['results'] = ['id' => 0, 'text' => 'No matching records found'];
     }
     echo Json::encode($out);
 }
Ejemplo n.º 19
0
 public function getUser()
 {
     return $this->hasOne(User::className(), ['id' => 'user_id']);
 }
Ejemplo n.º 20
0
 /**
  * @param $email
  * @param $key
  * @return \yii\web\Response
  */
 public function actionActivation($email, $key)
 {
     if ($model = User::find()->where(['and', 'email = :email', 'auth_key = :auth_key'], [':email' => $email, ':auth_key' => $key])->inactive()->one()) {
         $model->setScenario('activation');
         // В случае если запись с введеным e-mail-ом и ключом была найдена, обновляем её и оповещаем пользователя об успешной активации.
         if ($model->save(false)) {
             Yii::$app->session->setFlash('success', Yii::t('user', 'Ваша учётная запись была успешно активирована. Теперь вы можете авторизоватся, и полноценно использовать услуги сайта. Спасибо!'));
         }
     } else {
         // В случае если запись с введеным e-mail-ом и ключом не был найден, оповещаем пользователя об неудачной активации.
         Yii::$app->session->setFlash('danger', Yii::t('user', 'Неверный код активации или возмоможно аккаунт был уже ранее активирован. Проверьте пожалуйста правильность ссылки, или напишите администратору.'));
     }
     // Перенаправляем пользователя на главную страницу сайта.
     return $this->goHome();
 }
Ejemplo n.º 21
0
<?php

use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
use yii\web\JsExpression;
use yii\widgets\Pjax;
use common\modules\user\models\User;
/**
 * @var $this yii\web\View
 * @var $comments array Array of common\models\Comment
 * @var $commentForm common\models\Comment
**/
$user = User::findOne(Yii::$app->user->id);
$avatar = $user->getAsset();
?>

<?php 
$form = ActiveForm::begin(['id' => 'comment-form', 'options' => ['class' => 'default-form'], 'action' => Url::to('/site/comment-add')]);
?>

<div class="user-photo">
    <a href="<?php 
echo Url::to(['user/profile']);
?>
"><img src="<?php 
echo $avatar->getFileUrl();
?>
"></a>
</div>
<div class="field textarea-field comment-field">
Ejemplo n.º 22
0
 public static function getAllLikeJsList()
 {
     $temp_js_list = '';
     $users = User::find()->orderBy('username ASC')->select(['email', 'username', 'approve_newsletter'])->all();
     foreach ($users as $user) {
         if ($user->email && $user->approve_newsletter) {
             $temp_js_list[$user->email] = $user->username;
         }
     }
     return $temp_js_list;
 }
Ejemplo n.º 23
0
 /**
  * Show profile form for update information
  *
  * @return string|\yii\web\Response
  */
 public function actionProfile()
 {
     /** @var ProfileForm $model */
     $model = new ProfileForm();
     /** @var User $user */
     $user = User::getCurrentUser();
     $model->setUsername($user->getUsername());
     $model->setEmail($user->getEmail());
     $model->setMailNotifications($user->getMailNotifications());
     if ($model->load(Yii::$app->request->post()) && $model->validate()) {
         /** @var User $user */
         $user = User::getCurrentUser();
         $user->username = $model->getUsername();
         $user->email = $model->getEmail();
         if (mb_strlen($model->getPassword()) > 5) {
             $user->setPassword($model->getPassword());
             $user->generateAuthKey();
         }
         if (mb_strlen($user->email) <= 5) {
             $user->setMailNotifications(false);
         }
         if ($user->save()) {
             Yii::$app->session->setFlash('success', Yii::t('app', 'FLASH_PROFILE_UPDATED'));
             return $this->redirect(['/estate']);
         } else {
             Yii::$app->session->setFlash('error', Yii::t('app', 'FLASH_PROFILE_FAILED'));
             return $this->redirect(['/estate']);
         }
     }
     return $this->render('profile', ['model' => $model]);
 }
Ejemplo n.º 24
0
 /**
  * @return Автор страницы.
  */
 public function getAuthor()
 {
     return $this->hasOne(User::className(), ['id' => 'author_id']);
 }
Ejemplo n.º 25
0
 public function actionServiceItem($id)
 {
     $service = Services::findOne($id);
     if ($service && !\Yii::$app->user->isGuest) {
         $user = User::findOne(\Yii::$app->user->id);
         $persAcc = PersonalAccount::find()->where('user_id = :user_id', [':user_id' => $user->id])->andWhere('service_id = :service_id', [':service_id' => $id])->one();
         $history = PaymentData::find()->where('service_id = :service_id', [':service_id' => $id])->andWhere('personal_acc_id = :personal_acc_id', [':personal_acc_id' => $persAcc->id])->all();
         return $this->render('service-item', ['service' => $service, 'history' => $history, 'persAcc' => $persAcc]);
     } else {
         return false;
     }
 }
Ejemplo n.º 26
0
 private function sendPasswordResetEmail($phone)
 {
     $user = User::find(['status' => User::STATUS_ACTIVE, 'phone' => $phone])->one();
     if (!$user) {
         return false;
     }
     $user->password_reset_token = Security::generateRandomKey();
     $user->password = User::generatePassword();
     if ($user->save(false)) {
         $result = \Yii::$app->sms->sms_send(preg_replace("/[^0-9]/", '', $user->phone), 'Ваш новый пароль: ' . $user->password, "Kvadro");
         return true;
     }
     return false;
 }
Ejemplo n.º 27
0
 /**
  * @inheritdoc
  */
 public function attributes()
 {
     // add related fields to searchable attributes
     return array_merge(parent::attributes(), ['profile.full_name']);
 }
Ejemplo n.º 28
0
 /**
  * This method is called after each cest class test method, even if test failed.
  * @param \Codeception\Event\Test $event
  */
 public function _after($event)
 {
     User::deleteAll(['email' => '*****@*****.**', 'username' => 'tester']);
 }
Ejemplo n.º 29
0
 /**
  * Finds the User model based on its primary key value.
  * If the model is not found, a 404 HTTP exception will be thrown.
  * @param integer $id
  * @return User the loaded model
  * @throws NotFoundHttpException if the model cannot be found
  */
 protected function findModel($id)
 {
     if (($model = User::findOne($id)) !== null) {
         return $model;
     } else {
         throw new NotFoundHttpException('The requested page does not exist.');
     }
 }
Ejemplo n.º 30
0
 public function actionGetHistoryForService()
 {
     $token = $this->getToken();
     if ($token) {
         $user = User::find()->where('password_reset_token = :token', [':token' => $token])->one();
         if (!empty($user)) {
             if (!empty($_POST['bill']) && !empty($_POST['service_id'])) {
                 $service = Services::find()->where('id = :id', [':id' => $_POST['service_id']])->one();
                 if ($service) {
                     $persAcc = PersonalAccount::find()->where('value = :value', [':value' => $_POST['bill']])->one();
                     if ($persAcc) {
                         $result = ['status' => ['code' => 200, 'message' => 'ОК'], 'data' => ['tariff' => $service->tariff, 'tariff_measure' => $service->tariff_measure, 'history' => []]];
                         $history = PaymentData::find()->where('personal_acc_id = :personal_acc_id', [':personal_acc_id' => $persAcc->id])->andWhere('service_id = :service_id', [':service_id' => $_POST['service_id']])->all();
                         if ($history) {
                             foreach ($history as $index => $payment) {
                                 $result['data']['history'][$index] = ['date' => "" . $payment->kvit_date, 'dept_end' => $payment->dept_end, 'dept_begin' => $payment->dept_begin, 'enrolled' => $payment->enrolled, 'paid' => $payment->paid, 'bill' => $_POST['bill']];
                             }
                         }
                     } else {
                         $result = ['status' => ['code' => 409, 'message' => 'Лицевой счет не найден']];
                     }
                 } else {
                     $result = ['status' => ['code' => 406, 'message' => 'Услуга не найдена']];
                 }
             } else {
                 $result = ['status' => ['code' => 403, 'message' => 'Не все обязательные поля заполнены']];
             }
         } else {
             $result = ['status' => ['code' => 402, 'message' => 'Пользователь не найден']];
         }
     } else {
         $result = ['status' => ['code' => 400, 'message' => 'Значение Token не задано']];
     }
     return Json::encode($result);
 }