0

我遵循了 CakePHP 的基本身份验证教程。如果我添加一个用户,我不能用他登录。带有输入的视图应该没问题。 背景用户 HASANDBELONGSTOMANY带有连接表的播客。


控制器/用户控制器.php

public function add() {
    if ($this->request->is('post')) {
        $this->User->create();
        if ($this->User->saveAssociated($this->request->data)) { //saveAssociatied() is described below
            $this->redirect(array('action' => 'index'));
        }

    }
    $podcasts = $this->User->Podcast->find('list');
    $this->set(compact('podcasts'));
}

public function login() {
    if ($this->request->is('post')) {
        if ($this->Auth->login()) {
            $this->redirect($this->Auth->redirect());
        }
    }
}

模型/用户.php

public $hasAndBelongsToMany = array(
    'Podcast' => array(
        'className' => 'Podcast',
        'joinTable' => 'podcasts_users',
        'foreignKey' => 'user_id',
        'associationForeignKey' => 'podcast_id',
        'unique' => false,
    )
);

//password encryption
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;
}

AppModel.php根据this

class AppModel extends Model {
public function saveAssociated($data = null, $options = array()) {
    foreach ($data as $alias => $modelData) {
        if (!empty($this->hasAndBelongsToMany[$alias])) {
            $habtm = array();
            $Model = ClassRegistry::init($this->hasAndBelongsToMany[$alias]['className']);
            foreach ($modelData as $modelDatum) {
                if (empty($modelDatum['id'])) {
                    $Model->create();
                }
                $Model->save($modelDatum);
                $habtm[] = empty($modelDatum['id']) ? $Model->getInsertID() : $modelDatum['id'];                    
            }
            $data[$alias] = array($alias => $habtm);
        }
    }
    return parent::saveAssociated($data, $options);
  }
}
4

1 回答 1

0

解决方案:我想通过电子邮件进行身份验证,我必须根据这个答案声明。

所以我的 AppController.php 看起来像这样:

public $components = array(
        'Session',
        'Auth' => array(
            'authenticate' => array(
                'Form' => array(
                    'fields' => array('username' => 'email')
                )
            ),
            'loginRedirect' => array('controller' => 'xxx', 'action' => 'index'),
            'logoutRedirect' => array('controller' => 'users', 'action' => 'login')
        )
    );
于 2013-06-21T15:05:49.167 回答