我已经用用户登录系统构建了一个简单的 CakePHP 应用程序,并连接了 Milesj.me 的 Cake Form 插件(不确定这是否会导致问题)。
但是,我的验证似乎已应用于登录表单和注册表单。因此,当我尝试登录时,我收到诸如“用户名已在使用”之类的错误。
有什么想法会导致这种情况吗?CakePHP 中是否发生了一些变化,也将验证添加到了身份验证表单中?
另外,为什么我必须在模型中对密码进行哈希处理?我的印象是 CakePHP 会自动对密码进行哈希处理?而且我以前不需要这样做。但是,如果我不这样做,那么它将密码保存在数据库中,而不是散列......
这是我的视图、控制器和模型:
<?php echo $this->Form->create(); ?>
<?php echo $this->Form->input('User.username',
array('tabindex'=>1, 'autofocus',
'label'=>array('class'=>'placeholder','text'=>'Username'))); ?>
<?php echo $this->Form->input('User.password',
array('tabindex'=>2, 'type'=>'password',
'label'=>array('class'=>'placeholder','text' =>'Password' ))); ?>
<div class="input button">
<button class="orangeButton" tabindex="3" type="submit"><span class="icon login">Log in</span></button>
</div>
<?php echo $this->Form->end(); ?>
控制器:
public function login() {
if ($this->request->data) {
$this->User->set($this->request->data);
if ($this->User->validates() && $this->Auth->login()) {
if ($user = $this->Auth->user()) {
$this->User->Profile->login($user['id']);
$this->Session->delete('Forum');
$this->redirect($this->referer());
}
}
}
}
注意:对 Profile 模型的登录调用只是保存了一些上次登录时间的数据和其他内容,实际上并没有对身份验证做任何事情!
和模型:
class User extends AppModel {
public $name = 'User';
public $hasOne = array(
'Profile' => array('className' => 'Forum.Profile')
);
public $hasMany = array(
'Access' => array('className' => 'Forum.Access'),
'Moderator' => array('className' => 'Forum.Moderator')
);
public $validate = array(
'email' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A valid email address is required'
),
'email' => array(
'rule' => array('email'),
'message' => 'This is not a valid email address'
),
'unique' => array(
'rule' => array('isUnique'),
'message' => 'This email is already in use'
)
),
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
),
'unique' => array(
'rule' => array('isUnique'),
'message' => 'This username is already in use'
),
'alphaNumeric' => array(
'rule' => array('alphaNumeric'),
'message' => 'Usernames must only contain letters and numbers'
),
'between' => array(
'rule' => array('between', 4, 20),
'message' => 'Usernames must be between 4 and 20 characters long'
)
),
'password' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A password is required'
)
)
);
public function beforeSave()
{
if (isset($this->data[$this->alias]['password']))
{
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}