[英]CakePHP Login Username/Password Validation
我在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和组件
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());
}
如果您的“默认验证”停止,则那里出了点问题。 如果模型中的before过滤器中包含某些内容,请确保它们返回true。 我建议您为此编写一个单元测试。
您绝对不必在控制器中执行!empty检查。 无论如何,整个代码块都可以减少到约6行。 其中大多数应纳入模型。
检查此插件或查看其代码以了解想法。 https://github.com/CakeDC/users/
从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));
}
这将页面循环回登录操作,没有数据,因此也没有验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.