/**
  * @param $userEmail
  *
  * @return null|static|User
  */
 protected function findUser($userEmail)
 {
     if (!($user = User::findByEmail($userEmail))) {
         throw new InvalidParamException("Not found user by email {$userEmail}");
     }
     return $user;
 }
Example #2
0
 public function actionIndex()
 {
     if (Yii::$app->user->isGuest) {
         $model = new IndexForm();
         if ($model->load(Yii::$app->request->post()) && $model->validate()) {
             if ($link = $model->generateLink()) {
                 if (User::findByEmail($link->email)) {
                     $url = Yii::$app->urlManager->createAbsoluteUrl(['/site/login', 'token' => $link->token]);
                 } else {
                     $url = Yii::$app->urlManager->createAbsoluteUrl(['/site/reg', 'token' => $link->token]);
                 }
                 if ($model->sendMail($url, $link->email)) {
                     Yii::$app->session->setFlash('warning', 'Check your email');
                     return $this->redirect('/site/index');
                 }
             } else {
                 Yii::$app->session->setFlash('error', 'Error generate link.');
                 Yii::error('Error generate link');
                 return $this->refresh();
             }
         }
         return $this->render('index', ['model' => $model]);
     }
     return $this->redirect('/account/index');
 }
Example #3
0
 /**
  * Finds user by [[email]]
  *
  * @return User|null
  */
 public function getUser()
 {
     if ($this->_user === false) {
         $this->_user = User::findByEmail($this->email);
     }
     return $this->_user;
 }
Example #4
0
 public function getUser()
 {
     if ($this->_user === false) {
         //            $this->_user = User::findByUsername($this->username);
         $this->_user = User::findByEmail($this->email);
     }
     return $this->_user;
 }
 public function findUser()
 {
     $this->_user = User::findByEmail($this->email);
     if (!$this->_user) {
         return false;
     }
     return true;
 }
Example #6
0
 /**
  * Finds user by [[username]]
  *
  * @return User|null
  */
 public function getUser()
 {
     if ($this->_user === false) {
         $this->_user = User::findByUsername($this->username);
         if (is_null($this->_user)) {
             $this->_user = User::findByEmail($this->username);
         }
     }
     return $this->_user;
 }
 public function testSuccess()
 {
     $user = User::findByEmail('*****@*****.**');
     expect_not($user->isConfirmed());
     $form = new ConfirmEmailForm();
     expect_that($form->validateToken($user->email_confirm_token));
     expect_that($form->confirmEmail());
     $user = User::findByEmail($user->email);
     expect($user->email_confirm_token)->isEmpty();
     expect_that($user->isConfirmed());
 }
 public function testSuccess()
 {
     $user = $this->tester->grabFixture('user', 'user-1');
     $form = new ResetPasswordForm();
     $form->password = '******';
     expect_that($form->validateToken($user->password_reset_token));
     expect_that($form->resetPassword());
     $user = User::findByEmail($user->email);
     expect($user->password_reset_token)->isEmpty();
     expect_that($user->validatePassword('password-new'));
 }
Example #9
0
 public function getUser()
 {
     if ($this->_user === false) {
         if ($this->scenario === 'loginWithEmail') {
             $this->_user = User::findByEmail($this->email);
         } else {
             $this->_user = User::findByUsername($this->username);
         }
     }
     return $this->_user;
 }
 /**
  * Send password reset instructions.
  * @return boolean
  */
 public function sendEmail()
 {
     $user = User::findByEmail($this->email);
     if ($user && $user->status === User::STATUS_ENABLED) {
         $user->generatePasswordResetToken();
         if ($user->save()) {
             return $this->mail('passwordRequest', $this->email, ['subject' => Yii::t('app', 'Reset password information for {name} at {site}', ['name' => $user->name, 'site' => Yii::$app->name]), 'user' => $user]);
         }
     }
     return false;
 }
 public function login()
 {
     if ($this->validate()) {
         if (!($user = User::findByUsername($this->username))) {
             $user = User::findByEmail($this->username);
         }
         if ($login = \Gbox::$components->user->login($user, $this->rememberMe ? 3600 * 24 * 30 : 0)) {
         }
         return $login;
     }
     return false;
 }
 public function actionIndex()
 {
     $params = Yii::$app->request->getBodyParams();
     $user = User::findByEmail(Yii::$app->request->getBodyParam('email'));
     if (!$user) {
         return ['success' => 0, 'message' => 'No such user found'];
     }
     $valid = $user->validatePassword(Yii::$app->request->getBodyParam('password'));
     if (!$valid) {
         return ['success' => 0, 'message' => 'Incorrect password'];
     }
     return ['success' => 1, 'payload' => $user];
 }
Example #13
0
 public function authenticate($data)
 {
     $user = User::findByEmail($data->email);
     if (empty($user)) {
         throw new Exception('Такой пользователь не существует', self::ERROR_INVALID_EMAIL);
     }
     if (!\T4\Crypt\Helpers::checkPassword($data->password, $user->password)) {
         throw new Exception('Неверный пароль', self::ERROR_INVALID_PASSWORD);
     }
     $this->login($user);
     Application::getInstance()->user = $user;
     return $user;
 }
Example #14
0
 public function restorePsw()
 {
     $user = User::findByEmail($this->email);
     if ($user) {
         if ($user->password_reset_token === '') {
             $user->password_reset_token = Yii::$app->security->generateRandomString();
             $user->save();
         }
         $this->sendEmail($this->email, $user->id, $user->password_reset_token);
         return true;
     }
     return false;
 }
Example #15
0
 public function resetPassword()
 {
     if ($this->validate()) {
         $user = User::findByEmail($this->email, true);
         if (is_null($user)) {
             $this->addError('email', '无效的邮箱');
             return false;
         }
         $user->salt = Str::random(10);
         $user->password = $user->generatePassword($this->password);
         return $user->save();
     }
     $this->addError('password', '重置密码失败');
     return false;
 }
Example #16
0
 public function testSuccess()
 {
     $form = new SignupForm(['fullName' => 'Test', 'email' => '*****@*****.**', 'password' => 'test_password']);
     $user = $form->signup();
     expect($user)->isInstanceOf('app\\models\\User');
     expect_not($user->isConfirmed());
     expect($user->email)->equals('*****@*****.**');
     expect_that($user->validatePassword('test_password'));
     expect_that($form->sendEmail());
     $user = User::findByEmail('*****@*****.**');
     expect($user->profile->full_name)->equals('Test');
     $message = $this->tester->grabLastSentEmail();
     expect('valid email is sent', $message)->isInstanceOf('yii\\mail\\MessageInterface');
     expect($message->getTo())->hasKey($user->email);
     expect($message->getFrom())->hasKey('*****@*****.**');
 }
 /**
  * Sends an email with a link, for resetting the password
  *
  * @return boolean
  */
 public function sendEmail()
 {
     /* @var $user User */
     $user = User::findByEmail($this->email);
     if ($user) {
         if (!User::isTokenValid($user->password_reset_token)) {
             $user->generatePasswordResetToken();
         }
         if ($user->save(false)) {
             return Yii::$app->notify->sendMessage($this->email, Yii::t('app', 'Password Reset'), 'passwordResetToken', ['user' => $user]);
         }
         // @codeCoverageIgnore
     }
     // @codeCoverageIgnore
     return false;
 }
Example #18
0
 public function register($data)
 {
     $errors = new MultiException();
     if (empty($data->email)) {
         $errors->add('Не введен e-mail', self::ERROR_INVALID_EMAIL);
     }
     if (empty($data->password)) {
         $errors->add('Не введен пароль', self::ERROR_INVALID_PASSWORD);
     }
     if (empty($data->password2)) {
         $errors->add('Не введено подтверждение пароля', self::ERROR_INVALID_PASSWORD);
     }
     if ($data->password2 != $data->password) {
         $errors->add('Введенные пароли не совпадают', self::ERROR_INVALID_PASSWORD);
     }
     if (!$errors->isEmpty()) {
         throw $errors;
     }
     $user = User::findByEmail($data->email);
     if (!empty($user)) {
         $errors->add('Такой e-mail уже зарегистрирован', self::ERROR_INVALID_EMAIL);
     }
     if (!$errors->isEmpty()) {
         throw $errors;
     }
     $app = Application::getInstance();
     if ($app->config->extensions->captcha->register) {
         if (empty($data->captcha)) {
             $errors->add('Не введена строка с картинки', self::ERROR_INVALID_CAPTCHA);
         } else {
             if (!$app->extensions->captcha->checkKeyString($data->captcha)) {
                 $errors->add('Неверные символы с картинки', self::ERROR_INVALID_CAPTCHA);
             }
         }
     }
     if (!$errors->isEmpty()) {
         throw $errors;
     }
     $user = new User();
     $user->email = $data->email;
     $user->password = \T4\Crypt\Helpers::hashPassword($data->password);
     $user->save();
     return $user;
 }
Example #19
0
 public function actionAdduser()
 {
     /*       echo \Yii::$app->basePath;
             echo \Yii::$app->session->get('role');
             exit('1');*/
     if (!($post = \Yii::$app->getRequest()->getBodyParams())) {
         throw new \yii\web\HttpException(400, 'Дані не отримані');
     }
     $userModel = new User();
     if ($userModel->findByLogin($post['login'])) {
         throw new \yii\web\HttpException(400, 'Користувач з таким логіном уже існує');
     }
     if ($userModel->findByEmail($post['email'])) {
         throw new \yii\web\HttpException(400, 'Користувач з таким емейлом уже існує');
     }
     $transaction = \Yii::$app->db->beginTransaction();
     try {
         $userModel = new User();
         $userModel->login = $post['login'];
         $password = $post['password'];
         $validator = new \yii\validators\StringValidator(['min' => 3, 'max' => 12, 'tooShort' => 'Пароль повинен містити мінімум {min, number} символи', 'tooLong' => 'Пароль повинен містити не більше {max, number} символів']);
         if (!$validator->validate($password, $error)) {
             throw new \yii\web\HttpException(422, $error);
         }
         $userModel->setPassword($post['password']);
         $userModel->email = $post['email'];
         $userModel->role_id = 1;
         $userModel->generateAuthKey();
         if (!$userModel->save()) {
             foreach ($userModel->errors as $key) {
                 $errorMessage .= $key[0];
             }
             throw new \yii\web\HttpException(422, $errorMessage);
         }
         $transaction->commit();
     } catch (Exception $e) {
         $transaction->rollBack();
         throw new \yii\web\HttpException(422, $errorMessage . $error);
         return $errorMessage . $error;
     }
     exit('end');
 }
 /**
  * @SuppressWarnings(PHPMD.ElseExpression)
  */
 public function handle()
 {
     $user = $this->findUserByProvider();
     if ($user) {
         $this->exist = true;
     } else {
         $profile = $this->client->getUserAttributes();
         $this->email = ArrayHelper::getValue($profile, 'email');
         $this->verified = ArrayHelper::getValue($profile, 'verified');
         if ($this->verified && !empty($this->email)) {
             $user = User::findByEmail($this->email);
         }
         if (!$user) {
             $user = new User();
             $user->setProfile($this->parseProfile());
         }
     }
     $user->setProviders($this->parseProvider());
     $this->user = $user;
     return $this;
 }
Example #21
0
 /**
  * Obtain the user information from Provider.
  *
  * @param  string          $provider
  * @param  Socialite|SocialiteManager       $socialite
  * @param  User  $userModel
  *
  * @throws UnprocessableEntityException
  *
  * @return ApiResponse
  */
 public function handleProviderCallback($provider, Socialite $socialite, User $userModel)
 {
     $this->validateProvider($provider);
     $socialUser = $socialite->with($provider)->user();
     // Verify so we received an email address, if using oAuth credentials
     // with Twitter for instance, that isn't whitelisted, no email
     // address will be returned with the response.
     // See the notes in Spira API doc under Social Login for more info.
     if (!$socialUser->email) {
         // The app is connected with the service, but the 3rd party service
         // is not configured or allowed to return email addresses, so we
         // can't process the data further. Let's throw an exception.
         \Log::critical('Provider ' . $provider . ' does not return email.');
         throw new UnprocessableEntityException('User object has no email');
     }
     // Parse the social user to fit within Spira's user model
     $socialUser = ParserFactory::parse($socialUser, $provider);
     // Get or create the Spira user from the social login
     try {
         $user = $userModel->findByEmail($socialUser->email);
     } catch (ModelNotFoundException $e) {
         $user = $userModel->newInstance();
         $user->fill(array_merge($socialUser->toArray(), ['user_type' => 'guest']));
         $user->save();
     }
     $socialLogin = new SocialLogin(['provider' => $provider, 'token' => $socialUser->token]);
     $user->addSocialLogin($socialLogin);
     // Prepare response data
     $token = $this->jwtAuth->fromUser($user, ['method' => $provider]);
     $returnUrl = $socialite->with($provider)->getCachedReturnUrl() . '?jwtAuthToken=' . $token;
     $response = $this->getResponse();
     $response->redirect($returnUrl, 302);
     return $response;
 }
 public function testLoginAfterSignupVkontakteAndBlocked($I)
 {
     $this->signup($I, 'vkontakte', '*****@*****.**');
     $I->amOnRoute('/');
     $I->see('Activate Your Account');
     $I->dontSee('signup');
     $I->dontSeeElement($this->formId);
     $user = User::findByEmail('*****@*****.**');
     $user->status = User::STATUS_BLOCKED;
     $user->save();
     Yii::$app->user->logout();
     $controller = new IndexController('test', 'default');
     $controller->successCallback($this->getProvider('vkontakte'));
     $I->amOnRoute('/index/signup-provider');
     $I->see('Your account has been suspended');
 }
Example #23
0
 /**
  * Checks whether email or login is unique
  */
 public function actionCheckUnique()
 {
     $post = Yii::$app->request->post();
     switch ($post['field']) {
         case 'email':
             $isUnique = User::findByEmail($post['value']) === null;
             break;
         case 'login':
             $isUnique = User::findByLogin($post['value']) === null;
             break;
         default:
             break;
     }
     Yii::$app->response->format = 'json';
     return ["result" => $isUnique];
 }
 /**
  * Get User model.
  * @param string $email
  * @return User
  * @throws \yii\console\Exception
  */
 protected function findUser($email)
 {
     if (!($user = User::findByEmail($email))) {
         throw new ConsoleException(Yii::t('app', 'User not found.'));
     }
     return $user;
 }
Example #25
0
 /**
  * 激活
  * @param $activationCode
  * @return string
  * @throws \yii\web\HttpException
  */
 public function actionActivate($activationCode)
 {
     // 数据库验证令牌
     $activation = Activation::findOne(['token' => $activationCode]);
     if (is_null($activation)) {
         throw new NotFoundHttpException('请求页面不存在');
     }
     // 激活对应用户
     $user = User::findByEmail($activation->email, true);
     $user->activated_at = new Carbon();
     $user->save();
     $activation->delete();
     // 删除令牌
     return $this->render('activation-success');
 }
 /**
  * Get user model by its name or email.
  * @param string $nameOrEmail
  * @throws InvalidArgumentException when user not found.
  * @return User
  */
 protected function getUser($nameOrEmail)
 {
     $emailValidator = new EmailValidator();
     if ($emailValidator->validate($nameOrEmail)) {
         $user = User::findByEmail($nameOrEmail);
     } else {
         $user = User::findOne(['name' => $nameOrEmail]);
     }
     if (!$user) {
         throw new InvalidArgumentException("Couldn't find user by specified email or name.");
     }
     return $user;
 }
Example #27
0
 /**
  * Finds user by username or email in 'lwe' scenario.
  *
  * @return User|null|static
  */
 public function getUser()
 {
     if ($this->_user === false) {
         // in 'lwe' scenario we find user by email, otherwise by username
         if ($this->scenario === 'lwe') {
             $this->_user = User::findByEmail($this->email);
         } else {
             $this->_user = User::findByUsername($this->username);
         }
     }
     return $this->_user;
 }
    public function actionCharge()
    {
        $session = new Session();
        \Stripe\Stripe::setApiKey(\Yii::$app->params['stripeSecretKey']);
        $get = \Yii::$app->request->get();
        $token = $get['stripeToken'];
        $email = $get['stripeEmail'];
        $user = User::findByEmail($email);
        $customer = \Stripe\Customer::create(array("source" => $token, "description" => $email, "email" => $email));
        if ($user->customer_token != $customer->id) {
            $user->customer_token = $customer->id;
            $user->save();
        }
        $cart = Cart::getCurrentCart();
        $cart->processCart();
        if ($cart->total == 0) {
            return $this->actionSave();
        }
        try {
            $stripe_user_id = $cart->items[0]->ticket->group->event->owner->stripe_user_id;
            if ($stripe_user_id) {
                $charge = \Stripe\Charge::create(array("amount" => floor($cart->total * 100), "application_fee" => floor($cart->fees * 100), "currency" => "gbp", "customer" => $customer->id, "description" => $cart->quantity . ' tickets', "destination" => $stripe_user_id));
                $cart->status = Cart::CART_SOLD;
                $cart->charge_id = $charge->id;
                $cart->charge_details = json_encode($charge);
                $cart->save();
                $session->addSuccess(Yii::t('app', 'Congratulations, you\'ve completed your order!'));
                $cart_lines = [];
                foreach ($cart->items as $item) {
                    $cart_lines[] = $item->ticket->group->event->name . ': ' . $item->ticket->name . ' x' . $item->quantity . ' @ ' . $item->ticket->ticket_price . ' each';
                }
                $cart_lines[] = 'Card fees @ ' . $cart->stripe_fee;
                $cart_details = implode("\n", $cart_lines);
                $email = new Email();
                $email->to_name = $user->name;
                $email->to_email = $user->email;
                $email->subject = "Your Tixty Purchase";
                $message = <<<EOT
Hi {$user->name}!!

You just bought {$cart->quantity} tickets for a total of {$cart->total} - details below.

Thanks,

Tixty

---
{$cart_details}
EOT;
                $email->body = nl2br($message);
                $email->save();
                $email->send();
                $email = new Email();
                $email->to_name = "Tixty";
                $email->to_email = \Yii::$app->params['adminEmail'];
                $email->subject = "Tixty Purchase #{$cart->id}";
                $message = <<<EOT
{$user->name} just bought {$cart->quantity} tickets for a total of {$cart->total} - details below.

Tixty

---
{$cart_details}
EOT;
                $email->body = nl2br($message);
                $email->save();
                $email->send();
            }
        } catch (\Stripe\Error\Card $e) {
            //card declined
            $session->addError(Yii::t('app', 'Looks like your card was declined or some other error happened'));
        }
        return $this->redirect('index');
    }
Example #29
0
 public function register()
 {
     if ($this->registerUser()) {
         $user = User::findByEmail($this->email);
         if ($user) {
             $this->sendEmail($user->email, $user->id, $user->email_confirm_token);
             return true;
         }
     }
     return false;
 }
Example #30
0
 public function checkSelfEmail($attribute, $params)
 {
     $model = User::findByEmail($this->{$attribute});
     if ($model && $model->id !== $this->user->id) {
         $this->addError($attribute, 'Этот e-mail уже используется.');
     }
 }