public function saveModel()
 {
     if ($this->scenario == 'insert') {
         $hash = password_hash($this->password_entered, PASSWORD_BCRYPT, array('cost' => 10));
         $this->password_hash = $hash;
         $dt = new DateTime();
         $this->date_reg = $dt->format(AuthCommon::getParam('dateFormat'));
         $ip = AuthCommon::getUserIp();
         $this->ip_endorsed = $ip;
     } elseif ($this->scenario == 'update' || $this->scenario == 'passRestore') {
         if (!empty($this->password_entered)) {
             $hash = password_hash($this->password_entered, PASSWORD_BCRYPT, array('cost' => 10));
             $this->password_hash = $hash;
         }
     } elseif ($this->scenario == 'activation') {
         $this->activated = true;
     }
     $scenario = $this->scenario;
     if (!$this->save()) {
         yii::app()->user->setFlash('error', CHtml::errorSummary($this));
         return false;
     }
     //add default subscriptions
     if ($scenario == 'activation') {
         Helpers::setUserDefaultParameters($this->id);
     }
     //send message to Admin about changes
     if ($scenario != 'extServiceLogin' && $scenario != 'setLastLogin') {
         $result = AuthCommon::notifyAdminAboutUser($this, $scenario);
     }
     return true;
 }
 /**
  * Authenticates a user.
  * The example implementation makes sure if the username and password
  * are both 'demo'.
  * In practical applications, this should be changed to authenticate
  * against some persistent user identity storage (e.g. database).
  * @return boolean whether authentication succeeds.
  */
 public function authenticate($isExtServiceLogin = false)
 {
     $ip = AuthCommon::getUserIp();
     $timeZoneLabel = AuthCommon::getParam('timeZoneLabel');
     $dateFormat = AuthCommon::getParam('dateFormat');
     if (!empty($ip)) {
         $result = $this->checkIpBlocked($ip);
         if ($result != null) {
             $this->errorCode = self::ERROR_UNKNOWN_IDENTITY;
             yii::app()->user->setFlash('error', sprintf(Yii::t('AuthModule.main', 'Your IP address has been blocked'), $ip, $result, $timeZoneLabel));
             return false;
         }
     }
     $modelUser = Users::model()->getByUsername($this->username);
     if (empty($modelUser)) {
         $this->errorCode = self::ERROR_UNKNOWN_IDENTITY;
         $this->saveUnsuccessfulIpAttempt($ip, $this->username);
         Yii::app()->user->setFlash('error', Yii::t('AuthModule.main', 'Inrorrect login or password'));
         return false;
     }
     if (!$modelUser->activated) {
         $this->errorCode = self::ERROR_UNKNOWN_IDENTITY;
         Yii::app()->user->setFlash('error', sprintf(Yii::t('AuthModule.main', 'User not activated'), $modelUser->username));
         return false;
     }
     if ($modelUser->blocked) {
         //blocked by admin
         $this->errorCode = self::ERROR_UNKNOWN_IDENTITY;
         Yii::app()->user->setFlash('error', sprintf(Yii::t('AuthModule.main', 'User has been blocked'), $modelUser->username));
         return false;
     }
     if ($modelUser->deleted) {
         $this->errorCode = self::ERROR_UNKNOWN_IDENTITY;
         Yii::app()->user->setFlash('error', sprintf(Yii::t('AuthModule.main', 'User has been deleted'), $modelUser->username));
         return false;
     }
     $result = $this->checkUserBlocked($modelUser);
     if ($result != null) {
         $this->errorCode = self::ERROR_UNKNOWN_IDENTITY;
         Yii::app()->user->setFlash('error', sprintf(Yii::t('AuthModule.main', 'User has been blocked until'), $result));
         return false;
     }
     if (!$isExtServiceLogin) {
         $password_hash = $modelUser->password_hash;
         $pass = $this->password;
         if (!password_verify($pass, $password_hash)) {
             $this->errorCode = self::ERROR_PASSWORD_INVALID;
             $result = $this->saveUnsuccessfulIpAttempt($ip, $modelUser->username);
             if ($result != null) {
                 Yii::app()->user->setFlash('error', sprintf(Yii::t('AuthModule.main', 'Too much login attempts from IP'), $ip, $result->format($dateFormat), $timeZoneLabel));
                 return;
             }
             $result = $this->saveUnsuccessfulUserAttempt($modelUser);
             if ($result != null) {
                 Yii::app()->user->setFlash('error', sprintf(Yii::t('AuthModule.main', 'Too much login attempts from user'), $modelUser->username, $result->format($dateFormat), $timeZoneLabel));
                 return;
             }
             Yii::app()->user->setFlash('error', Yii::t('AuthModule.main', 'Login failed'));
             return false;
         }
     }
     //login OK
     $this->errorCode = self::ERROR_NONE;
     $this->_id = $modelUser->id;
     $this->saveSuccessfulUserAttemt($modelUser);
     $this->saveSuccessfulIpAttemt($ip);
     // Generate a login token and save it in the DB
     $dt = new DateTime();
     $modelUser->date_lastlogin = $dt->format($dateFormat);
     $modelUser->setScenario('setLastLogin');
     $modelUser->logintoken = sha1(uniqid(mt_rand(), true));
     if ($modelUser->save()) {
         //the login token is saved as a state
         $this->setState(self::LOGIN_TOKEN, $modelUser->logintoken);
     } else {
         yii::app()->user->setFlash('error', CHtml::errorSummary($modelUser));
     }
     $this->setState('username', $modelUser->username);
     $this->setState('fullname', $modelUser->full_name);
     return true;
 }
 private function getUserByServiceProfile($serviceProfile, $service)
 {
     //check if user exist in database
     $serviceUserId = $serviceProfile->identifier;
     $serviceUserEmail = $serviceProfile->emailVerified;
     //define service username
     if (array_key_exists('username', $serviceProfile) && !empty($serviceProfile->username)) {
         $serviceUsername = $serviceProfile->username;
     } else {
         $serviceUsername = $serviceProfile->firstName . '' . $serviceProfile->lastName;
     }
     $dt = new DateTime();
     $currentDateString = $dt->format(AuthCommon::getParam('dateFormat'));
     $ExtAccount = ExtAccounts::model()->getUserByServiceIndentifier($service, $serviceUserId);
     if ($ExtAccount == null) {
         //create external account
         $ExtAccount = new ExtAccounts();
         $ExtAccount->date_connected = $currentDateString;
         $ExtAccount->provider_name = $service;
         //check user in database by email
         if (!empty($serviceUserEmail)) {
             $siteUser = Users::model()->getByEmail($serviceUserEmail);
         } else {
             //no external email, so we try to find by existing non manually created users
             //$isCreatedManually=false;
             //$siteUser=Users::model()->getByUsername($serviceUsername, $isCreatedManually);
             $accountName = Yii::t('userProfile', $service);
             throw new CHttpException(404, 'Нет адреса электронной почты в учетной записи ' . $accountName);
         }
     } else {
         //serivce found in database
         $userId = $ExtAccount->user_id;
         $siteUser = Users::model()->findByPk($userId);
     }
     if ($siteUser == null) {
         //create database user
         $siteUser = new Users();
         $siteUser->created_manually = false;
         $siteUser->date_reg = $currentDateString;
         $siteUser->activated = true;
         //do not need activation by email
         $siteUser->ip_endorsed = AuthCommon::getUserIp();
         $userContemporary = new UsersComplementary();
     } else {
         //update database user
         $userContemporary = UsersComplementary::model()->getByUserById($siteUser->id);
     }
     if ($userContemporary == null) {
         $userContemporary = new UsersComplementary();
     }
     $isNewUserContemporary = $userContemporary == null;
     $siteUser->scenario = 'extServiceLogin';
     $siteUser->date_lastlogin = $currentDateString;
     if (!$siteUser->created_manually) {
         //update user data if it is not created manually
         $siteUser->username = $serviceUsername;
         $siteUser->full_name = $serviceProfile->firstName . ' ' . $serviceProfile->lastName;
         if (empty($siteUser->email)) {
             $siteUser->email = $serviceUserEmail;
         }
         $siteUser->comments = 'Updated from ' . ucwords($service);
     }
     if ($siteUser->saveModel() === false) {
         throw new CHttpException(404, CHtml::errorSummary($siteUser));
     }
     if ($isNewUserContemporary || !$siteUser->created_manually) {
         $userContemporary->scenario = 'extServiceLogin';
         $userContemporary->user_id = $siteUser->id;
         $userContemporary->city = $serviceProfile->city;
         $userContemporary->country = $serviceProfile->country;
         $userContemporary->picture_url = $serviceProfile->photoURL;
         $userContemporary->language = $serviceProfile->language;
         $userContemporary->comments = 'Updated from ' . ucwords($service);
         if ($userContemporary->saveModel() === false) {
             throw new CHttpException(404, CHtml::errorSummary($userContemporary));
         }
     }
     //fill service user data
     $ExtAccount->user_id = $siteUser->id;
     $ExtAccount->connected = true;
     $ExtAccount->service_user_email = $serviceUserEmail;
     $ExtAccount->service_user_id = $serviceUserId;
     if ($ExtAccount->saveModel() === false) {
         throw new CHttpException(404, CHtml::errorSummary($ExtAccount));
     }
     return $siteUser;
 }