public function notifyAdminAboutUser(&$modelUser, $scenario)
 {
     $userEmail = $modelUser->email;
     $adminEmail = AuthCommon::getParam('adminEmail');
     $userName = $modelUser->username;
     switch ($scenario) {
         case 'insert':
             $actionSubject = 'Новый пользователь';
             $actionText = 'зарегистрировался';
             break;
         case 'activation':
             $actionSubject = 'Активация пользователя';
             $actionText = 'выполнил активацию';
             break;
         case 'update':
             $actionSubject = 'Изменение данных пользователя';
             $actionText = 'изменил данные';
             break;
         case 'passRestore':
             $actionSubject = 'Пользователь восстановил пароль';
             $actionText = 'восстановил пароль';
             break;
         default:
             return;
     }
     $websiteUrl = Yii::app()->getBaseUrl(true);
     $siteName = Yii::app()->name;
     $headers = AuthCommon::createMailHeader();
     $subjectTemplate = AuthCommon::getTemplateValue('mail', 'notifyAdmin_subject');
     $subject = sprintf($subjectTemplate, $actionSubject, $siteName);
     $textTemplate = AuthCommon::getTemplateValue('mail', 'notifyAdmin_text');
     $body = sprintf($textTemplate, $userName, $userEmail, $actionText, $websiteUrl);
     $subject = '=?UTF-8?B?' . base64_encode($subject) . '?=';
     return mail($adminEmail, $subject, $body, $headers);
 }
 public function renderIndex($model)
 {
     $maxAttemptsBeforeCaptha = (int) AuthCommon::getParam('attemptsBeforeCaptcha');
     if ($maxAttemptsBeforeCaptha != 0) {
         $loginAtteptsInSession = (int) Yii::app()->session['loginAtteptsInSession'];
         if ($loginAtteptsInSession > $maxAttemptsBeforeCaptha) {
             $model->scenario = 'withCaptcha';
         }
         Yii::app()->session['loginAtteptsInSession'] = ++$loginAtteptsInSession;
     }
     $this->render('index', array('model' => $model));
 }
 /**
  * Logs in the user using the given username and password in the model.
  * @return boolean whether login is successful
  */
 public function login()
 {
     if ($this->_identity === null) {
         $this->_identity = new UserIdentity($this->username, $this->password);
         $this->_identity->authenticate();
     }
     if ($this->_identity->errorCode === UserIdentity::ERROR_NONE) {
         $days = AuthCommon::getParam('cookieBasedLoginDays');
         if (empty($days)) {
             $days = 14;
         }
         $duration = $this->rememberMe ? 3600 * 24 * $days : 0;
         Yii::app()->user->login($this->_identity, $duration);
         return true;
     } else {
         return false;
     }
 }
 public function saveUnsuccessfulIpAttempt($ip, $username)
 {
     if (empty($ip)) {
         return;
     }
     $ipBlockedUntil = null;
     $unsafeIp = Unsafeip::model()->getByIp($ip);
     if ($unsafeIp == null) {
         $unsafeIp = new Unsafeip();
         $unsafeIp->ip_address = $ip;
     }
     $unsafeIp->attempts++;
     $unsafeIp->attempts_total++;
     $unsafeIp->comments = "user: " . $username;
     $maxAttempts = AuthCommon::getParam('ipBlockMaxLoginAttempts');
     if ($maxAttempts > 0) {
         if ($unsafeIp->attempts < $maxAttempts) {
             $unsafeIp->blocked_until = null;
         } else {
             $ipBlockTimeMinutes = AuthCommon::getParam('ipBlockTimeMinutes');
             if ($ipBlockTimeMinutes > 0) {
                 //block user
                 $dt = new DateTime();
                 $dt->add(new DateInterval('PT' . $ipBlockTimeMinutes . 'M'));
                 $unsafeIp->blocked_until = $dt->format(AuthCommon::getParam('dateFormat'));
                 $ipBlockedUntil = $dt;
             }
         }
     }
     if (!$unsafeIp->saveModel()) {
         //can't block user
         $ipBlockedUntil = null;
     }
     return $ipBlockedUntil;
 }
 /**
  * Performs the AJAX validation.
  * @param AdminUsers $model the model to be validated
  */
 protected function performAjaxValidation($model)
 {
     if (isset($_POST['ajax']) && $_POST['ajax'] === 'user-login') {
         //if we have an email as username, then find username by email in database
         if (strpos($model->username, '@', 1) !== false) {
             //this is an email so
             $email = $model->username;
             $user = Users::model()->getByEmail($email);
             if ($user != null) {
                 $username = $user->username;
                 $model->username = $username;
                 $modelName = CHtml::modelName($model);
                 $_POST[$modelName]['username'] = $username;
             }
         }
         $response = CActiveForm::validate($model);
         $responseArray = CJSON::decode($response);
         if (Yii::app()->user->hasFlash('error')) {
             $flashError = '';
             foreach (Yii::app()->user->getFlashes() as $key => $message) {
                 if ($key === 'error') {
                     $flashError .= $message . '<br>';
                 }
             }
             $flashArray = array('status' => 'error', 'message' => $flashError);
             $responseArray = array_merge($responseArray, $flashArray);
         }
         if ($response != '[]') {
             //some errors, so we stop next processing and print post data
             $maxAttemptsBeforeCaptha = (int) AuthCommon::getParam('attemptsBeforeCaptcha');
             if ($maxAttemptsBeforeCaptha != 0) {
                 $loginAtteptsInSession = (int) Yii::app()->session['loginAtteptsInSession'];
                 if ($loginAtteptsInSession > $maxAttemptsBeforeCaptha) {
                     $capthaArray = array('captcha' => 'on');
                     $responseArray = array_merge($responseArray, $capthaArray);
                 }
             }
             $response = CJSON::encode($responseArray);
             echo $response;
             Yii::app()->end();
         } else {
             unset(Yii::app()->session['loginAtteptsInSession']);
         }
     }
 }
예제 #6
0
 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;
 }
 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;
 }
예제 #8
0
<?php

$this->pageTitle = "Введите приглашение";
?>
<p>
В данное время регистрация новых пользователей производится по приглашениям (инвайтам).
</p>
<p>Если у вас нет приглашения, то его можно запросить, написав письмо на адрес:
    <?php 
try {
    $email = Helpers::getAppParam('adminEmail');
} catch (Exception $ex) {
    $email = AuthCommon::getParam('adminEmail');
}
echo CHtml::mailto($email, $email);
?>
</p>

<div class="margin-bottom-30"></div>
<div class="row">
    <div class="table-responsive col-md-5">
    <?php 
$formRender = new FormElements($this, $model);
$formRender->fieldClass = "col-sm-8";
$formRender->labelClass = "col-sm-3";
$formRender->submitOffcet = "col-sm-offset-3";
$formRender->startForm();
$formRender->showErrors();
$formRender->textField('guid', '', '', false);
if ($model->scenario == 'withCaptcha') {
    $formRender->capthaField('verifyCode');