大家好我正在使用cakephp 2.x,因为我是新来的,我需要在将密码存储到数据库之前对其进行加密
User.ctp:我这样张贴发布
<?php
echo $this->Form->input('password',array('type'=>'password','label'=>false,'div'=>false,'class'=>'form-control','id'=>'password'));
?>
控制器:
public function setting()
{
$this->layout='setting_template';
if($this->Session->read('username')==""){
$this->redirect(array('action' => 'user_login'));
}
elseif ($this->Session->read('username') == "admin" )
{
if($this->request->is('post'))
{
$this->data['password'] = encrypt($this->data ['password']);
if ($this->Login->save($this->request->data)) {
$this->Session->setFlash('The user has been saved');
$this->redirect(array('action' => 'setting'));
} else {
$this->Session->setFlash('The user could not be saved. Please, try again.');
}
}
$opp=$this->Login->find('all');
$this->set('login',$opp);
}
else{
echo "<script type='text/javascript'> alert('Permission Denied'); </script>";
$this->redirect(array('action' => 'index'));
}
}
登录控制器:
public function login()
{
$this->layout='login_template';
if($this->data)
{
$this->Session->write('id',$this->data['Login']['id'] );
$results = $this->Login->find('first',array('conditions' => array('Login.password' => $this->data['Login']['password'],'Login.username' => $this->data['Login']['username'])));
$this->Session->write('name',$results['Login']['name']);
if ($results['Login']['id'])
{
$this->Session->write($this->data['Login']['username'].','. $this->data['Login']['password']);
$this->Session->write('username',$this->data['Login']['username']);
$this->redirect(array('action'=>'index'));
}
else
{
$this->Session->setFlash("error");
}
}
如何加密密码文件以及如何使用模型
答案 0 :(得分:4)
当您使用CakePhp
时,请使用框架的最佳做法。
创建新用户记录时,您可以在中填写密码 before使用适当的密码hasher保存模型的回调 类:
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
class User extends AppModel {
public function beforeSave($options = array()) {
if (!empty($this->data[$this->alias]['password'])) {
$passwordHasher = new SimplePasswordHasher(array('hashType' => 'sha256'));
$this->data[$this->alias]['password'] = $passwordHasher->hash(
$this->data[$this->alias]['password']
);
}
return true;
}
}
在调用$this->Auth->login()
之前,您无需哈希密码。各种身份验证对象将单独散列密码。
如果使用与User
不同的模型进行身份验证,则需要在AppController中定义该模型。在你的Case中你需要在AppController中做这样的事情:
$this->Auth->authenticate = array(
'Form' => array('userModel' => 'Login')
);
如果您希望哈希密码,请尝试以下操作:
$hashedPassword = AuthComponent::password('original_password');
答案 1 :(得分:-1)
怎么样
MD5($this->data['password']);
在控制器上?