cakephp中的用户身份验证

时间:2013-01-23 06:24:06

标签: php cakephp

有些人可能会觉得这个问题很愚蠢。但我真的已经完成了所有的谷歌搜索,阅读cakephp文档,但仍然无法理解cakephp的身份验证机制。我已经尝试了一些代码,但仍然无法进行身份验证....

我的错误是每个正确的条目我收到错误作为无效的用户名密码。 这是我的代码

//login.tpl

<div class="users form">
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('User'); ?>
<fieldset>
    <legend><?php echo __('Please enter your username and password'); ?></legend>
    <?php echo $this->Form->input('username');
    echo $this->Form->input('password');
?>
</fieldset>
<?php echo $this->Form->end(__('Login')); ?>
</div>

//控制器文件

public function login() {
if ($this->request->is('post')) {
    if ($this->Auth->login()) {
        $this->redirect($this->Auth->redirect());
    } else {
        $this->Session->setFlash(__('Invalid username or password, try again'));
    }
}
}

任何人都可以告诉我如何进行身份验证,我是cakephp的新手

1 个答案:

答案 0 :(得分:1)

好的cakephp处理身份验证本身你不需要在login函数内编写代码。

<强> app_controller.php

<?php
class AppController extends Controller
{
    var $components = array
    (
        'Auth',
        'Session',
        'RequestHandler',
        'Email'
    );

    var $helpers    = array
    (
        'Javascript',
        'Form',
        'Html',
        'Session'
    );

    function beforeFilter()
    {
        $this->Auth->autoRedirect = true;

        $this->Auth->authError = 'Sorry, you are not authorized to view that page.';
        $this->Auth->loginError = 'invalid username and password combination.';

        $this->Auth->loginAction = array
        (
            'controller' => 'users',
            'action' => 'login',
            'admin' => true
        );

        $this->Auth->logoutRedirect = array
        (
            'controller' => 'users',
            'action' => 'logout',
            'admin' => true
        );

        $this->Auth->loginRedirect = array
        (
            'controller' => 'users',
            'action' => 'dashboard',
            'admin' => true
        );

        $this->Auth->fields = array('username' => 'email', 'password' => 'password');
    }
?>

<强> users_controller.php中

<?php
class UsersController extends AppController
{
    var $name = 'Users';

    /*
        do not forget to add beforeFilter function and inside this function call parent beforeFilter function.
    */

    function beforeFilter()
    {
        parent::beforeFilter();
    }

    function admin_login()
    {

    }

    function admin_logout()
    {
        $this->Session->destroy();
        $this->Auth->logout();
        $this->Session->setFlash(__('Yor are now Logged out Successfully', true), 'default',array('class'=>'alert alert-success'));
        $this->redirect('/');
        exit;
    }
?>

你已经完成了。