Advertisement
Guest User

Untitled

a guest
Jun 11th, 2018
332
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 9.05 KB | None | 0 0
  1.     /**
  2.      * Восстановление пароля пользователя
  3.      */
  4.     public function forgot()
  5.     {
  6.         # Уже авторизован
  7.        if (User::id()) {
  8.             if (Request::isAJAX()) {
  9.                 $this->errors->impossible();
  10.                 $this->ajaxResponseForm();
  11.             }
  12.             $this->redirectToCabinet();
  13.         }
  14.  
  15.         $sKey = $this->input->getpost('key', TYPE_STR, array('len' => 100));
  16.         $bSocial = $this->input->getpost('social', TYPE_BOOL);
  17.         if (!empty($sKey)) {
  18.             # Шаг2: Смена пароля
  19.            if (Request::isAJAX()) {
  20.                 do {
  21.                     if (!$this->security->validateReferer()) {
  22.                         $this->errors->reloadPage();
  23.                         break;
  24.                     }
  25.                     # Ищем по "ключу восстановления"
  26.                    $aData = $this->model->userDataByFilter(array(
  27.                             'blocked'      => 0, # незаблокированные аккаунты
  28.                            'activate_key' => $sKey,
  29.                             array('activate_expire > :expire', ':expire' => $this->db->now()),
  30.                         ), array('user_id', 'email', 'password', 'password_salt', 'activated')
  31.                     );
  32.  
  33.                     // $this->ajaxResponseForm('salom dunyo'); break;
  34.  
  35.                     # Не нашли, возможные причины:
  36.                    # 1) Истек срок действия ссылки восстановления / неверная ссылка восстановления
  37.                    # 2) Аккаунт заблокирован
  38.                    if (empty($aData)) {
  39.                         $this->errors->set(_t('users', 'Срок действия ссылки восстановления пароля истек или ссылка некорректна, <a href="[link_fogot]">повторите попытку</a>.',
  40.                                 array('link_fogot' => static::url('forgot'))
  41.                             )
  42.                         );
  43.                         break;
  44.                     }
  45.  
  46.                     # Проверяем новый пароль
  47.                    $password = $this->input->post('pass', TYPE_NOTRIM);
  48.                     if (mb_strlen($password) < $this->passwordMinLength) {
  49.                         $this->errors->set(_t('users', 'Пароль не должен быть короче [min] символов', array('min' => $this->passwordMinLength)), 'pass');
  50.                         break;
  51.                     }
  52.  
  53.                     $nUserID = $aData['user_id'];
  54.  
  55.                     # Cохраняем новый пароль + активируем
  56.                    $this->model->userSave($nUserID, array(
  57.                         'password'     => $this->security->getUserPasswordMD5($password, $aData['password_salt']),
  58.                         'activated'    => 1,  # активируем, если аккаунт еще НЕ активирован
  59.                        'activate_key' => '', # сбрасываем ключ
  60.                    ));
  61.  
  62.                     # Закрепляем соц. аккаунт за профилем
  63.                    if ($bSocial) {
  64.                         $this->social()->authFinish($nUserID);
  65.                     }
  66.  
  67.                 } while (false);
  68.  
  69.                 $this->ajaxResponseForm();
  70.             }
  71.  
  72.             return $this->authPage('auth.forgot.finish', _t('users', 'Введите новый пароль'), array(
  73.                     'key'    => $sKey,
  74.                     'social' => $bSocial,
  75.                 )
  76.             );
  77.         } else {
  78.             # Шаг1: Инициация восстановления пароля по E-mail адресу
  79.            if (Request::isAJAX()) {
  80.                 $email = $this->input->post('email', TYPE_STR);
  81.                 do {
  82.  
  83.                     if($email)
  84.                     {
  85.                         $email = str_replace('+', '', $email);
  86.  
  87.                         if (strlen($email) !=  12)
  88.                         {
  89.                             $this->errors->set(_t('users', 'Номер телефона указан некорректно'), 'phone');
  90.                             break;
  91.                         }
  92.                         $phone = $email;
  93.                         $email = $email.'@mayak.uz';
  94.                     }
  95.                     // if (!$this->security->validateReferer()) {
  96.                     //     $this->errors->reloadPage();
  97.                     //     break;
  98.                     // }
  99.                     # Проверяем E-mail
  100.                    // if (!$this->input->isEmail($email)) {
  101.                     //     $this->errors->set(_t('users', 'E-mail адрес указан некорректно'), 'email');
  102.                     //     break;
  103.                     // }
  104.                     # Получаем данные пользователя
  105.                    # - восстановление пароля для неактивированных аккаунтов допустимо
  106.                    $aData = $this->model->userDataByFilter(array('email' => $email, 'blocked' => 0),
  107.                         array('user_id', 'name', 'password', 'password_salt', 'activated', 'activate_expire')
  108.                     );
  109.  
  110.  
  111.                     if (empty($aData)) {
  112.                         $this->errors->set(_t('users', 'Указанный e-mail в базе не найден1'), 'email');
  113.                         break;
  114.                     }
  115.  
  116.                     /**
  117.                      * Генерируем "ключ восстановления", помечаем период его действия.
  118.                      * В случае если аккаунт неактивирован, период действия ключа восстановления пароля будет равен
  119.                      * периоду действия ссылки активации аккаунта, поскольку задействуется
  120.                      * одно и тоже поле "activate_expire"
  121.                      */
  122.                     // $sKey = func::generator(20);
  123.                     $chars="23456789qazxsedcvfrtgbnhyujmkp";
  124.                     $max=4;
  125.                     $size=StrLen($chars)-1;
  126.                     $password=null;
  127.                         while($max--)
  128.                         $password.=$chars[rand(0,$size)];
  129.  
  130.                     $sKey = $password;
  131.  
  132.                     $bSaved = $this->model->userSave($aData['user_id'], array(
  133.                             'activate_key'    => $sKey,
  134.                             'activate_expire' => (!$aData['activated'] ? $aData['activate_expire'] :
  135.                                     date('Y-m-d H:i:s', strtotime('+4 hours'))),
  136.                             'activated' => (!$aData['activated'] ? 1 : 1),
  137.                             'password'     => $this->security->getUserPasswordMD5($sKey, $aData['password_salt']),
  138.                         )
  139.                     );
  140.  
  141.                     if (!$bSaved) {
  142.                         $this->errors->reloadPage();
  143.                     }
  144.                     else
  145.                     {
  146.  
  147.                         $this->sms()->sendActivationCode($phone, $sKey);
  148.                         // $this->model->userSave($nUserID, array(
  149.                         //     'password'     => $this->security->getUserPasswordMD5($password, $aData['password_salt']),
  150.                         //     'activated'    => 1,  # активируем, если аккаунт еще НЕ активирован
  151.                         //     'activate_key' => '', # сбрасываем ключ
  152.                         // ));
  153.  
  154.                         // $this->sms()->sendActivationCode($email, $aData['password_salt']);
  155.  
  156.                         # Отправляем письмо с инcтрукцией о смене пароля
  157.                        // $myemail = 'sherzod-sapaev@mail.ru';
  158.                         // bff::sendMailTemplate(array(
  159.                         //         'link'  => static::url('forgot', array('key' => $sKey, 'social' => $bSocial)),
  160.                         //         'email' => $myemail,
  161.                         //         'name'  => $aData['name']
  162.                         //     ), 'users_forgot_start', $myemail
  163.                         // );
  164.                         // $this->ajaxResponseForm($sKey); break;
  165.                     }
  166.                 } while (false);
  167.  
  168.                 $this->ajaxResponseForm();
  169.             }
  170.  
  171.             # seo
  172.            $this->urlCorrection(static::url('forgot'));
  173.             $this->setMeta('forgot');
  174.  
  175.             return $this->authPage('auth.forgot.start', _t('users', 'Введите электронную почту, которую вы указывали при регистрации'), array(
  176.                     'social' => $bSocial,
  177.                 )
  178.             );
  179.         }
  180.     }
  181.  
  182.     /**
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement