Как вы можете проверить, активен ли пользователь в компоненте аутентификации Cakephp 2.0? - PullRequest
1 голос
/ 22 января 2012

У меня проблемы с хэшированием, как проверить, активен ли пользователь, используя новый компонент Auth.У меня есть 3 состояния, в которых может находиться пользователь: 0 неактивировано (по умолчанию), 1 активировано, 2 деактивировано.Я пытаюсь реализовать это в функции входа в систему, чтобы я мог вернуть, если они не зарегистрированы или были забанены.

Логин :

        public function login() {
        if ($this->request->is('post')) {
            if($this->Auth->login()) {                   
                $results = $this->User->find('all', array(
                    'conditions' => array('User.email' => $this->Auth->user('email')),
                    'fields' => array('User.is_active')
                ));
                if ($results['User']['is_active'] == 0) {
                    // User has not confirmed account
                    $this->Session->setFlash('Your account has not been activated. Please check your email.');
                    $this->Auth->logout();
                    $this->redirect(array('action'=>'login'));
                }
               // not working atm
                else if ($results['User']['is_active'] == 2) {
                    // User has been deactivated
                    $this->Session->setFlash('Your account has been deactivated. Contact site admin if you believe this is in error.');
                    $this->Auth->logout();
                    $this->redirect(array('action'=>'login'));
                }
                else if ($results['User']['is_active'] == 1) {
                    // User is active
                      $this->redirect($this->Auth->redirect());
                    }
            } else {
                $this->Session->setFlash(__('Your email/password combination was incorrect'));
            }
        }
    }

Не вижу, где я ошибся.Пользователи с правами администратора и активированными пользователями все еще получают ошибку неактивированной учетной записи.

Обновление

Принято решение удалить поле User.is_active и обработать его в ролях.Я работаю с ним в AppController, и он почти работает сейчас.В функции isAuthorized теперь выдает ошибки, если пользователь забанен или неактивирован, но он мне также нужен для выхода из системы.

    public function isAuthorized($user) {
    // This isAuthorized determines what logged in users are able to see on ALL controllers. Use controller
    // by controller isAuthorized to limit what they can view on each one. Basically, you do not want to allow
    // actions on all controllers for users. Only admins can access every controller.
    if (isset($user['role']) && $user['role'] === 'admin') {
        return true; //Admin can access every action
    }
    elseif (isset($user['role']) && $user['role'] === 'unactivated') { // Account has not been activated
        $this->Session->setFlash("You haven't activated your account yet. Please check your email.");
        return false; 
    }
    elseif (isset($user['role']) && $user['role'] === 'banned') { // Your account has been banned
        $this->Session->setFlash("You're account has been banned. If you feel this was an error, please contact the site administrator.");
        return false;
    }
    return false; // The rest don't
}

1 Ответ

8 голосов
/ 22 января 2012

Если они войдут в систему, информация о модели пользователя будет доступна с помощью $this->Auth->user().Таким образом, вы должны иметь возможность сделать что-то вроде этого:

if ($this->Auth->login()) {
    if ($this->Auth->user('is_active') == 0) {
        // User has not confirmed account
    } else if ($this->Auth->user('is_active') == 1) {
        // User is active

    // and so on

Вы можете использовать debug($this->Auth->user()); после login(), чтобы увидеть, почему пользователи продолжают показываться как неактивированные.

...