【发布时间】:2014-04-11 11:28:27
【问题描述】:
我是 Cakephp 的新手,正在尝试制作一个简单的用户注册和登录应用程序。编写代码后,我面临的问题是我的登录表单正在授权任何电子邮件和密码,并重定向到我在登录后设置的页面。 这是我的代码:
在AppController.php
App::uses('Controller', 'Controller');
class AppController extends Controller
{
var $components = array('Auth');
}
在 UserController.php
<?php
//Filename -UsersController.php
//Registering new users and login
class UsersController extends AppController
{
public $helpers = array('Html','Form','Session');
public $components = array('Session',
'Auth' => array(
'authenticate' => array(
'Form' => array (
'fields' => array('username'=>'email','password'=>'password')
))));
/**
* Function for saving a new user
*/
public function index()
{
if($this->request->is('post'))
{
//print_r($this->request->data);die;
$this->User->create();
if($this->User->save($this->request->data))
{
$this->Session->setFlash(__('Congrats, you are registered successfully'));
return $this->redirect(array('action'=>'index'));
}
$this->Session->setFlash(__('Unable to store the user'));
}
}
/**
* Function for login functionality
*/
function beforeFilter()
{
$this->Auth->loginRedirect=array('controller'=>'pages','action'=>'welcome');
$this->Auth->logoutRedirect = array('controller'=>'pages','action'=>'welcome');
}
public function login()
{
if($this->request->is('post'))
{
if($this->Auth->login())
{
//print_r($this->request->data);die;
$this->redirect($this->Auth->redirect());
}
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
public function logout() {
return $this->redirect($this->Auth->logout());
} }
在模型中User.php
<?php
// Filename - User.php
// Model for registering new users
App::uses('AppModel', 'Model');
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
class User extends AppModel
{
public $validate = array(
'username'=>array('required'=>array(
'rule'=>array('notEmpty'),
'message'=>'Username is required'
)),
'password'=>array('required'=>array(
'rule'=>array('notEmpty'),
'message'=>'Password is required'
)),
'email'=>array('required'=>array(
'rule'=>array('notEmpty'),
'message'=>'Email is required'
))
);
public function beforeSave($options = array())
{
if(isset($this->data['User']['password']))
{
$passwordHasher = new SimplePasswordHasher();
$this->data['User']['password']=
$passwordHasher->hash($this->data['User']['password']);
}
return true;
}
}
在 login.ctp
<?php
echo $this->Form->create();
echo $this->Form->input('username',array('style'=>'width:200px;'));
echo $this->Form->input('password',array('style'=>'width:200px;'));
echo $this->Form->end('Sign in');
?>
请帮我解决这个问题。提前致谢。
【问题讨论】:
-
最近提出了一个可能有帮助的相关问题:stackoverflow.com/questions/22990023/…
标签: cakephp-2.4