Exemple #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 int $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]);
 }
 /**
  * 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();
     }
     $fi = FirmaIngeniero::find()->where(['ingeniero_id' => $profile->user_id])->one();
     return $this->render('show', ['profile' => $profile, 'fi' => $fi]);
 }
 /** @inheritdoc */
 public function rules()
 {
     return ['emailTrim' => ['email', 'filter', 'filter' => 'trim'], 'emailRequired' => ['email', 'required'], 'emailPattern' => ['email', 'email'], 'emailExist' => ['email', 'exist', 'targetClass' => $this->module->modelMap['User'], 'message' => \Yii::t('user', 'There is no user with this email address')], 'emailUnconfirmed' => ['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('user', 'You need to confirm your email address'));
         }
     }], 'passwordRequired' => ['password', 'required'], 'passwordLength' => ['password', 'string', 'min' => 6]];
 }
 public function actionIndex()
 {
     $id = Yii::$app->user->identity->id;
     $profile = $this->finder->findProfileById($id);
     if ($profile === null) {
         throw new NotFoundHttpException();
     }
     $this->view->params['profile'] = $profile;
     return $this->render('index');
 }
 /**
  * @param $params
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = $this->finder->getUserQuery();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     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;
 }
 /**
  * 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('user', 'User is not found') . "\n", Console::FG_RED);
     } else {
         if ($user->resetPassword($password)) {
             $this->stdout(Yii::t('user', 'Password has been changed') . "\n", Console::FG_GREEN);
         } else {
             $this->stdout(Yii::t('user', 'Error occurred while changing password') . "\n", Console::FG_RED);
         }
     }
 }
 /**
  * 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('user', 'User is not found') . "\n", Console::FG_RED);
     } else {
         if ($user->confirm()) {
             $this->stdout(Yii::t('user', 'User has been confirmed') . "\n", Console::FG_GREEN);
         } else {
             $this->stdout(Yii::t('user', 'Error occurred while confirming user') . "\n", Console::FG_RED);
         }
     }
 }
 /**
  * Shows user's profile.
  *
  * @param int $id
  *
  * @return \yii\web\Response
  * @throws \yii\web\NotFoundHttpException
  */
 public function actionShow($id)
 {
     $profile = $this->finder->findProfileById($id);
     $post = Post::getPostByUser($id);
     $tags = array();
     for ($i = 0; $i < count($post->getModels()); $i++) {
         array_push($tags, Post_tags::getTags($post->getModels()[$i]['post_id']));
     }
     if ($profile === null) {
         throw new NotFoundHttpException();
     }
     return $this->render('show', ['profile' => $profile, 'posts' => $post, 'tags' => $tags]);
 }
Exemple #10
0
 /**
  * @param $params
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = $this->finder->getUserQuery();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     if (!($this->load($params) && $this->validate())) {
         return $dataProvider;
     }
     if ($this->created_at !== null) {
         $date = strtotime($this->created_at);
         $query->andFilterWhere(['between', 'created_at', $date, $date + 3600 * 24]);
     }
     $query->andFilterWhere(['like', 'username', $this->username])->andFilterWhere(['like', 'email', $this->email])->andFilterWhere(['like', 'profileUser', $this->profileUser->name])->andFilterWhere(['registration_ip' => $this->registration_ip]);
     return $dataProvider;
 }
Exemple #11
0
 /**
  * Creates new confirmation token and sends it to the user.
  *
  * @return bool
  */
 public function resend()
 {
     if (!$this->validate()) {
         return false;
     }
     $user = $this->finder->findUserByEmail($this->email);
     if ($user instanceof User && !$user->isConfirmed) {
         /** @var Token $token */
         $token = \Yii::createObject(['class' => Token::className(), 'user_id' => $user->id, 'type' => Token::TYPE_CONFIRMATION]);
         $token->save(false);
         $this->mailer->sendConfirmationMessage($user, $token);
     }
     \Yii::$app->session->setFlash('info', \Yii::t('user', 'A message has been sent to your email address. It contains a confirmation link that you must click to complete registration.'));
     return true;
 }
 /**
  * Deletes a user.
  *
  * @param string $search Email or username
  */
 public function actionIndex($search)
 {
     if ($this->confirm(\Yii::t('user', 'Are you sure? Deleted user can not be restored'))) {
         $user = $this->finder->findUserByUsernameOrEmail($search);
         if ($user === null) {
             $this->stdout(\Yii::t('user', 'User is not found') . "\n", Console::FG_RED);
         } else {
             if ($user->delete()) {
                 $this->stdout(\Yii::t('user', 'User has been deleted') . "\n", Console::FG_GREEN);
             } else {
                 $this->stdout(\Yii::t('user', 'Error occurred while deleting user') . "\n", Console::FG_RED);
             }
         }
     }
 }
Exemple #13
0
 /** @inheritdoc */
 public function bootstrap($app)
 {
     /** @var $module Module */
     if ($app->hasModule('user') && ($module = $app->getModule('user')) instanceof Module) {
         $this->_modelMap = array_merge($this->_modelMap, $module->modelMap);
         foreach ($this->_modelMap as $name => $definition) {
             $class = "dektrium\\user\\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 = 'dektrium\\user\\commands';
         } else {
             \Yii::$container->set('yii\\web\\User', ['enableAutoLogin' => true, 'loginUrl' => ['/user/security/login'], 'identityClass' => $module->modelMap['User']]);
             $configUrlRule = ['prefix' => $module->urlPrefix, 'rules' => $module->urlRules];
             if ($module->urlPrefix != 'user') {
                 $configUrlRule['routePrefix'] = 'user';
             }
             $app->get('urlManager')->rules[] = new GroupUrlRule($configUrlRule);
             if (!$app->has('authClientCollection')) {
                 $app->set('authClientCollection', ['class' => Collection::className()]);
             }
         }
         $app->get('i18n')->translations['user*'] = ['class' => PhpMessageSource::className(), 'basePath' => __DIR__ . '/messages'];
         $defaults = ['welcomeSubject' => \Yii::t('user', 'Welcome to {0}', \Yii::$app->name), 'confirmationSubject' => \Yii::t('user', 'Confirm account on {0}', \Yii::$app->name), 'reconfirmationSubject' => \Yii::t('user', 'Confirm email change on {0}', \Yii::$app->name), 'recoverySubject' => \Yii::t('user', 'Complete password reset on {0}', \Yii::$app->name)];
         \Yii::$container->set('dektrium\\user\\Mailer', array_merge($defaults, $module->mailer));
     }
 }
 /** @inheritdoc */
 public function beforeValidate()
 {
     if (parent::beforeValidate()) {
         if (!empty($this->Login)) {
             $this->user = $this->finder->findUser(['Login' => $this->Login])->one();
             /**
              * Generate password
              */
             $hash = Yii::$app->security->generatePasswordHash($this->Password);
             ////$this->Password = $this->Password . ':' . $hash;
             ////list($password, $hash) = explode(':', $this->Password);
             //                if ($this->user !== null && Yii::$app->getSecurity()->validatePassword($this->Password, $hash) ) {
             //                    $this->user->updateAttributes(['Password' => $hash]);
             //                    echo $this->Password . ':' . $hash. ' OK  ';
             //                }
             //                exit;
         }
         if ($this->user === null) {
             if (CardRecord::check($this->Login)) {
                 $card = CardRecord::findCard($this->Login);
                 if ($card !== null && $card->person) {
                     //                    $this->user = $card->person->ServiceCard ? $card->person : null;
                     $this->user = $card->person;
                     return true;
                 }
             }
             $this->addError('Login', \Yii::t('user', 'Invalid login or password'));
             return false;
         } else {
             return true;
         }
     } else {
         return false;
     }
 }
Exemple #15
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('user', 'Your confirmation token is invalid or expired'));
     } else {
         $token->delete();
         if (empty($this->unconfirmed_email)) {
             \Yii::$app->session->setFlash('danger', \Yii::t('user', 'An error occurred processing 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('user', 'Awesome, almost there. Now you need to click the 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('user', 'Awesome, almost there. Now you need to click the 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('user', 'Your email address has been changed'));
                 }
                 $this->save(false);
             }
         }
     }
 }
 /**
  * Tries to authenticate user via social network. If user has already used
  * this network's account, he will be logged in. Otherwise, it will try
  * to create new user account.
  *
  * @param ClientInterface $client
  */
 public function authenticate(ClientInterface $client)
 {
     $account = $this->finder->findAccount()->byClient($client)->one();
     if (!$this->module->enableRegistration && ($account === null || $account->user === null)) {
         Yii::$app->session->setFlash('danger', Yii::t('user', 'Registration on this website is disabled'));
         $this->action->successUrl = Url::to(['/user/security/login']);
         return;
     }
     if ($account === null) {
         /** @var Account $account */
         $accountObj = Yii::createObject(Account::className());
         $account = $accountObj::create($client);
     }
     $event = $this->getAuthEvent($account, $client);
     $this->trigger(self::EVENT_BEFORE_AUTHENTICATE, $event);
     if ($account->user instanceof User) {
         if ($account->user->isBlocked) {
             Yii::$app->session->setFlash('danger', Yii::t('user', 'Your account has been blocked.'));
             $this->action->successUrl = Url::to(['/user/security/login']);
         } else {
             Yii::$app->user->login($account->user, $this->module->rememberFor);
             $this->action->successUrl = Yii::$app->getUser()->getReturnUrl();
         }
     } else {
         $this->action->successUrl = $account->getConnectUrl();
     }
     $this->trigger(self::EVENT_AFTER_AUTHENTICATE, $event);
 }
 /**
  * Displays page where user can reset password.
  *
  * @param int    $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();
     $event = $this->getResetPasswordEvent($token);
     $this->trigger(self::EVENT_BEFORE_TOKEN_VALIDATE, $event);
     if ($token === null || $token->isExpired || $token->user === null) {
         $this->trigger(self::EVENT_AFTER_TOKEN_VALIDATE, $event);
         Yii::$app->session->setFlash('danger', Yii::t('user', 'Recovery link is invalid or expired. Please try requesting a new one.'));
         return $this->render('/message', ['title' => Yii::t('user', 'Invalid or expired link'), 'module' => $this->module]);
     }
     /** @var RecoveryForm $model */
     $model = Yii::createObject(['class' => RecoveryForm::className(), 'scenario' => 'reset']);
     $event->setForm($model);
     $this->performAjaxValidation($model);
     $this->trigger(self::EVENT_BEFORE_RESET, $event);
     if ($model->load(Yii::$app->getRequest()->post()) && $model->resetPassword($token)) {
         $this->trigger(self::EVENT_AFTER_RESET, $event);
         return $this->render('/message', ['title' => Yii::t('user', 'Password has been changed'), 'module' => $this->module]);
     }
     return $this->render('reset', ['model' => $model]);
 }
 public function actionConfirmar($userName)
 {
     $user = $this->finder->findUserByUsername($userName);
     $user['confirmed_at'] = $user['created_at'];
     $user->scenario = 'update';
     $user->save();
     echo JSON::encode('usuario ' . $user['username'] . ' confirmado!');
 }
 /**
  * Finds the User model based on its primary key value.
  * If the model is not found, a 404 HTTP exception will be thrown.
  *
  * @param int $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;
 }
Exemple #20
0
 /** @inheritdoc */
 public function beforeValidate()
 {
     if (parent::beforeValidate()) {
         $this->user = $this->finder->findUserByUsernameOrEmail(trim($this->login));
         return true;
     } else {
         return false;
     }
 }
 /**
  * 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('user', 'Recovery link is invalid or out-of-date. Please try requesting a new one.'));
         return $this->render('/message', ['title' => \Yii::t('user', '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('user', '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 int    $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('user', 'Account confirmation'), 'module' => $this->module]);
 }
Exemple #23
0
 /**
  * Sends recovery message.
  *
  * @return bool
  */
 public function sendRecoveryMessage()
 {
     if (!$this->validate()) {
         return false;
     }
     $user = $this->finder->findUserByEmail($this->email);
     if ($user instanceof User) {
         /** @var Token $token */
         $token = \Yii::createObject(['class' => Token::className(), 'user_id' => $user->id, 'type' => Token::TYPE_RECOVERY]);
         if (!$token->save(false)) {
             return false;
         }
         if (!$this->mailer->sendRecoveryMessage($user, $token)) {
             return false;
         }
     }
     \Yii::$app->session->setFlash('info', \Yii::t('user', 'An email has been sent with instructions for resetting your password'));
     return true;
 }
 /**
  * Displays page where user can reset password.
  *
  * @param int    $id
  * @param string $code
  *
  * @return string
  * @throws \yii\web\NotFoundHttpException
  */
 public function actionReset($id, $code)
 {
     $this->layout = '@app/views/layouts/login';
     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('user', 'Recovery link is invalid or expired. Please try requesting a new one.'));
         return $this->goHome();
     }
     /** @var RecoveryForm $model */
     $model = Yii::createObject(['class' => RecoveryForm::className(), 'scenario' => 'reset']);
     $this->performAjaxValidation($model);
     if ($model->load(Yii::$app->getRequest()->post()) && $model->resetPassword($token)) {
         return $this->redirect('/user/login', 302);
     }
     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 int    $id
  * @param string $code
  *
  * @return string
  * @throws \yii\web\HttpException
  */
 public function actionConfirm($id, $code)
 {
     $user = $this->finder->findUserById($id);
     $event = $this->getUserEvent($user);
     if ($user === null || $this->module->enableConfirmation == false) {
         throw new NotFoundHttpException();
     }
     $this->trigger(self::EVENT_BEFORE_CONFIRM, $event);
     $user->attemptConfirmation($code);
     $this->trigger(self::EVENT_AFTER_CONFIRM, $event);
     return $this->render('/message', ['title' => Yii::t('user', 'Account confirmation'), 'module' => $this->module]);
 }
 /**
  * Disconnects a network account from user.
  *
  * @param int $id
  *
  * @return \yii\web\Response
  * @throws \yii\web\NotFoundHttpException
  * @throws \yii\web\ForbiddenHttpException
  */
 public function actionDisconnect($id)
 {
     $account = $this->finder->findAccount()->byId($id)->one();
     if ($account === null) {
         throw new NotFoundHttpException();
     }
     if ($account->user_id != Yii::$app->user->id) {
         throw new ForbiddenHttpException();
     }
     $account->delete();
     return $this->redirect(['networks']);
 }
 /**
  * Tries to authenticate user via social network. If user has already used
  * this network's account, he will be logged in. Otherwise, it will try
  * to create new user account.
  *
  * @param ClientInterface $client
  */
 public function authenticate(ClientInterface $client)
 {
     $account = $this->finder->findAccount()->byClient($client)->one();
     if ($account === null) {
         $account = Account::create($client);
     }
     if ($account->user instanceof User) {
         Yii::$app->user->login($account->user, $this->module->rememberFor);
         $this->action->successUrl = Yii::$app->getUser()->getReturnUrl();
     } else {
         $this->action->successUrl = $account->getConnectUrl();
     }
 }
 /**
  * Tests login method.
  */
 public function testLogin()
 {
     $user = \Yii::createObject(User::className());
     test::double(Finder::className(), ['findUserByUsernameOrEmail' => $user]);
     $form = Yii::createObject(LoginForm::className());
     $form->beforeValidate();
     test::double($form, ['validate' => false]);
     verify($form->login())->false();
     test::double($form, ['validate' => true]);
     test::double(\yii\web\User::className(), ['login' => false]);
     verify($form->login())->false();
     test::double(\yii\web\User::className(), ['login' => true]);
     verify($form->login())->true();
 }
 /**
  * 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('user', 'Account has been successfully connected'));
     } else {
         \Yii::$app->session->setFlash('error', \Yii::t('user', 'This account has already been connected to another user'));
     }
     $this->action->successUrl = Url::to(['/user/settings/networks']);
 }
Exemple #30
0
 /**
  * Disconnects a network account from user.
  *
  * @param int $id
  *
  * @return \yii\web\Response
  * @throws \yii\web\NotFoundHttpException
  * @throws \yii\web\ForbiddenHttpException
  */
 public function actionDisconnect($id)
 {
     $account = $this->finder->findAccount()->byId($id)->one();
     if ($account === null) {
         throw new NotFoundHttpException();
     }
     if ($account->user_id != Yii::$app->user->id) {
         throw new ForbiddenHttpException();
     }
     $event = $this->getConnectEvent($account, $account->user);
     $this->trigger(self::EVENT_BEFORE_DISCONNECT, $event);
     $account->delete();
     $this->trigger(self::EVENT_AFTER_DISCONNECT, $event);
     return $this->redirect(['networks']);
 }