无法登录Cakephp 3应用程序

时间:2017-11-18 13:38:55

标签: php cakephp cakephp-3.0

我正在使用Cakephp 3中的登录和注册模块但是无法登录,而注册时密码也没有被哈希,它将保存为纯文本。我收到错误:用户名或密码无效,请重试。 我已经遵循了一些教程,但有些东西丢失了,导致应用程序无法正常登录。请帮助解决我的问题。

以下是完整的代码:

  

Login.ctp

<h1> Login </h1>
<p>Enter your username & password: </p>
<?php echo $this->Form->create();
    echo $this->Form->input('email');
    echo $this->Form->input('password');
    echo $this->Form->button('Login');

    echo $this->Form->end()
    ?>
  

AppController.ctp

<?php

namespace PanelAdmin\Controller;
use Cake\Event\Event;
use Cake\View\Helper\FlashHelper;
use Cake\Controller\Component\FlashComponent;
use App\Controller\AppController as BaseController;

class AppController extends BaseController
{

public function initialize()

    {

        parent::initialize();

        $this->loadComponent('RequestHandler');

        $this->loadComponent('Flash');

        $this->loadComponent('Auth', [

        'authorize'=> 'Controller',

        'authenticate' => [

            'Form' => [

                // fields used in login form

                'fields' => [

                    'username' => 'email',

                    'password' => 'password'

                ]

          ]

        ],

        // login Url

        'loginAction' => [

            'controller' => 'Users',

            'action' => 'login'

        ],

        // where to be redirected after logout 

        'logoutRedirect' => [

            'controller' => 'Topics',

            'action' => 'index'//,

            //'home'

        ],

        // if unauthorized user go to an unallowed action he will be redirected to this url

        'unauthorizedRedirect' => [

            'controller' => 'Topics',

            'action' => 'index'//,

            //'home'

        ],

        'authError' => 'Did you really think you are allowed to see that?',

        ]);

        // Allow the display action so our pages controller still works and  user can visit index and view actions.

        $this->Auth->allow(['index','display','view']);



    }





    public function isAuthorized($user)

    {

        $this->Flash->error('You aren\'t allowed');

        return false;

    }



    public function beforeFilter(Event $event)

    {

        $this->Auth->allow(['index', 'view', 'display']);

    }





public function beforeRender(Event $event)

    {

if (!array_key_exists('_serialize', $this->viewVars) &&

in_array($this->response->type(), ['application/json', 'application/xml'])

        ) {

            $this->set('_serialize', true);

        }

    }

}

?>
  

UsersController.ctp

<?php

namespace PanelAdmin\Controller;

use Cake\Controller\Controller;
use Cake\ORM\TableRegistry;
use Cake\Event\Event;


class UsersController extends AppController
       {



   public function initialize()

    {

        parent::initialize();

        $this->loadComponent('Flash'); // Include the FlashComponent

        // Auth component allow visitors to access add action to register  and access logout action

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



    }



    public function login()

    {

        if ($this->request->is('post')) {

            // Auth component identify if sent user data belongs to a user

            $user = $this->Auth->identify();

            if ($user) {

                //

                $this->Auth->setUser($user);

                return $this->redirect($this->Auth->redirectUrl());

            }

            $this->Flash->error(__('Invalid username or password, try again.'));

        }

    }



    public function logout(){

        $this->Flash->success('You successfully have loged out');

    return  $this->redirect($this->Auth->logout());

    }

    public function index()

    {

        $this->set('users',$this->Users->find('all'));    

    }

    public function view($id)

    {

        $user = $this->Users->get($id);

        $this->set('user',$user);



    }

    public function add()

    {

        $user = $this->Users->newEntity();

        if($this->request->is('post')) {

            $this->Users->patchEntity($user,$this->request->data);

            if($this->Users->save($user)){

            $this->Flash->success(__('Your account has been registered .'));

return $this->redirect(['action' => 'index']);

            }

            $this->Flash->error(__('Unable to register your account.'));

        }

        $this->set('user',$user);

    }

    public function edit($id)

    {

        $user = $this->Users->get($id);

        if ($this->request->is(['post', 'put'])) {

            $this->Users->patchEntity($user, $this->request->data);

            if ($this->Users->save($user)) {

                $this->Flash->success(__('Your profile data has been updated.'));

                return $this->redirect(['action' => 'index']);

            }

            $this->Flash->error(__('Unable to update your profile.'));

        }



        $this->set('user', $user);      



    }

    public function delete($id)

    {

        $this->request->allowMethod(['post', 'delete']);



        $user = $this->Users->get($id);

        if ($this->Users->delete($user)) {

            $this->Flash->success(__('The user with id: {0} has been deleted.', h($id)));

            return $this->redirect(['action' => 'index']);

        }      



    }  

}

?>
  

UsersTable.ctp

<?php
namespace App\Model\Table;

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

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'
        ]);
    }


}

?>
  

实体:User.php

<?php
namespace App\Model\Entity;

use Cake\ORM\Entity;
use Cake\Auth\DefaultPasswordHasher;

class User extends Entity 
{

  protected $accessible = [
       '*' => true,
       'id' => false, 
  ];


  protected function _setPassword($password) {
    if (strlen($password) > 0) {
            return (new DefaultPasswordHasher)->hash($password);
        }
  }

}

?>
  

add.ctp

<h1>Register new user </h1>

<?php

echo $this->Flash->render('auth');

echo $this->Form->create($user);

echo $this->Form->input('name');

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

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

echo $this->Form->input('password2',array('label'=>"confirm password",'type'=>'password'));

echo $this->Form->input('email');

echo $this->Form->input('phone');

echo $this->Form->input('birthdate',[

        'minYear' => date('Y') - 80,

        'maxYear' => date('Y') - 10

    ]);





echo $this->Form->button(__('Register'));

echo $this->Form->end();

?>

0 个答案:

没有答案