caitlin
caitlin

Reputation: 2819

CakePHP: Check a user's group_id before deletion

I'm trying to protect administrators from accidentally deleting each other in CakePHP 2.4 by checking the group_id. I tried using the following delete method, but it deletes the user anyway and doesn't redirect. How do I return the group_id of the user and then redirect and display an appropriate flash saying "Administrators cannot be deleted"?

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 ($user['User']['group_id'] == 1) { //Check user group
        $this->Session->setFlash(__('Administrators can not be deleted'), 'flash/error');
        $this->redirect(array('action' => 'index'));
        }

    if (!$this->User->delete()) {
        $this->Session->setFlash(__('User could not be deleted'), 'flash/error');
        $this->redirect(array('action' => 'index'));
        }

    if ($this->User->delete()) {
        $this->Session->setFlash(__('User deleted'), 'flash/success');
        $this->redirect(array('action' => 'index'));

}}

Upvotes: 0

Views: 84

Answers (1)

Kai
Kai

Reputation: 3823

  1. You have a typo in your code -- change your = to == ; then your if statement shouldn't be evaluating as true all the time

    if ($user['User']['group_id'] == '1') 
    
  2. Session is either a component (part of the Controller layer) or a helper (part of the View layer) -- it is not intended to be used in the Model, nor should it be used in the model, generally. And redirect() is a controller method only. Just have beforeDelete return false, and then in your controller have a check to see if the delete failed (i.e. it returned false), and if so, show your error flash message, and redirect.

Upvotes: 1

Related Questions