CakeDC用户使用用户名登录

时间:2012-12-03 16:02:59

标签: cakephp authentication plugins cakedc

默认登录过程需要电子邮件,而不是用户名。

我已将此添加到AppController.php上的beforeFilter()CakePHP's Docs Authentication上也提到了这一点:

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

但不知何故,它不允许用户使用他们的用户名登录。关于如何改变它的任何想法?

AppController的

App::uses('Controller', 'Controller');
class AppController extends Controller {
var $components = array(
    'Session',
    'RequestHandler',
    'Security'
);
var $helpers = array('Form', 'Html', 'Session', 'Js');

public function beforeFilter() {
    $this->Auth->authorize = 'Controller';
    $this->Auth->fields = array('username' => 'username', 'password' => 'password');
    $this->Auth->loginAction = array('plugin' => 'users', 'controller' => 'users', 'action' => 'login', 'admin' => false);
    $this->Auth->loginRedirect = '/';
    $this->Auth->logoutRedirect = '/';
    $this->Auth->authError = __('Sorry, but you need to login to access this location.', true);
    $this->Auth->loginError = __('Invalid e-mail / password combination.  Please try again', true);
    $this->Auth->autoRedirect = true;
    $this->Auth->userModel = 'User';
    $this->Auth->userScope = array('User.active' => 1);  
    if ($this->Auth->user()) {
        $this->set('userData', $this->Auth->user());
        $this->set('isAuthorized', ($this->Auth->user('id') != ''));
    }
}

/View/Users/login.ctp

这与插件文件夹中的默认login.ctp相同。我刚刚将字段电子邮件更改为用户名。

现在,这里有一些有趣的东西。无论我放在这个文件中的代码,CakePHP从插件登录视图中提取内容,我创建的视图都会被忽略。

调试

调用调试器时:

Debugger::dump($this->Auth);

显示我设置的所有值。但它仍然不接受用户名。我仍然可以使用电子邮件登录,因此我并没有插入错误的凭据。只是它正在等待电子邮件/密码,而不是用户名/密码。

1 个答案:

答案 0 :(得分:3)

尝试在AppController中的$ components上配置它:

public $components = array(
    'Auth' => array(
        'authenticate' => array(
            'Form' => array(
                'fields' => array('username' => 'username')
            )
        )            
    )
}

我有相反的问题,我想用他们的邮件验证用户,而不是用户名,并使用上述配置'username'=> 'email'为我工作。

编辑:

public $components = array(
    'Acl',
    'Auth' => array(
        'authorize' => array(
            'Actions' => array('actionPath' => 'controllers')
        ),
        'authenticate' => array(
            'Form' => array(
                'fields' => array('username' => 'email')
            )
        )            
    ),
    'Session'
);

public function beforeFilter() {
    //User settings
    $this->activeUserId = $this->Auth->user;
    $this->set('activeuserphoto', $this->Auth->user('photo'));
    $this->set('activeusername', $this->Auth->user('username'));

    //Configure AuthComponent
    $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
    $this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');
    $this->Auth->loginRedirect = array('controller' => 'pages', 'action' => 'dashboard');
}