Cakephp 2.0 $this->Auth->login() 不工作

Posted

技术标签:

【中文标题】Cakephp 2.0 $this->Auth->login() 不工作【英文标题】:Cakephp 2.0 $this->Auth->login() not working 【发布时间】:2013-01-15 12:21:50 【问题描述】:

我正在尝试使用 Auth 中内置的 cakephp 进行用户登录。我已成功验证用户注册(与登录名位于同一视图中),但未使登录正常工作。

我在尝试登录时得到的只是“用户名或密码无效,请重试”错误。我已经阅读了博客教程,但我是 cake/php 新手,并且只在 1.3 中处理过自己的粗略身份验证的混乱项目。

MarshallsController.php

class MarshalsController extends AppController 
public $helpers     = array('html', 'Form');
public $uses        = array("Marshal", "User");
public $components  = array("RequestHandler","Session", "Auth");

public function beforeFilter() 
    parent::beforeFilter();
    $this->Auth->allow('register', 'login');


public function index() 
    $this->set('users', $this->User->find('all',
            array(
                'conditions'=>array(
                    'User.marshall_id'=>$Marshall['Marshall']['id']
                )
            )));


//Run when Marshal attempts to register for login page
public function register()
    if ($this->request->is('post')) 
        $this->Marshal->create();
        if ($this->Marshal->save($this->request->data)) 
            //if new marshall has been saved fetch all their data
            $marshal = $this->Marshal->find('first',
                array(
                    'conditions'=>array(
                        "Marshal.email"     => $this->data['Marshal']['email'],
                    )
                )
            );
            if(!empty($marshal))
                //set marshal session data to track logged in users and their data
                $this->Session->write("Marshal",$marshal);
            
            $this->Session->setFlash(__('The Marshal has been saved'));
            //redirect user to logged in page
            $this->redirect(array('controller' => 'pages', 'action' => 'home'));
         else 
            $this->Session->setFlash(__('The Marshal could not be saved. Please, try again.'));
            echo $this->render('login');
            exit();
        
    
    else
        //if Marshal has not attempted to login redirect the back to the login/register page
        echo $this->render('login');
        exit();
    



public function login() 

    //if user has atempted a login
    if ($this->request->is('post')) 
        if ($this->Auth->login()) 
            //If login detials are correct get user data
            $marshal = $this->Marshal->find('first',
                array(
                    'conditions'=>array(
                        "Marshal.email"     => $this->data['Marshal']['email'],
                    )
                )
            );
            if(!empty($marshal))
                //set marshal session data to track logged in users and their data
                $this->Session->write("Marshal",$marshal);
            
            //redirect user to the logged in page
            $this->redirect($this->Auth->redirect());
         else 
            $this->Session->setFlash(__('Invalid username or password, try again'));
            debug($this->Auth->request->data);
        

元帅模型

class Marshal extends AppModel 

public function beforeSave($options = array()) 
    if (isset($this->data[$this->alias]['password'])) 
        $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
    
    return true;


public $hasMany = array(
    'User' => array(
        'className'     => 'User',
        'foreignKey'    => 'marshal_id',
        'conditions'    => array('User.status' => '1'),
    )
);

public $validate = array(
    'first_name' => array(
        'required' => array(
            'rule' => array('notEmpty'),
            'message' => 'A first name is required'
        )
    ),
    'last_name' => array(
        'required' => array(
            'rule' => array('notempty'),
            'message' => 'A last name is required'
        )
    ),
    'password' => array(
        'required' => array(
            'rule'    => array('minLength', '8'),
            'message' => 'Minimum 8 characters long'
        )
    ),
    'email' => 'email'
);

login.ctp

<div class="row">
<?php echo $this->Session->flash('auth'); ?>
<div class="sixcol">
    <?php
    echo $this->Form->create('Marshal', array('action' => 'login'));
    echo $this->Form->inputs(array(
        'legend' => __('Login'),
        'email',
        'password'
    ));
    echo $this->Form->end('Login');
    ?>
</div>
<div class="sixcol last">
    <?php
    echo $this->Form->create('Marshal', array('action' => 'register'));
    echo $this->Form->inputs(array(
        'legend' => __('register'),
        'first_name',
        'last_name',
        'email',
        'password'
    ));
    echo $this->Form->end('Register');
    ?>
</div>

【问题讨论】:

【参考方案1】:

默认情况下,CakePHP 使用用户名和密码字段,但您使用电子邮件而不是用户名。您需要指定它:

public $components = array(
            'Auth' => array('authenticate' => array('Form' => array( 'userModel' => 'User',
                                    'fields' => array(
                                                        'username' => 'email',
                                                        'password' => 'password'
                                                        )
                                                )
                            ),
                    'authorize' => array('Controller'),
                    'loginAction' => array('controller' => 'users', 'action' => 'login'),
                    'loginRedirect' => array('controller' => 'home', 'action' => 'index'),
                    'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
                    'authError' => 'You don\'t have access here.',
            ),
        );

这是我的工作示例,请随时根据您的需要进行更改。

【讨论】:

同样,默认情况下 Auth 使用 User 模型,但您使用的是 Marshall 模型并且没有相应地指定 userModel 选项。 我知道它默认为用户模型,但在文档中找不到如何更改它。我已经设法获得登录和设置会话数据,谢谢你的例子:)【参考方案2】:

您也可以检查安全哈希方法并与数据库中的密码进行比较:

Security::setHash('sha1');

(sha1 或 md5)

比较密码:

 Security::hash($password,"sha1", true);

【讨论】:

【参考方案3】:

函数登录()

//if already logged-in, redirect
// if($this->Session->check('email'))
//     $this->redirect(array('action' => ''));        
// 

// if we get the post information, try to authenticate
if ($this->request->is('post')) 
    $data = $this->request->data;


    print_r($data); die;
    if ($this->Auth->login()) 
        return $this->redirect($this->Auth->redirectUrl());
    
    $this->Session->setFlash(__('Your username or password was incorrect.'));

 

只有其他代码为真

【讨论】:

以上是关于Cakephp 2.0 $this->Auth->login() 不工作的主要内容,如果未能解决你的问题,请参考以下文章

CakePHP 2.0 确定点击了哪个提交按钮

Cakephp 验证更新实体上的数据

CakePHP 2.0 添加相关数据失败,缺少数据库表

CakePHP 2.0 无法保存

CakePHP重定向方法不起作用?

尝试使用 cakephp 2.0 保存表单数组数据