Multipe Record delete not working CSRF- Cakephp

2019-08-23 09:58发布

I've found one of the answers delete multipe record and tried following it, but I keep getting the same message:

CSRF token mismatch.
Cake\Http\Exception\InvalidCsrfTokenException

'_Token' was not found in request data.

Edit : The Delete button isn't working on thoses 4 Controller/Table (Users, Prospects, Contacts, Accounts, Leads) But they do work on my other table

Here is the

AppController.php

  <?php

  namespace App\Controller;

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


 class AppController extends Controller
 {

public function initialize()
{

    parent::initialize();
    $this->loadComponent('RequestHandler', [
        'enableBeforeRedirect' => false,
    ]);
    $this->loadComponent('Flash');

    $this->loadComponent('Security');
    $this->loadComponent('Csrf');
}
public function pr($arr){
    echo "<pre>";
    print_r($arr);
    echo "</pre>";
    exit();
}
public function beforeRender(Event $event)
{
    if(!array_key_exists('_serialize', $this->viewVars) &&
        in_array($this->response->getType(), ['application/json', 'application/xml'])
){
        $this->set('_serialize', true);
    }

    if($this->request->getSession()->read('Auth.User')){
         $this->set('loggedIn', true);   
    } else {
        $this->set('loggedIn', false); 
    }
 }
 }

UsersController.php

  <?php
    namespace App\Controller;

    use App\Controller\AppController;
    use Cake\I18n\Time;
    use Cake\Event\Event;
    use Cake\ORM\TableRegistry; 
    use Cake\Mailer\Email;
    use Cake\Auth\DefaultPasswordHasher;
    Use Cake\Utility\Security;
    use Cake\Routing\Router;

    class UsersController extends AppController
    {
   public function beforeFilter(Event $event)
  {
    parent::beforeFilter($event);

   $this->Security->setConfig('unlockedActions', ['add']);

  public function initialize(){
    parent::initialize();
    $this->loadComponent('Paginator');
    $this->loadComponent('Security');
  }
   public function delete($id = null) {
if (!$this->request->is('post')) {
    throw new MethodNotAllowedException();
}
$this->User->id = $id;
if (!$this->User->exists()) {
    throw new NotFoundException(__('Invalid user'));
}
if ($this->User->delete()) {
    $this->Session->setFlash(__('User deleted'));
    $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('User was not deleted'));
$this->redirect(array('action' => 'index'));
}

public function deleteall()
{

     if ($this->request->is('post'))
    {
        foreach($this->data['Users']['user_id'] as $key => $value)
        {
            $this->Subject->delete($value);
        }
        $this->Session->setFlash('User has been deleted.');
    }        
    $this->redirect(array('action' => 'index'));

   /* $this->request->allowMethod(['post', 'delete']);
    $user = $this->Users->get($id);
    foreach ($user as $value) {
        $this->Users->deleteAll(['id'=>$value]);
    }
    return $this->redirect(['action'=>'index']);*/
}
      public function isAuthorized($user)
{
    // Admin has full access
    if ($user['role'] == 'Admin') {
        return true;
    }
    // User can view and edit own account only
    if (in_array($this->request->action, ['view', 'edit', 'delete']) && $user['id'] == (int)$this->request->params['pass'][0]) {
        return true;
    }
    return false;
}    

   public function verification($token){
        $userTable = TableRegistry::get('Users');
        $verify = $userTable->find('all')->where(['token'=>$token])->first();
        $verify->verified = '1';
        $UserTable->save($verify);
    }    

And Here is a Working Delete on

NotesController

public function delete($id = null)
{
    $this->request->allowMethod(['post', 'delete']);
    $note = $this->Notes->get($id);
    if ($this->Notes->delete($note)) {
        $this->Flash->success(__('The note has been deleted.'));
    } else {
        $this->Flash->error(__('The note could not be deleted. Please, try again.'));
    }

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

index.ctp

 <button type="submit" formaction="<?php echo $this->Url- 
 >build(['action'=>'deleteall']) ?>" class="btn btn-danger" 
 onclick="return confirm('Are yo u sure you want to delete users?')">
    Delete</button>
    </p>

 <th><input type="checkbox" class="selectall"/></th>

 <td><input type="checkbox" class="selectbox" name="ids[]" value="<?= 
 h($user->id) ?></td>"/></td>

<button type="submit" formaction="<?php echo $this->Url->build(['action' =>'delete', $user->id]) ?>" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure?')">Delete</button>

标签: cakephp csrf
1条回答
来,给爷笑一个
2楼-- · 2019-08-23 10:34

You need to disable CSRF and Security components. You can disable them for specific actions by adding below code in your controller's beforeFilter method.

$actions = [
    'delete',
    'deleteall'
];

if (in_array($this->request->params['action'], $actions)) {
    // for csrf
    $this->eventManager()->off($this->Csrf);

    // for security component
    $this->Security->config('unlockedActions', $actions);
}

Hope this will help.

查看更多
登录 后发表回答