Cakephp 3.0 Войти

У меня проблемы с моей системой входа. Мне удалось зарегистрировать своего пользователя в моей базе данных, но всякий раз, когда я пытаюсь войти в систему, он продолжает предлагать «Неверный адрес электронной почты или пароль, попробуйте еще раз».

Это моя модель:

    <?php
    namespace App\Model\Table;

    use Cake\ORM\Table;
    use Cake\Validation\Validator;

    class UsersTable extends Table
    { 

    public function validationDefault(Validator $validator)
    {
    return $validator
        ->notEmpty('email', 'A email is required')
        ->add('email', 'valid' , ['rule'=> 'email'])
        ->add('email', [
            'unique' => ['rule' => 'validateUnique', 'provider' => 'table']
        ])
        ->requirePresence('email','create')

        ->notEmpty('password', 'A password is required')
        ->notEmpty('role', 'A role is required')
        ->add('role', 'inList', [
            'rule' => ['inList', ['admin', 'author']],
            'message' => 'Please enter a valid role'
        ]);
        } 

        }

Мой контроллер:

       <?php
       namespace App\Controller;

       use App\Controller\AppController;
       use Cake\Event\Event;
       use Cake\Network\Exception\NotFoundException;

       class UsersController extends AppController
       {

       public function beforeFilter(Event $event)
       {
       parent::beforeFilter($event);

    $this->Auth->allow(['add', 'logout']);
   }

    public function login()
   {
    if ($this->request->is('post')) {
    $user = $this->Auth->identify();
    if ($user) {
        $this->Auth->setUser($user);
        return $this->redirect($this->Auth->redirectUrl());
    }
    $this->Flash->error(__('Invalid email or password, try again'));
  }
  }

  public function logout()
  {
  return $this->redirect($this->Auth->logout());
  }

 public function index()
 {
    $this->set('users', $this->Users->find('all'));
}

public function view($id)
{
    if (!$id) {
        throw new NotFoundException(__('Invalid user'));
    }

    $user = $this->Users->get($id);
    $this->set(compact('user'));
}

public function add()
{
    $user = $this->Users->newEntity();
    if ($this->request->is('post')) {
        $user = $this->Users->patchEntity($user, $this->request->data);
        if ($this->Users->save($user)) {
            $this->Flash->success(__('The user has been saved.'));
            return $this->redirect(['action' => 'add']);
        }
        $this->Flash->error(__('Email already existed.'));
    }
    $this->set('user', $user);
   } 

    }

Контроллер приложений:

    <?php

    namespace App\Controller;

    use Cake\Controller\Controller;
    use Cake\Event\Event;


   class AppController extends Controller
   {


  public function initialize()
  {
     $this->loadComponent('Flash');
    $this->loadComponent('Auth', [
        'authorize' => ['Controller'],  
        'loginRedirect' => [
            'controller' => 'Articles',
            'action' => 'index'
        ],
        'logoutRedirect' => [
            'controller' => 'Pages',
            'action' => 'display',
            'home'
        ]
    ]);
  }

  public function isAuthorized($user)
{

if (isset($user['role']) && $user['role'] === 'admin') {
    return true;
}


return false;
  }

public function beforeFilter(Event $event)
{
    $this->Auth->allow(['index', 'view', 'display']);
}

 } 

логин.ctp

 <div class="users form">
 <?= $this->Flash->render('auth') ?>
<?= $this->Form->create() ?>
<fieldset>
    <legend><?= __('Please enter your username and password') ?></legend>
    <?= $this->Form->input('email') ?>
    <?= $this->Form->input('password') ?>
</fieldset>
<?= $this->Form->button(__('Login')); ?>
 <?= $this->Form->end() ?>
</div>  

person Yuk Ching    schedule 10.04.2015    source источник
comment
Вы хэшируете свои пароли? См. раздел Add Password Hashing по этой ссылке book.cakephp.org/ 3.0/ru/учебники и примеры/закладки/   -  person AKKAweb    schedule 10.04.2015


Ответы (2)


Я думаю, что проблема исходит от AppController


Взгляните на это: Пример части закладки CookBook CakePHP 3.0 1

Часть логин находится здесь: Пример закладки CookBook CakePHP 3.0, часть 2

Найдите сходство с вашим проектом, попытайтесь провести аналогию, отношение.

person James    schedule 10.04.2015

Спасибо, парни! Удалось найти ответ после обращения к учебникам. Оказывается, я пропускаю

        'authenticate' => [
        'Form' => [
        'fields' => [
        'username' => 'email',
        'password' => 'password'

Теперь все хорошо! Привет =)

person Yuk Ching    schedule 10.04.2015