使用Cakephp中的插件验证Auth组件重定向问题

时间:2017-11-20 11:57:53

标签: php cakephp cakephp-3.0

如果未经授权访问编辑操作,我将使用auth组件而不是http://localhost/project_name/PanelAdmin/users/login?redirect=%2FPanelAdmin%2Fusers%2Fedit重定向到此网址http://localhost/project_name/PanelAdmin/users/login。我得到的页面是正确的登录页面,但我想将网址更改为此类http://localhost/project_name/PanelAdmin/users/login

  

AppController.php

<?php

namespace PanelAdmin\Controller;

use App\Controller\AppController as BaseController;
use Cake\Event\Event;

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.php

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

        }      



    }  

}

?>

TopicsController.php

<?php

namespace PanelAdmin\Controller;

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

class TopicsController extends AppController

{
public function initialize()

    {



        parent::initialize();



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





    }

    public function isAuthorized($user)

    {

        $action = $this->request->params['action'];

        //  registered users can add topics and view index

        if (in_array($action, ['index', 'add','topics'])) {

        return true;

        }

        // All other actions require an id or users cannot do it

        if (empty($this->request->params['pass'][0])) {

            return false;

        }      



        // The owner of a topic can edit and delete it

        // the owner of topic is known by its id and user_id value of topic .

        if (in_array($this->request->action, ['edit', 'delete'])) {

        // get topic id from the request   

        $topicId = (int)$this->request->params['pass'][0];

        // check if the topic is owned by the user

        if ($this->Topics->isOwnedBy($topicId, $user['id'])) {

        return true;

        }

        }

        return parent::isAuthorized($user);





    }



public function index()

    {

        // find('all') get all records from Topics model

        // We uses set() to pass data to view

        $this->set('topics', $this->Topics->find('all'));

    }



public function view($id)

    {

        // get() method get only one topic record using

        // the $id paraameter is received from the requested url

        // if request is /topics/view/5   the $id parameter value is 3

        $topic = $this->Topics->get($id);

        $this->set(compact('topic'));

    }



public function add()

    {

        $topic = $this->Topics->newEntity();

        //if the user topics data to your application, the POST request  informations are registered in $this->request  

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

            $topic = $this->Topics->patchEntity($topic, $this->request->data);

            $topic->user_id = $this->Auth->user('id');

if ($this->Topics->save($topic)) {

                // success() method of FlashComponent restore messages in session variable.

                // Flash messages are displayed in views

                $this->Flash->success(__('Your topic has been saved.'));

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

            }

            $this->Flash->error(__('Unable to add your topic.'));

        }

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

    }

    public function edit($id = null)

    {

        $topic = $this->Topics->get($id);

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

            $this->Topics->patchEntity($topic, $this->request->data);

            if ($this->Topics->save($topic)) {

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

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

            }

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

        }



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

    }

    public function delete($id)

    {

        //if user wants to delete a record by a GET request ,allowMethod() method give an Exception as the only available request for deleting is POST

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



        $topic = $this->Topics->get($id);

        if ($this->Topics->delete($topic)) {

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

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

        }

    }

}

?>

1 个答案:

答案 0 :(得分:1)

您必须在 src / Controller / Component /

中创建CustomAuthComponent.php文件

将代码放入CustomAuthComponent.php

<?php

namespace App\Controller\Component;


use Cake\Controller\Component\AuthComponent;

class CustomAuthComponent extends AuthComponent
{

    protected function _loginActionRedirectUrl()
    {

        return $this->_config['loginAction'];
    }

}

AppController.php之后找到$this->loadComponent('Auth',.....替换$this->loadComponent('CustomAuth',.......

之后,在每个Controller文件中找到并替换$this->Auth $this->CustomAuth

这对我有用。