示例#1
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->email = $this->email;
         $user->setPassword($this->password);
         $user->generateAuthKey();
         // Если необходима активация email адресов
         if (Yii::$app->params['emailActivation'] == true) {
             $user->status = $user::STATUS_NOT_ACTIVE;
         }
         $transaction = Yii::$app->db->beginTransaction();
         if ($r = $user->save()) {
             $profile = new UserProfile();
             $profile->user_id = $user->id;
             if ($profile->save()) {
                 $transaction->commit();
                 // Генерируем токен для подтверждения email
                 $user->generateEmailConfirmToken();
                 // Сохраняем его в базе
                 $user->save();
                 // Отправляем письмо
                 $user->sendEmailConfirm();
                 return $user;
             } else {
                 $transaction->rollBack();
             }
         } else {
             $transaction->rollBack();
         }
     }
     return null;
 }
示例#2
0
 /**
  * @inheritdoc
  */
 public function run()
 {
     $user = User::find()->where(['username' => \Yii::$app->request->get('username')])->joinWith('profile')->limit(1)->one();
     if ($user) {
         return $this->render('sidebar', ['user' => $user]);
     }
 }
示例#3
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('Код для смены пароля не может быть пустым.');
     }
     $this->_user = User::findByPasswordResetToken($token);
     if (!$this->_user) {
         throw new InvalidParamException('Неверный код для смены пароля. Возможно, истек срок его действия. Запросите новую ссылку на восстановление пароля.');
     }
     parent::__construct($config);
 }
示例#4
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 ($token != 'none') {
         if (!empty($token) && is_string($token)) {
             if ($this->_user = User::findByEmailConfirmToken($token)) {
                 $this->userFound = true;
             }
         }
     }
     parent::__construct($config);
 }
示例#5
0
 /**
  * Finds user by [[username]]
  *
  * @return User|null
  */
 protected function getUser()
 {
     if ($this->_user === null) {
         if (mb_strpos($this->username, '@')) {
             $this->_user = User::findByEmail($this->username);
         } else {
             $this->_user = User::findByUsername($this->username);
         }
         //var_dump($this->_user);
     }
     return $this->_user;
 }
示例#6
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = User::find();
     $dataProvider = new ActiveDataProvider(['query' => $query, 'sort' => ['defaultOrder' => ['created_at' => SORT_DESC]]]);
     $this->load($params);
     if (!$this->validate()) {
         // uncomment the following line if you do not want to return any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     $query->andFilterWhere(['id' => $this->id, 'status' => $this->status, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at]);
     $query->andFilterWhere(['like', 'username', $this->username])->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_confirm_token', $this->email_confirm_token])->andFilterWhere(['like', 'email', $this->email]);
     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);
     });
 }
示例#8
0
文件: Files.php 项目: bessonov87/bw
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getUser()
 {
     return $this->hasOne(User::className(), ['id' => 'user_id']);
 }
示例#9
0
 public static function getSiteSummary()
 {
     $today_begin = date("Y-m-d") . " 00:00:00";
     $today_end = date("Y-m-d") . " 23:59:59";
     $yesterday_begin = date("Y-m-d 00:00:00", time() - 86400);
     $yesterday_end = date("Y-m-d 23:59:59", time() - 86400);
     // Статьи
     $summary['postsCount'] = Post::find()->count();
     $summary['postsToday'] = Post::find()->where(['between', 'date', $today_begin, $today_end])->count();
     $summary['postsYesterday'] = Post::find()->where(['between', 'date', $yesterday_begin, $yesterday_end])->count();
     // Пользователи
     $summary['usersCount'] = User::find()->count();
     $summary['usersToday'] = User::find()->where(['between', 'created_at', strtotime($today_begin), strtotime($today_end)])->count();
     $summary['usersYesterday'] = User::find()->where(['between', 'created_at', strtotime($yesterday_begin), strtotime($yesterday_end)])->count();
     // Комментарии
     $summary['commentsCount'] = Comment::find()->count();
     $summary['commentsToday'] = Comment::find()->where(['between', 'date', $today_begin, $today_end])->count();
     $summary['commentsYesterday'] = Comment::find()->where(['between', 'date', $yesterday_begin, $yesterday_end])->count();
     // Ошибки
     $summary['errorsCount'] = Log::find()->count();
     $summary['errorsToday'] = Log::find()->where(['between', 'log_time', strtotime($today_begin), strtotime($today_end)])->count();
     $summary['errorsYesterday'] = Log::find()->where(['between', 'log_time', strtotime($yesterday_begin), strtotime($yesterday_end)])->count();
     return $summary;
 }
示例#10
0
 /**
  * This method is called after each cest class test method, even if test failed.
  * @param \Codeception\Event\TestEvent $event
  */
 public function _after($event)
 {
     User::deleteAll(['email' => '*****@*****.**', 'username' => 'tester']);
 }
示例#11
0
文件: Comment.php 项目: bessonov87/bw
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getUser()
 {
     return $this->hasOne(User::className(), ['id' => 'user_id'])->joinWith('profile');
 }
示例#12
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 string $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.');
     }
 }
示例#13
0
 /**
  * Получает объект класса User по username
  *
  * @return array|null|\yii\db\ActiveRecord
  * @throws NotFoundHttpException
  */
 public function getUser()
 {
     $user = User::find()->where(['username' => \Yii::$app->request->get('username')])->joinWith('profile')->limit(1)->one();
     if (!$user) {
         throw new NotFoundHttpException('Такого пользователя не существует. Проверьте правильно ли вы скопировали или ввели адрес в адресную строку. Если вы перешли на эту страницу по ссылке с данного сайта, сообщите пожалуйста о неработающей ссылке нам с помощью обратной связи.');
     }
     return $user;
 }
示例#14
0
 /**
  * @inheritdoc
  */
 public function run()
 {
     $user = User::findByUsername(Yii::$app->user->identity->username);
     return $this->render('user-widget', ['user' => $user]);
 }
示例#15
0
文件: Post.php 项目: bessonov87/bw
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getAuthor()
 {
     return $this->hasOne(User::className(), ['id' => 'author_id']);
 }
示例#16
0
 /**
  * CallBack метод для oAuth авторизации через внешние сервисы
  *
  * @param $client
  * @throws BadRequestHttpException
  * @throws \yii\base\Exception
  * @throws \yii\db\Exception
  */
 public function onAuthSuccess($client)
 {
     $attributes = $client->getUserAttributes();
     // VK
     if ($client instanceof \yii\authclient\clients\VKontakte) {
         $auth_params = $client->getAccessToken()->getParams();
         $email = ArrayHelper::getValue($auth_params, 'email', '');
         // Аватарка из VK да ПОБОЛЬШЕ!!!
         $vk_data_response = $client->api('users.get', 'POST', ['uids' => $attributes['id'], 'fields' => 'photo_max_orig']);
         if ($vk_data_response = ArrayHelper::getValue($vk_data_response, 'response', false)) {
             $vk_data = array_shift($vk_data_response);
         }
         $userInfo['source_id'] = $attributes['id'];
         $userInfo['username'] = $attributes['screen_name'] ? $attributes['screen_name'] : GlobalHelper::usernameFromEmail($attributes['email']);
         $userInfo['email'] = $attributes['email'];
         $userInfo['name'] = $attributes['first_name'];
         $userInfo['surname'] = $attributes['last_name'];
         $userInfo['birth_date'] = date('Y-m-d', strtotime($attributes['bdate']));
         $userInfo['sex'] = $attributes['sex'] == 2 ? 'm' : 'f';
     }
     // YANDEX
     if ($client instanceof \yii\authclient\clients\YandexOAuth) {
         $userInfo['source_id'] = $attributes['id'];
         $userInfo['username'] = $attributes['login'] ? $attributes['login'] : GlobalHelper::usernameFromEmail($attributes['emails'][0]);
         $userInfo['email'] = $attributes['emails'][0];
         $userInfo['name'] = $attributes['first_name'];
         $userInfo['surname'] = $attributes['last_name'];
         $userInfo['birth_date'] = $attributes['birthday'];
         $userInfo['sex'] = $attributes['sex'] == 'male' ? 'm' : 'f';
     }
     // FACEBOOK
     if ($client instanceof \yii\authclient\clients\Facebook) {
         //var_dump($attributes); die();
         $userInfo['source_id'] = $attributes['id'];
         $userInfo['username'] = GlobalHelper::usernameFromEmail($attributes['email']);
         $userInfo['email'] = $attributes['email'];
         $userInfo['name'] = $attributes['name'];
         $userInfo['surname'] = '';
         $userInfo['birth_date'] = '';
         $userInfo['sex'] = '';
     }
     // GOOGLE
     if ($client instanceof \yii\authclient\clients\GoogleOAuth) {
         //var_dump($attributes); die();
         $userInfo['source_id'] = $attributes['id'];
         $userInfo['username'] = GlobalHelper::usernameFromEmail($attributes['emails'][0]["value"]);
         $userInfo['email'] = $attributes['emails'][0]["value"];
         $userInfo['name'] = $attributes['name']["givenName"];
         $userInfo['surname'] = $attributes['name']["familyName"];
         $userInfo['birth_date'] = '';
         $userInfo['sex'] = $attributes['gender'] == 'male' ? 'm' : 'f';
     }
     // MAIL.RU
     if ($client instanceof \frontend\components\auth\Mailru) {
         //var_dump($attributes[0]); die();
         $userInfo['source_id'] = $attributes['id'];
         $userInfo['username'] = GlobalHelper::usernameFromEmail($attributes[0]['email']);
         $userInfo['email'] = $attributes[0]["email"];
         $userInfo['name'] = $attributes[0]["first_name"];
         $userInfo['surname'] = $attributes[0]["last_name"];
         $userInfo['birth_date'] = date('Y-m-d', strtotime($attributes[0]["birthday"]));
         $userInfo['sex'] = $attributes[0]["sex"] == 0 ? 'm' : 'f';
     }
     /*// ODNOKLASSNIKI
       if($client instanceof \frontend\components\auth\Odnoklassniki) {
           var_dump($attributes); die();
           $userInfo['source_id'] = $attributes['uid'];
           $userInfo['username'] = GlobalHelper::usernameFromEmail($attributes[0]['email']);
           if($attributes['has_email']) $userInfo['email'] = $attributes[0]["email"];
           $userInfo['name'] = $attributes["first_name"];
           $userInfo['surname'] = $attributes["last_name"];
           $userInfo['birth_date'] = $attributes["birthday"];
           $userInfo['sex'] = ($attributes["gender"] == 'male') ? 'm' : 'f';
       }*/
     if (!isset($userInfo['email']) || empty($userInfo['email'])) {
         throw new BadRequestHttpException('Не удалось получить email адрес');
     }
     /* @var $auth Auth */
     $auth = Auth::find()->where(['source' => $client->getId(), 'source_id' => $attributes['id']])->one();
     if (Yii::$app->user->isGuest) {
         if ($auth) {
             // авторизация
             $user = $auth->user;
             Yii::$app->user->login($user);
             Yii::$app->session->setFlash('success', 'Вход произведен. Теперь вы можете использовать все дополнительные возможности сайта.');
         } else {
             // регистрация
             if (isset($userInfo['email']) && User::find()->where(['email' => $userInfo['email']])->exists()) {
                 Yii::$app->getSession()->setFlash('error', [Yii::t('app', "Пользователь с электронной почтой как в <strong>{client} (" . $userInfo['email'] . ")</strong> уже существует, но не связан с этим аккаунтом. Вероятно, вы уже регистрировались на нашем сайте с помощью другой социальной сети, к которой привязан email <strong>" . $userInfo['email'] . "</strong>, или с использованием классического способа регистрации.\n                        Для входа на сайт используйте тот сервис, который вы использовали в первый раз. Если это невозможно, перейдите <a href='/site/request-password-reset'>на эту страницу</a> и пройдите процедуру восстановления доступа, указав email <strong>" . $userInfo['email'] . "</strong>. На этот адрес будет отправлено письмо с дальнейшими действиями. После восстановления доступа вы сможете привязать\n                        к своему аккаунту любую из социальных сетей и далее входить на сайт в один клик.", ['client' => $client->getTitle()])]);
             } else {
                 $password = Yii::$app->security->generateRandomString(6);
                 $user = new User(['username' => $userInfo['username'], 'email' => $userInfo['email'], 'password' => $password]);
                 $user->generateAuthKey();
                 $user->generatePasswordResetToken();
                 $transaction = $user->getDb()->beginTransaction();
                 if ($user->save()) {
                     $profile = new UserProfile();
                     $profile->user_id = $user->id;
                     $profile->name = $userInfo['name'];
                     $profile->surname = $userInfo['surname'];
                     $profile->birth_date = $userInfo['birth_date'];
                     if (isset($userInfo['sex'])) {
                         $profile->sex = $userInfo['sex'];
                     }
                     $profile->save();
                     $auth = new Auth(['user_id' => $user->id, 'source' => $client->getId(), 'source_id' => (string) $userInfo['source_id']]);
                     if ($auth->save()) {
                         $transaction->commit();
                         Yii::$app->session->setFlash('success', 'Вход на сайт произведен. Для вас была автоматически создана учетная запись. Информация о ней отправлена на ваш email (<strong>(' . $userInfo['email'] . ')</strong>). В дальнейшем вы можете входить на сайт как с помощью {client}, так и с помощью своего логина и пароля.');
                         Yii::$app->user->login($user);
                     } else {
                         print_r($auth->getErrors());
                     }
                 } else {
                     print_r($user->getErrors());
                 }
             }
         }
     } else {
         // Пользователь уже зарегистрирован
         if ($auth->user_id != Yii::$app->user->getId()) {
             // Если аккаунт привязан к другому пользователю
             Yii::$app->session->setFlash('error', 'Данный аккаунт ' . $client->getTitle() . ' привязан к учетной записи другого пользователя сайта. Привязать аккаунт к двум учетным записям невозможно.');
         } else {
             Yii::$app->session->setFlash('info', 'Данный аккаунт ' . $client->getTitle() . ' уже привязан к вашей учетной записи.');
         }
         if (!$auth) {
             // добавляем внешний сервис аутентификации
             $auth = new Auth(['user_id' => Yii::$app->user->id, 'source' => $client->getId(), 'source_id' => $attributes['id']]);
             $auth->save();
         }
     }
 }