Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Восстановление пароля пользователя
- */
- public function forgot()
- {
- # Уже авторизован
- if (User::id()) {
- if (Request::isAJAX()) {
- $this->errors->impossible();
- $this->ajaxResponseForm();
- }
- $this->redirectToCabinet();
- }
- $sKey = $this->input->getpost('key', TYPE_STR, array('len' => 100));
- $bSocial = $this->input->getpost('social', TYPE_BOOL);
- if (!empty($sKey)) {
- # Шаг2: Смена пароля
- if (Request::isAJAX()) {
- do {
- if (!$this->security->validateReferer()) {
- $this->errors->reloadPage();
- break;
- }
- # Ищем по "ключу восстановления"
- $aData = $this->model->userDataByFilter(array(
- 'blocked' => 0, # незаблокированные аккаунты
- 'activate_key' => $sKey,
- array('activate_expire > :expire', ':expire' => $this->db->now()),
- ), array('user_id', 'email', 'password', 'password_salt', 'activated')
- );
- // $this->ajaxResponseForm('salom dunyo'); break;
- # Не нашли, возможные причины:
- # 1) Истек срок действия ссылки восстановления / неверная ссылка восстановления
- # 2) Аккаунт заблокирован
- if (empty($aData)) {
- $this->errors->set(_t('users', 'Срок действия ссылки восстановления пароля истек или ссылка некорректна, <a href="[link_fogot]">повторите попытку</a>.',
- array('link_fogot' => static::url('forgot'))
- )
- );
- break;
- }
- # Проверяем новый пароль
- $password = $this->input->post('pass', TYPE_NOTRIM);
- if (mb_strlen($password) < $this->passwordMinLength) {
- $this->errors->set(_t('users', 'Пароль не должен быть короче [min] символов', array('min' => $this->passwordMinLength)), 'pass');
- break;
- }
- $nUserID = $aData['user_id'];
- # Cохраняем новый пароль + активируем
- $this->model->userSave($nUserID, array(
- 'password' => $this->security->getUserPasswordMD5($password, $aData['password_salt']),
- 'activated' => 1, # активируем, если аккаунт еще НЕ активирован
- 'activate_key' => '', # сбрасываем ключ
- ));
- # Закрепляем соц. аккаунт за профилем
- if ($bSocial) {
- $this->social()->authFinish($nUserID);
- }
- } while (false);
- $this->ajaxResponseForm();
- }
- return $this->authPage('auth.forgot.finish', _t('users', 'Введите новый пароль'), array(
- 'key' => $sKey,
- 'social' => $bSocial,
- )
- );
- } else {
- # Шаг1: Инициация восстановления пароля по E-mail адресу
- if (Request::isAJAX()) {
- $email = $this->input->post('email', TYPE_STR);
- do {
- if($email)
- {
- $email = str_replace('+', '', $email);
- if (strlen($email) != 12)
- {
- $this->errors->set(_t('users', 'Номер телефона указан некорректно'), 'phone');
- break;
- }
- $phone = $email;
- $email = $email.'@mayak.uz';
- }
- // if (!$this->security->validateReferer()) {
- // $this->errors->reloadPage();
- // break;
- // }
- # Проверяем E-mail
- // if (!$this->input->isEmail($email)) {
- // $this->errors->set(_t('users', 'E-mail адрес указан некорректно'), 'email');
- // break;
- // }
- # Получаем данные пользователя
- # - восстановление пароля для неактивированных аккаунтов допустимо
- $aData = $this->model->userDataByFilter(array('email' => $email, 'blocked' => 0),
- array('user_id', 'name', 'password', 'password_salt', 'activated', 'activate_expire')
- );
- if (empty($aData)) {
- $this->errors->set(_t('users', 'Указанный e-mail в базе не найден1'), 'email');
- break;
- }
- /**
- * Генерируем "ключ восстановления", помечаем период его действия.
- * В случае если аккаунт неактивирован, период действия ключа восстановления пароля будет равен
- * периоду действия ссылки активации аккаунта, поскольку задействуется
- * одно и тоже поле "activate_expire"
- */
- // $sKey = func::generator(20);
- $chars="23456789qazxsedcvfrtgbnhyujmkp";
- $max=4;
- $size=StrLen($chars)-1;
- $password=null;
- while($max--)
- $password.=$chars[rand(0,$size)];
- $sKey = $password;
- $bSaved = $this->model->userSave($aData['user_id'], array(
- 'activate_key' => $sKey,
- 'activate_expire' => (!$aData['activated'] ? $aData['activate_expire'] :
- date('Y-m-d H:i:s', strtotime('+4 hours'))),
- 'activated' => (!$aData['activated'] ? 1 : 1),
- 'password' => $this->security->getUserPasswordMD5($sKey, $aData['password_salt']),
- )
- );
- if (!$bSaved) {
- $this->errors->reloadPage();
- }
- else
- {
- $this->sms()->sendActivationCode($phone, $sKey);
- }
- } while (false);
- $this->ajaxResponseForm();
- }
- # seo
- $this->urlCorrection(static::url('forgot'));
- $this->setMeta('forgot');
- return $this->authPage('auth.forgot.start', _t('users', 'Введите электронную почту, которую вы указывали при регистрации'), array(
- 'social' => $bSocial,
- )
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement