Example #1
0
 /**
  * @return User
  */
 public function getUser()
 {
     if ($this->_user === null) {
         $this->_user = $this->finder->findUserByEmail($this->email);
     }
     return $this->_user;
 }
 /**
  * Shows user's profile.
  * @param  integer $id
  * @return \yii\web\Response
  * @throws \yii\web\NotFoundHttpException
  */
 public function actionShow($id)
 {
     $profile = $this->finder->findProfileById($id);
     if ($profile === null) {
         throw new NotFoundHttpException();
     }
     return $this->render('show', ['profile' => $profile]);
 }
Example #3
0
 /** @inheritdoc */
 public function rules()
 {
     return [['email', 'filter', 'filter' => 'trim'], ['email', 'required'], ['email', 'email'], ['email', 'exist', 'targetClass' => $this->module->modelMap['User'], 'message' => \Yii::t('users', 'There is no user with such email.')], ['email', function ($attribute) {
         $this->user = $this->finder->findUserByEmail($this->email);
         if ($this->user !== null && $this->module->enableConfirmation && !$this->user->getIsConfirmed()) {
             $this->addError($attribute, \Yii::t('users', 'You need to confirm your email address'));
         }
     }], ['password', 'required'], ['password', 'string', 'min' => 6]];
 }
Example #4
0
 /**
  * @param $params
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = $this->finder->getUserQuery();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     $query->andFilterWhere(['<>', 'username', 'root']);
     if (!($this->load($params) && $this->validate())) {
         return $dataProvider;
     }
     $query->andFilterWhere(['created_at' => $this->created_at])->andFilterWhere(['like', 'username', $this->username])->andFilterWhere(['like', 'email', $this->email])->andFilterWhere(['registration_ip' => $this->registration_ip]);
     return $dataProvider;
 }
 /**
  * Confirms a user by setting confirmed_at field to current time.
  *
  * @param string $search Email or username
  */
 public function actionIndex($search)
 {
     $user = $this->finder->findUserByUsernameOrEmail($search);
     if ($user === null) {
         $this->stdout(\Yii::t('users', 'User is not found') . "\n", Console::FG_RED);
     } else {
         if ($user->confirm()) {
             $this->stdout(\Yii::t('users', 'User has been confirmed') . "\n", Console::FG_GREEN);
         } else {
             $this->stdout(\Yii::t('users', 'Error occurred while confirming user') . "\n", Console::FG_RED);
         }
     }
 }
 /**
  * Updates user's password to given.
  *
  * @param string $search   Email or username
  * @param string $password New password
  */
 public function actionIndex($search, $password)
 {
     $user = $this->finder->findUserByUsernameOrEmail($search);
     if ($user === null) {
         $this->stdout(\Yii::t('users', 'User is not found') . "\n", Console::FG_RED);
     } else {
         if ($user->resetPassword($password)) {
             $this->stdout(\Yii::t('users', 'Password has been changed') . "\n", Console::FG_GREEN);
         } else {
             $this->stdout(\Yii::t('users', 'Error occurred while changing password') . "\n", Console::FG_RED);
         }
     }
 }
 /**
  * Deletes a user.
  *
  * @param string $search Email or username
  */
 public function actionIndex($search)
 {
     if ($this->confirm(\Yii::t('users', 'Are you sure? Deleted user can not be restored'))) {
         $user = $this->finder->findUserByUsernameOrEmail($search);
         if ($user === null) {
             $this->stdout(\Yii::t('users', 'User is not found') . "\n", Console::FG_RED);
         } else {
             if ($user->delete()) {
                 $this->stdout(\Yii::t('users', 'User has been deleted') . "\n", Console::FG_GREEN);
             } else {
                 $this->stdout(\Yii::t('users', 'Error occurred while deleting user') . "\n", Console::FG_RED);
             }
         }
     }
 }
Example #8
0
 /**
  * This method attempts changing user email. If user's "unconfirmed_email" field is empty is returns false, else if
  * somebody already has email that equals user's "unconfirmed_email" it returns false, otherwise returns true and
  * updates user's password.
  *
  * @param  string $code
  * @return bool
  * @throws \Exception
  */
 public function attemptEmailChange($code)
 {
     /** @var Token $token */
     $token = $this->finder->findToken(['user_id' => $this->id, 'code' => $code])->andWhere(['in', 'type', [Token::TYPE_CONFIRM_NEW_EMAIL, Token::TYPE_CONFIRM_OLD_EMAIL]])->one();
     if (empty($this->unconfirmed_email) || $token === null || $token->isExpired) {
         \Yii::$app->session->setFlash('danger', \Yii::t('users', 'Your confirmation token is invalid'));
     }
     $token->delete();
     if (empty($this->unconfirmed_email)) {
         \Yii::$app->session->setFlash('danger', \Yii::t('users', 'An error occurred during your request'));
     } else {
         if (static::find()->where(['email' => $this->unconfirmed_email])->exists() == false) {
             if ($this->module->emailChangeStrategy == Module::STRATEGY_SECURE) {
                 switch ($token->type) {
                     case Token::TYPE_CONFIRM_NEW_EMAIL:
                         $this->flags |= self::NEW_EMAIL_CONFIRMED;
                         \Yii::$app->session->setFlash('success', \Yii::t('users', 'Awesome, almost there. Now you need to click confirmation link sent to your old email address'));
                         break;
                     case Token::TYPE_CONFIRM_OLD_EMAIL:
                         $this->flags |= self::OLD_EMAIL_CONFIRMED;
                         \Yii::$app->session->setFlash('success', \Yii::t('users', 'Awesome, almost there. Now you need to click confirmation link sent to your new email address'));
                         break;
                 }
             }
             if ($this->module->emailChangeStrategy == Module::STRATEGY_DEFAULT || $this->flags & self::NEW_EMAIL_CONFIRMED && $this->flags & self::OLD_EMAIL_CONFIRMED) {
                 $this->email = $this->unconfirmed_email;
                 $this->unconfirmed_email = null;
                 \Yii::$app->session->setFlash('success', \Yii::t('users', 'Your email has been successfully changed'));
             }
             $this->save(false);
         }
     }
 }
 /**
  * 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)
 {
     $user = $this->finder->findUserById($id);
     if ($user === null) {
         throw new NotFoundHttpException('The requested page does not exist');
     }
     return $user;
 }
 /**
  * Displays page where user can reset password.
  * @param  integer $id
  * @param  string  $code
  * @return string
  * @throws \yii\web\NotFoundHttpException
  */
 public function actionReset($id, $code)
 {
     if (!$this->module->enablePasswordRecovery) {
         throw new NotFoundHttpException();
     }
     /** @var Token $token */
     $token = $this->finder->findToken(['user_id' => $id, 'code' => $code, 'type' => Token::TYPE_RECOVERY])->one();
     if ($token === null || $token->isExpired || $token->user === null) {
         \Yii::$app->session->setFlash('danger', \Yii::t('users', 'Recovery link is invalid or out-of-date. Please try requesting a new one.'));
         return $this->render('/message', ['title' => \Yii::t('users', 'Invalid or out-of-date link'), 'module' => $this->module]);
     }
     $model = \Yii::createObject(['class' => RecoveryForm::className(), 'scenario' => 'reset']);
     $this->performAjaxValidation($model);
     if ($model->load(\Yii::$app->getRequest()->post()) && $model->resetPassword($token)) {
         return $this->render('/message', ['title' => \Yii::t('users', 'Password has been changed'), 'module' => $this->module]);
     }
     return $this->render('reset', ['model' => $model]);
 }
 /**
  * Confirms user's account. If confirmation was successful logs the user and shows success message. Otherwise
  * shows error message.
  * @param  integer $id
  * @param  string  $code
  * @return string
  * @throws \yii\web\HttpException
  */
 public function actionConfirm($id, $code)
 {
     $user = $this->finder->findUserById($id);
     if ($user === null || $this->module->enableConfirmation == false) {
         throw new NotFoundHttpException();
     }
     $user->attemptConfirmation($code);
     return $this->render('/message', ['title' => \Yii::t('users', 'Account confirmation'), 'module' => $this->module]);
 }
Example #12
0
 /** @inheritdoc */
 public function beforeValidate()
 {
     if (parent::beforeValidate()) {
         $this->user = $this->finder->findUserByUsernameOrEmail($this->login);
         return true;
     } else {
         return false;
     }
 }
 /**
  * Connects social account to user.
  * @param  ClientInterface $client
  * @return \yii\web\Response
  */
 public function connect(ClientInterface $client)
 {
     $attributes = $client->getUserAttributes();
     $provider = $client->getId();
     $clientId = $attributes['id'];
     $account = $this->finder->findAccountByProviderAndClientId($provider, $clientId);
     if ($account === null) {
         $account = \Yii::createObject(['class' => Account::className(), 'provider' => $provider, 'client_id' => $clientId, 'data' => json_encode($attributes), 'user_id' => \Yii::$app->user->id]);
         $account->save(false);
         \Yii::$app->session->setFlash('success', \Yii::t('users', 'Account has been successfully connected'));
     } else {
         \Yii::$app->session->setFlash('error', \Yii::t('users', 'This account has already been connected to another user'));
     }
     $this->action->successUrl = Url::to(['/users/settings/networks']);
 }
 /**
  * Logs the user in if this social account has been already used. Otherwise shows registration form.
  * @param  ClientInterface $client
  * @return \yii\web\Response
  */
 public function authenticate(ClientInterface $client)
 {
     $attributes = $client->getUserAttributes();
     $provider = $client->getId();
     $clientId = $attributes['id'];
     $account = $this->finder->findAccountByProviderAndClientId($provider, $clientId);
     if ($account === null) {
         $account = \Yii::createObject(['class' => Account::className(), 'provider' => $provider, 'client_id' => $clientId, 'data' => json_encode($attributes)]);
         $account->save(false);
     }
     if (null === ($user = $account->user)) {
         $this->action->successUrl = Url::to(['/users/registration/connect', 'account_id' => $account->id]);
     } else {
         \Yii::$app->user->login($user, $this->module->rememberFor);
     }
 }
Example #15
0
 /** @inheritdoc */
 public function bootstrap($app)
 {
     /** @var $module Module */
     if ($app->hasModule('users') && ($module = $app->getModule('users')) instanceof Module) {
         $this->_modelMap = array_merge($this->_modelMap, $module->modelMap);
         foreach ($this->_modelMap as $name => $definition) {
             $class = "mii\\modules\\users\\models\\" . $name;
             \Yii::$container->set($class, $definition);
             $modelName = is_array($definition) ? $definition['class'] : $definition;
             $module->modelMap[$name] = $modelName;
             if (in_array($name, ['User', 'Profile', 'Token', 'Account'])) {
                 \Yii::$container->set($name . 'Query', function () use($modelName) {
                     return $modelName::find();
                 });
             }
         }
         \Yii::$container->setSingleton(Finder::className(), ['userQuery' => \Yii::$container->get('UserQuery'), 'profileQuery' => \Yii::$container->get('ProfileQuery'), 'tokenQuery' => \Yii::$container->get('TokenQuery'), 'accountQuery' => \Yii::$container->get('AccountQuery')]);
         if ($app instanceof ConsoleApplication) {
             $module->controllerNamespace = 'mii\\modules\\users\\commands';
             $app->get('i18n')->translations['users*'] = ['class' => PhpMessageSource::className(), 'basePath' => __DIR__ . '/messages'];
         } else {
             try {
                 $app->user->enableAutoLogin = true;
                 $app->user->loginUrl = ['/users/security/login'];
                 $app->user->identityClass = $module->modelMap['User'];
             } catch (InvalidConfigException $e) {
                 $app->set('user', ['class' => User::className(), 'enableAutoLogin' => true, 'loginUrl' => ['/users/security/login'], 'identityClass' => $module->modelMap['User']]);
             }
             $configUrlRule = ['prefix' => $module->urlPrefix, 'rules' => $module->urlRules];
             if ($module->urlPrefix != 'users') {
                 $configUrlRule['routePrefix'] = 'users';
             }
             $app->get('urlManager')->rules[] = new GroupUrlRule($configUrlRule);
             $app->get('urlManager')->addRules(['PUT,PATCH /' . $this->id . '/apis/<id>' => $this->id . '/api/update', 'DELETE /' . $this->id . '/apis/<id>' => $this->id . '/api/delete', 'GET,HEAD /' . $this->id . '/apis/<id>' => $this->id . '/api/view', 'POST /' . $this->id . '/apis' => $this->id . '/api/create', 'GET,HEAD /' . $this->id . '/apis' => $this->id . '/api/index', 'OPTIONS /' . $this->id . '/apis/<id>' => $this->id . '/api/options', 'OPTIONS /' . $this->id . '/apis' => $this->id . '/api/options'], false);
             if (!$app->has('authClientCollection')) {
                 $app->set('authClientCollection', ['class' => Collection::className()]);
             }
         }
         $app->get('i18n')->translations['users*'] = ['class' => PhpMessageSource::className(), 'basePath' => __DIR__ . '/messages'];
         $defaults = ['welcomeSubject' => \Yii::t('users', 'Welcome to {0}', \Yii::$app->name), 'confirmationSubject' => \Yii::t('users', 'Confirm account on {0}', \Yii::$app->name), 'reconfirmationSubject' => \Yii::t('users', 'Confirm email change on {0}', \Yii::$app->name), 'recoverySubject' => \Yii::t('users', 'Complete password reset on {0}', \Yii::$app->name)];
         \Yii::$container->set('mii\\modules\\users\\Mailer', array_merge($defaults, $module->mailer));
     }
 }