CakePHP 2.1 Auth-> login()不工作,但添加用户 [英] CakePHP 2.1 Auth->login() not working, but adding user does

查看:113
本文介绍了CakePHP 2.1 Auth-> login()不工作,但添加用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索过stackoverflow上的许多帖子的答案,也许我只是忽略的东西,但我似乎不能得到$ this-> Auth-> login()工作。我试过许多不同的建议从其他职位。在描述我尝试过的其他方法时,我将尽可能详细。



我添加了一个用户工作。 MD5散列正常工作。我散了密码,然后使用奇迹沙拉md5 http://www.miraclesalad.com/webtools /md5.php



我不使用盐来进行哈希。我使用MD5没有盐。



我使用的数据库是Postgresql 9.0。我知道一些CakePhp魔法不适用于所有的数据库(或者我已经被告知)。



app / Config / core.php



 配置:: write('Security.level','medium'); 

/ **
*在安全哈希方法中使用的随机字符串。
* /

配置:: write('Security.salt','');

我使用Auth->字段将密码映射到user_password,将用户名映射到DB中的user_name。 user_password和user_name是core_users表中的列。我也有在beforeFilter()方法。

  $ this-> Auth-> fields = array =>'user_name','password'=>'user_password'); 



app / Controller / AppController.php



 类AppController extends Controller {
public $ components = array(
'Session',
'Auth'=&数组(
'loginRedirect'=> array('controller'=>'pages','action'=>'index'),
'logoutRedirect'=& =>'pages','action'=>'display','home'),
'loginAction'=> array('admin'=> false,'controller'=> 'user','username'=>'user_name'),* /','''','action'=>'login'),
/ *'fields'=&
'userModel'=>'CoreUser'

);

public function beforeFilter(){
Security :: setHash('md5');
$ this-> Auth-> allow('login');
// debug($ this-> Auth);
}
}

我离开调试,



app / Controller / CoreUsersController.php



  public function login(){
Security :: setHash('md5');
// debug($ this-> Auth);

if($ this-> request-> is('post')){
debug(Security :: hash($ this-> Auth-> request-> ; data ['CoreUser'] ['user_password']));
debug($ this-> Auth);
debug(Configure :: version());
debug($ this-> Auth-> request-> data ['CoreUser'] ['user_password']);
debug($ this-> Auth-> request-> data ['CoreUser'] ['user_name']);
if($ this-> Auth-> login()){
debug($ this-> Auth-> request-> data ['CoreUser'] ['user_password'] );
$ this-> redirect($ this-> Auth-> redirect());

} else {
debug($ this-> Auth-> request-> data ['CoreUser'] ['user_password']);
$ this-> Session-> setFlash(__('Invalid username or password,try again'));
}
}
}
public function logout(){
$ this-> redirect($ this-> Auth-> logout());
}



app / Model / CoreUser.php h3>

  App :: uses('AuthComponent','Controller / Component'); 
class CoreUser extends AppModel {
public $ primaryKey ='user_id';
public $ sequence ='core_user_id_seq';
public $ name ='CoreUser';
public $ validate = array(
'user_name'=> array(
'required'=> array(
'rule'=> array('notEmpty') ,
'message'=>'用户名是必需的'

),
'user_password'=&数组(
'rule'=> array('notEmpty'),
'message'=>'需要密码'

' privilege_id'=> array(
'required'=> array(
'rule'=> array('notEmpty'),
'message'=> required'
),
'legalValues'=> array(
'rule'=> array('between',1,4),
'message'=> ;'Privilege必须在1和4之间'

),
'user_initial'=> array(
'required'=& rule'=> array('notEmpty'),
'message'=>'用户首字母是必需的'

),
'email'=>数组(
'rule'=> array('email',true),
'message'=>'电子邮件必须有一个\'@ \' '

);

public function beforeSave(){
Security :: setHash('md5');
if(isset($ this-> data [$ this-> alias] ['user_password'])){
$ this-> data [$ this-& user_password'] = AuthComponent :: password($ this-> data [$ this-> alias] ['user_password']);
}
return true;
}
}



app / View / CoreUsers / login。 ctp



 < h3>登录< / h3& 

< div class =users form>
<?php echo $ this-> Session-> flash('auth'); ?>
<?php echo $ this-> Form-> create('CoreUser');?
< fieldset>
< legend><?php echo __('请输入您的用户名和密码'); ?>< / legend>
<?php
echo $ this-> Form-> input('user_name');
echo $ this-> Form-> input('user_password');
?>
< / fieldset>
<?php echo $ this-> Form-> end(__('Login'));?
< / div>



调试输出



所有这些都来自CoreUsersController,并按顺序处理它们。



已隐藏的密码。



 '098f6bcd4621d373cade4e832627b4f6'
code>



Auth对象



  object(AuthComponent){
components => array(
(int)0 =>'Session',
(int)1 =>'RequestHandler'

authenticate => array(
(int)0 =>'Form'

authorize => false
ajaxLogin => null
flash => array(
'element'=>'default',
'key'=>'auth',
'params'=& $ b loginAction => array(
'admin'=> false,
'controller'=>'CoreUsers',
'action'=>'login'

loginRedirect => array(
'controller'=>'pages',
'action'=>'index'

logoutRedirect => array(
'controller'=>'pages',
'action'=>'display',
(int)0 =>'home'

authError => 您无权访问该位置。
allowedActions => array(
(int)0 =>'login'

request => object(CakeRequest){
params => array(
'plugin'=> null,
'controller'=>'CoreUsers',
'action'=>'login',
'named' > array(),
'pass'=> array()

data => array(
'CoreUser'=> array(
'user_name'=>'testy5',
'user_password'=>'test'


query => array()
url => 'CoreUsers / login'
base => '/ cpm_v2_dev'
webroot => '/ cpm_v2_dev /'
here => '/ cpm_v2_dev / CoreUsers / login'
}
response => object(CakeResponse){

}
settings => array(
'loginRedirect'=> array(
'controller'=>'pages',
'action'=>'index'
),
'logoutRedirect'=> array(
'controller'=>'pages',
'action'=>'display',
(int)0 = '
),
'loginAction'=> array(
'admin'=> false,
'controller'=>'CoreUsers',
' action'=>'login'
),
'userModel'=>'CoreUser'

userModel => 'CoreUser'
}



CakePHP版本



 '2.1.0'



login()



 'test'

登录前的用户名()



 'testy5'



登录后调用密码



 code>'test'

这里是我读过的东西的快速列表其他stackoverflow的帖子,我试过。让我知道如果你需要我详细说明。



1)我将用户名和密码映射到DB中的字段。这是评论的领域。我也试着在beforeFilter()方法。使用:

  $ this-> Auth-> fields = array('username'=>'user_name' password'=>'user_password'); 

在登录视图中,表单是这样创建的:

  $ this-> Form-> input('username'); 
$ this-> Form-> input('password');

2)我在登录前尝试手动哈希密码:

  $ this-> Auth-> request-> data ['CoreUser'] ['password'] = Security :: hash($ this-> ; Auth-> request-> data ['CoreUser'] ['password'])
if($ this-> Auth-> login()){
$ this-> redirect($ this-> Auth-> redirect());
}



EDIT0



3)我刚刚尝试这样做 CakePHP 2.0 Auth登录不工作

a>



我的AuthComponent现在看起来像这样:

  public $ components = array(
'Session',
'Auth'=> array(
'authenticate'=> array(
'Form'=& $ b'userModel'=>'CoreUser',
'fields'=> array(
'username'=>'user_name',
'password'=>'user_password '


),
'loginRedirect'=> array('controller'=>'pages','action'=>'index'
'logoutRedirect'=> array('controller'=>'pages','action'=>'display','home'),
'loginAction'=& admin'=> false,'controller'=> 'CoreUsers','action'=> 'login')

);

如果我没有详细说明,或者我犯了一个错误,我道歉。我一直在这工作了几天,它真的耗尽了我。我欣赏任何可能会收到的帮助。谢谢!

解决方案

我最后为解决这个问题做了下面的教程,正如CakePHP。我也升级到2.1.2。我正在运行2.1.0。



http://book.cakephp.org/2.0/en/tutorials-and-examples/blog-auth-example/auth.html



然后我慢慢添加我需要的配置。有关我引用的Auth组件的信息:



http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html



真的,我的问题是很差的故障排除。我会做一堆更改,而不是一次一个。我有我的login.ctp视图两种不同的方式

  $ this-> Form-> input('username'); 
$ this-> Form-> input('password');

,现在如下所示:

  echo $ this-> Form-> input('user_name'); 
echo $ this-> Form-> Label('Password');
echo $ this-> Form-> password('user_password');

第二个版本适用。



EDIT0 :
这是非常重要的。没有对AppController父项的调用,登录将不起作用。

  class CoreUsersController extends AppController {
public $ helpers = array('Html','Form');

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

Auth组件的修订版本:

  public $ components = array(
'Session',
'Auth'=> array(
'authenticate'= & array(
'Form'=> array(
'userModel'=>'CoreUser',
'fields'=& >'user_name',
'password'=>'user_password'


),
'loginRedirect'=& ='page','action'=>'index'),
'logoutRedirect'=> 'home'),
'loginAction'=> array('admin'=> false,'controller'=>'CoreUsers','action'=>'login')

);

我的盐仍然是一个空字符串:

 配置:: write('Security.salt',''); 

设置md5哈希只需要在一个地方。在模型中的beforeSave()中不需要它:

  public function beforeFilter(){
Security :: setHash 'md5');
$ this-> Auth-> allow('login','add');
}

beforeSave():

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


I've searched through many posts on stackoverflow for an answer, and prehaps I'm just overlooking something, but I can't seem to get $this->Auth->login() to work. I've tried many different suggestions from other posts. I will try to be as thorough as possible when describing other methods I've tried.

I do have adding a user working. The MD5 hashing is working correctly. I hashed a password and then checked it using miracle salad md5 http://www.miraclesalad.com/webtools/md5.php

I do not use a salt for hashing. I use MD5 without a salt.

The database I'm using is Postgresql 9.0. I know some of the CakePhp magic doesn't work for all databases (or so I've been told).

app/Config/core.php

Configure::write('Security.level', 'medium');

/**
* A random string used in security hashing methods.
*/

    Configure::write('Security.salt', '');

I was using Auth->fields to map password to user_password and username to user_name in the DB. user_password and user_name are the columns in the core_users table. I also had in the beforeFilter() method.

$this->Auth->fields = array('username' => 'user_name', 'password' => 'user_password');

app/Controller/AppController.php

class AppController extends Controller {
public $components = array(
    'Session',
    'Auth' => array(
        'loginRedirect' => array('controller' => 'pages', 'action' => 'index'),
        'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'home'),
        'loginAction' => array('admin' => false, 'controller' => 'CoreUsers', 'action' => 'login'),
        /*'fields' => array('password' => 'user_password', 'username' => 'user_name'),*/
        'userModel' => 'CoreUser'
    )
);

public function beforeFilter() {
    Security::setHash('md5');
    $this->Auth->allow('login');
    //debug($this->Auth);
} 
}

I left the debugs in so you can see the order that they are processed and I will show you how they are printed.

app/Controller/CoreUsersController.php

    public function login() {
    Security::setHash('md5');
    //debug($this->Auth);

    if ($this->request->is('post')) {
        debug(Security::hash($this->Auth->request->data['CoreUser']['user_password']));
        debug($this->Auth);
        debug(Configure::version());
        debug($this->Auth->request->data['CoreUser']['user_password']);
        debug($this->Auth->request->data['CoreUser']['user_name']);
        if ($this->Auth->login()) {
            debug($this->Auth->request->data['CoreUser']['user_password']);
            $this->redirect($this->Auth->redirect());

        } else {
            debug($this->Auth->request->data['CoreUser']['user_password']);
            $this->Session->setFlash(__('Invalid username or password, try again'));
        }
    }
}
public function logout() {
    $this->redirect($this->Auth->logout());
}

app/Model/CoreUser.php

 App::uses('AuthComponent', 'Controller/Component');
class CoreUser extends AppModel{
public $primaryKey = 'user_id';
public $sequence = 'core_user_id_seq';
public $name = 'CoreUser';
public $validate = array(
    'user_name' => array(
        'required' => array(
            'rule' => array('notEmpty'),
            'message' => 'User name is required'
        )
    ),
    'user_password' => array(
        'required' => array(
            'rule' => array('notEmpty'),
            'message' => 'Password is required'
        )
    ),
    'privilege_id' => array(
        'required' => array(
            'rule' => array('notEmpty'),
            'message' => 'Privilege ID is required'
        ),
        'legalValues' => array(
             'rule' => array('between',1,4),
            'message' => 'Privilege must be between 1 and 4'
        )
    ),
    'user_initial' => array(
        'required' => array(
            'rule' => array('notEmpty'),
            'message' => 'User initials is required'
        )
    ),
    'email' => array(
        'rule' => array('email',true),
        'message' => 'Email must have an \'@\' symbol and a domain e.g. .com' 
    )
);

public function beforeSave() {
    Security::setHash('md5');
    if (isset($this->data[$this->alias]['user_password'])) {
        $this->data[$this->alias]['user_password'] = AuthComponent::password($this->data[$this->alias]['user_password']);
    }
    return true;
}
}

app/View/CoreUsers/login.ctp

<h3>Login</h3>

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

Debug output

All of these are from the CoreUsersController and going in order in which they are processed.

Hashed password. This is the same as what is in the DB, when I added the user.

'098f6bcd4621d373cade4e832627b4f6'

The Auth object

object(AuthComponent) {
components => array(
    (int) 0 => 'Session',
    (int) 1 => 'RequestHandler'
)
authenticate => array(
    (int) 0 => 'Form'
)
authorize => false
ajaxLogin => null
flash => array(
    'element' => 'default',
    'key' => 'auth',
    'params' => array()
)
loginAction => array(
    'admin' => false,
    'controller' => 'CoreUsers',
    'action' => 'login'
)
loginRedirect => array(
    'controller' => 'pages',
    'action' => 'index'
)
logoutRedirect => array(
    'controller' => 'pages',
    'action' => 'display',
    (int) 0 => 'home'
)
authError => 'You are not authorized to access that location.'
allowedActions => array(
    (int) 0 => 'login'
)
request => object(CakeRequest) {
    params => array(
        'plugin' => null,
        'controller' => 'CoreUsers',
        'action' => 'login',
        'named' => array(),
        'pass' => array()
    )
    data => array(
        'CoreUser' => array(
            'user_name' => 'testy5',
            'user_password' => 'test'
        )
    )
    query => array()
    url => 'CoreUsers/login'
    base => '/cpm_v2_dev'
    webroot => '/cpm_v2_dev/'
    here => '/cpm_v2_dev/CoreUsers/login'
}
response => object(CakeResponse) {

}
settings => array(
    'loginRedirect' => array(
        'controller' => 'pages',
        'action' => 'index'
    ),
    'logoutRedirect' => array(
        'controller' => 'pages',
        'action' => 'display',
        (int) 0 => 'home'
    ),
    'loginAction' => array(
        'admin' => false,
        'controller' => 'CoreUsers',
        'action' => 'login'
    ),
    'userModel' => 'CoreUser'
)
userModel => 'CoreUser'
  }

Version of CakePHP

'2.1.0'

Password before login() is called

'test'

Username before login() is called

 'testy5'

Password after login() is called

 'test'

Here is a quick list of things that I've read in other stackoverflow post that I've tried. Let me know if you need to me to elaborate.

1) I mapped username and password to the fields in the DB. It's where the comments are for fields. I also tried doing it in the beforeFilter() method. Using:

$this->Auth->fields = array('username' => 'user_name', 'password' => 'user_password');

In the login view the form was created as such:

$this->Form->input('username');
$this->Form->input('password');

2) I tried hashing the password manually before login like so:

 $this->Auth->request->data['CoreUser']['password'] = Security::hash($this->Auth->request->data['CoreUser']['password'])
   if ($this->Auth->login()) {
            $this->redirect($this->Auth->redirect());
   }

EDIT0

3) I just tried doing this as recommended by CakePHP 2.0 Auth Login not working

My AuthComponent now looks like this:

     public $components = array(
    'Session',
    'Auth' => array(
        'authenticate' => array(
            'Form' => array(
                'userModel' => 'CoreUser',
                'fields' => array(
                    'username' => 'user_name',
                    'password' => 'user_password'
                )
            )
        ),
        'loginRedirect' => array('controller' => 'pages', 'action' => 'index'),
        'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'home'),
        'loginAction' => array('admin' => false, 'controller' => 'CoreUsers', 'action' => 'login')
    )
);

I apologize if I didn't elaborate enough, or I made a mistake. I've been working on this for a couple of days and it has really drained me. I appreciate any help I may receive. Thanks!

解决方案

What I ended up doing to solve this issue was following the tutorial exactly as CakePHP has it. I also upgraded to 2.1.2. I was running 2.1.0.

http://book.cakephp.org/2.0/en/tutorials-and-examples/blog-auth-example/auth.html

Then I slowly added the configurations I needed. For information about the Auth component I referenced:

http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html

Really what my problem was poor troubleshooting. I would make a bunch of changes rather than one at a time. I had my login.ctp view two different ways

 $this->Form->input('username');
 $this->Form->input('password');

and now it looks like this:

 echo $this->Form->input('user_name');
 echo $this->Form->Label('Password');
 echo $this->Form->password('user_password');

The second version works.

EDIT0: This is very important. Without a call to the AppController parent the login will not work.

class CoreUsersController extends AppController{
    public $helpers = array('Html','Form');

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

The revision for the Auth component works:

public $components = array(
    'Session',
    'Auth' => array(
        'authenticate' => array(
            'Form' => array(
                'userModel' => 'CoreUser',
                'fields' => array(
                    'username' => 'user_name',
                    'password' => 'user_password'
                )
            )
        ),
        'loginRedirect' => array('controller' => 'pages', 'action' => 'index'),
        'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'home'),
        'loginAction' => array('admin' => false, 'controller' => 'CoreUsers', 'action' => 'login')
    )
);

My salt is still an empty string:

Configure::write('Security.salt', '');

Setting the md5 hash is only needed in one place. It's not needed in beforeSave() in the model:

public function beforeFilter() {
    Security::setHash('md5');
    $this->Auth->allow('login','add');  
} 

beforeSave():

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

这篇关于CakePHP 2.1 Auth-&gt; login()不工作,但添加用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆