Jerome Manatad Jerome Manatad - 1 year ago 79
CSS Question

how to prevent other users to edit my profile in cakephp3

I have simple program using cakephp3, when I try to directly put this into browser:

http://localhost/sample/users/edit/82

it directly goes to login page. Then after the login, my code still can edit the profile even that profile is not the current user login.

Below is my edit code

public function edit($id = null)
{
$user = $this->Users->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$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' => 'index']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}

}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}


edit.ctp

<div class="actions columns large-2 medium-3">
<h3><?= __('Actions') ?></h3>
<ul class="side-nav">
<li><?= $this->Form->postLink(
__('Delete'),
['action' => 'delete', $user->id],
['confirm' => __('Are you sure you want to delete # {0}?',
$user->id)]
)
?></li>
<li><?= $this->Html->link(__('List Users'), ['action' => 'index']) ?>
</li>
</ul>




<div class="users form large-10 medium-9 columns">
<?= $this->Form->create($user) ?>
<fieldset>
<legend><?= __('Edit User') ?></legend>
<?php
echo $this->Form->input('username');
echo $this->Form->input('password');
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>

Answer Source

You have to check the existing user is trying to update his/her profile. You can do something like this.

All this on top of your edit method

public function edit($id = null)
{
  $logged_user_id=$this->Auth->user('id');

  if($logged_user_id==$id){
  $user = $this->Users->get($id, [
        'contain' => []
    ]);
    if ($this->request->is(['patch', 'post', 'put'])) {
        $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' => 'index']);
                } else {
                    $this->Flash->error(__('The user could not be saved. Please, try again.'));
                }

    }
    $this->set(compact('user'));
    $this->set('_serialize', ['user']);
   } else {
                    $this->Flash->error(__('You are not allowed to do this.'));
     }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download