Почему $this-›Auth-›login() всегда возвращает false? (Торт PHP 2.x)

Я использую cakephp 2.6.7.

Внутри контроллера приложения:

   public $components = array(
        'Session',
        'Auth' => array(
            'authenticate' => array(
                'Form' => array(
                    'fields' => array(
                        'username' => 'email', //Default is 'username' in the userModel
                        'password' => 'password'  //Default is 'password' in the userModel
                    ),
                    'passwordHasher' => array(
                        'className' => 'Simple',
                        'hashType' => 'sha256'
                    )
                )
            )
        )
    );

Внутри ResellersController:

   public $components = array(
        'Session',
        'Auth' => array(
            'authenticate' => array(
                'Form' => array(
                    'userModel' => 'Reseller',
                    )
                ),
            'loginAction' => array(
                'controller' => 'resellers',
                'action' => 'login'
                ),
            'loginRedirect' => array('controller' => 'resellers', 'action' => 'profile'),
            'logoutRedirect' => array('controller' => 'resellers', 'action' => 'login'),
            'authError' => "You can't   acces that page",
            'authorize' => 'Controller'
            )
        );

  public function isAuthorized($user = null) {
        return true;
    }

function login() {
    $this->layout = 'public-login';
    $this->loadModel('Reseller');
        // if already logged in check this step
    if ($this->Auth->loggedIn()) {
            return $this->redirect('profile'); //(array('action' => 'deshboard'));
        }
        // after submit login form check this step
        if ($this->request->is('post')) {
            if ($this->Auth->login()) {
                return $this->redirect($this->Auth->redirectUrl());
            } else {
                $msg = '<div class="alert alert-error">
                <button type="button" class="close" data-dismiss="alert">×</button>
                <strong>Incorrect email/password combination. Try Again</strong>
            </div>';        
            $this->set(compact('msg'));
        }
    }
}

Внутри реселлеров/login.ctp:

  <?php
            echo $this->Form->create('Reseller', array(
                'inputDefaults' => array(
                    'label' => false,
                    'div' => false
                ),
                'class' => 'login-form',
                'url' => array('controller' => 'resellers', 'action' => 'login')
                    )
            );
            ?>

            <?php if(isset($msg)){
             echo $msg;
            } 
            ?>

            <h3 class="form-title">Login to your account</h3>
            <div class="alert alert-danger display-hide">
                <button class="close" data-close="alert"></button>
                <span>
                    Enter Email and password. </span>
            </div>
            <div class="form-group">
                <!--ie8, ie9 does not support html5 placeholder, so we just show field title for that-->
                <label class="control-label visible-ie8 visible-ie9">Email</label>
                <div class="input-icon">
                    <i class="fa fa-user"></i>

                    <?php
                    echo $this->Form->input(
                            'email', array(
                        'class' => 'form-control placeholder-no-fix',
                        'type' => 'text',
                        'autocomplete' => 'off',
                        'placeholder' => 'Email'
                            )
                    );
                    ?>
                </div>
            </div>
            <div class="form-group">
                <label class="control-label visible-ie8 visible-ie9">Password</label>
                <div class="input-icon">
                    <i class="fa fa-lock"></i>

                    <?php
                    echo $this->Form->input(
                            'password', array(
                        'class' => 'form-control placeholder-no-fix',
                        'type' => 'password',
                        'autocomplete' => 'off',
                        'placeholder' => 'Password'
                            )
                    );
                    ?>
                </div>
            </div>

            <div class="form-actions">
                <?php
                echo $this->Form->button(
                        'Login <i class="m-icon-swapright m-icon-white"></i>', array(
                    'class' => 'btn blue pull-right',
                    'type' => 'submit',
                    'escape' => false
                        )
                );
                ?> 

            </div>


            <div class="forget-password">
                <h4>Forgot your password ?</h4>
                <p>
                    no worries, click <a href="javascript:;" id="forget-password">
                        here </a>
                    to reset your password.
                </p>
            </div>
            <div class="create-account">
                <p>
                    Don&#39;t have an account yet ?&nbsp; <a style=" text-transform: none; font-size: 12px !important;" class="btn btn-circle blue" href="javascript:;" id="register-btn">
                        Create an account </a>
                </p>
            </div>
            <?php echo $this->Form->end(); ?>
            <!-- END LOGIN FORM -->

Внутри Model/Reseller.php:

<?php
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
class Reseller extends AppModel {

    var $name = "reseller";

    //  public $belongsTo = array(
    //     'Order' => array(
    //         'className' => 'Order',
    //         'foreignKey' => 'api_key'
    //     )
    // );

    public $validate = array(
        'email' => array(
            'rule' => 'isUnique',
            'required' => true,
            'message' => 'Email already exist'
        ),
        'password' => array(
            'rule' => array('minLength', '4'),
            'message' => 'password must be minimum 4 characters long'
        )
    );

    function hashPassword() {
     if (!empty($this->data[$this->alias]['password'])) {
            $passwordHasher = new SimplePasswordHasher(array('hashType' => 'sha256'));
            $this->data[$this->alias]['password'] = $passwordHasher->hash(
                $this->data[$this->alias]['password']
            );
        }
    }

    function beforeSave($options = array()) {
        $this->hashPassword();
        return true;
    }

}

?>

Я изучал свой код в течение двух дней. Но не выясняйте, почему он всегда возвращает false. Есть много вопросов, таких же, как у меня, я изучаю каждый, но не повезло. Любая помощь будет оценена. Спасибо


person Abdus Sattar Bhuiyan    schedule 05.12.2015    source источник
comment
Посмотрите здесь   -  person Pradeep Singh    schedule 05.12.2015


Ответы (1)


Вы переопределяете свой AuthComponent в свойстве in ResellersController:$components и не определяете поля аутентификации.

Ваше определение $components в ResellersController должно быть:

public $components = array(
    'Session',
    'Auth' => array(
        'authenticate' => array(
            'Form' => array(
                'userModel' => 'Reseller',
                'fields' => array(
                    'username' => 'email', 
                    'password' => 'password'  
                ),
                'passwordHasher' => array(
                    'className' => 'Simple',
                    'hashType' => 'sha256'
                ),
            )
        ),
        'loginAction' => array(
            'controller' => 'resellers',
            'action' => 'login'
        ),
        'loginRedirect' => array('controller' => 'resellers', 'action' => 'profile'),
        'logoutRedirect' => array('controller' => 'resellers', 'action' => 'login'),
        'authError' => "You can't acces that page",
        'authorize' => 'Controller'
    )
);   

Если вы не ожидаете, что ваши торговые посредники будут просто использовать действия, предусмотренные в ResellersController, вам следует объединить аутентификацию с аутентификацией в AppController.


Я заметил, что вы не мигаете ошибками аутентификации. Попробуйте включить в свое представление следующее:

<?php echo $this->Session->flash('auth'); ?>
person Inigo Flores    schedule 05.12.2015
comment
Спасибо за ваше время. Здесь я уже определяю «Поля аутентификации» в appController. Так в чем проблема? - person Abdus Sattar Bhuiyan; 05.12.2015
comment
ResellerController расширяет AppController. Хотя CakePHP пытается объединить оба определения $components, я не уверен, что свойства внутри ассоциативных массивов также объединены. - person Inigo Flores; 05.12.2015