CakePHP登录用户名/密码验证

时间:2011-11-30 08:28:27

标签: php cakephp login

我在users_controller中有以下内容,因为执行登录需要进一步的逻辑,但是当在CakePHP中完成时,默认验证停止,因此我尝试在执行帐户检查之前强制它验证用户名和密码字段。一切正常但是这个。我已经尝试添加两个if语句(下面)来检查用户名/密码是否为空,但是一旦页面加载它们就为空并且验证框显示。

我很难过如何实现这一目标。任何帮助将不胜感激。

    function login() {
    if($this->Auth->user()) {
        $this->redirect(array('controller'=>'shows'));
    }
    if(empty($this->data['User']['username'])) {
        $this->User->validationErrors['username'] = "Please enter a username";
    }
    if(empty($this->data['User']['password'])) {
        $this->User->validationErrors['password'] = "Please enter a password";
    }
    if(!empty($this->data['User']['username'])) {
        // unset unrequired validation rules
        unset($this->User->validate['username']['unique']);

        // validate form
        $this->User->set($this->data);
        if($this->User->validates()) {
            // update Last Login date
            $this->User->id = $this->User->_user['User']['id'];
            $this->User->saveField('last_login',date("Y-m-d H:i:s"));

            // save User to Session and redirect
            $this->Session->write('User', $this->User->_user);
            $this->Session->setFlash('You have successfully logged in.','default',array('class'=>'flash_green'));
            //$this->redirect(array('controller'=>'shows', 'admin'=>FALSE));
        } else {
            $this->Session->setFlash('Incorrect username/password combination.','default',array('class'=>'flash_red'));
            $this->redirect(array('controller'=>'users', 'action'=>'login', 'admin'=>FALSE));
        }
    }
}

users_controller beforeFilter()

    function beforeFilter(){
    parent::beforeFilter();
    $this->Auth->allow('register');
}

app_controller beforeFilter和components

    var $components = array('Session', 'Auth' => array(
    'loginAction' => array('controller'=>'users','action'=>'login', 'admin'=>false),
    //'logoutRedirect' => array('controller'=>'users','action'=>'logout'),
    'loginRedirect' => array('controller'=>'shows', 'action'=>'index'),
    'autoRedirect' => false,
    'authorize' => 'controller')
);

function beforeFilter() {
    $this->Auth->allow('home');
    $this->set('admin', $this->_isAdmin());
    $this->set('logged_in', $this->_loggedIn());
    $this->set('users_username', $this->_usersUsername());
}

2 个答案:

答案 0 :(得分:0)

如果您的“默认验证”停止,则出现问题。如果您在模型中的过滤器中有某些内容,请确保它们返回true。我建议你为此写一个单元测试。

你绝对不必在控制器中执行!空检查。无论如何,整个代码块可以减少到~6行。其中大部分应该进入模型。

检查此插件或查看其代码以获得一个想法。 https://github.com/CakeDC/users/

答案 1 :(得分:0)

从user_controller.php文件中删除以下代码。

 else {
        $this->Session->setFlash('Incorrect username/password combination.','default',array('class'=>'flash_red'));
        $this->redirect(array('controller'=>'users', 'action'=>'login', 'admin'=>FALSE));
    }

这会将页面循环回登录操作,没有数据,因此无法验证。

相关问题