1

有些人可能会觉得这个问题很愚蠢。但我真的完成了所有的谷歌搜索,阅读了 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 新手

4

1 回答 1

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;
    }
?>

你完成了。

于 2013-01-23T06:33:17.900 回答