doz59484 2016-09-17 22:20
浏览 40

避免用户可以在Cakephp上更改url id

I want to avoid that some user can change the id of the url and he can edit another Book. For example: this is the original url:

https://www.myurl/books/edit/1

The user can change the number 1:

https://www.myurl/books/edit/41

I wanna the user only can edit his books from his country

This is my original Edit from my BooksController

public function edit($id = null)
{
    $country_id= $this->Auth->User()['country_id'];

    $book= $this->Books->get($id, [
        'contain' => []
    ]);
    if ($this->request->is(['patch', 'book', 'put'])) {
        $book= $this->Books->patchEntity($book, $this->request->data);
        if ($this->Books->save($book)) {
            $this->Flash->success(__('Success.'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('Error'));
        }
    }


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

I tried to change this part of code:

$country_id= $this->Auth->User()['country_id'];
$book= $this->Books->get($id, [
        'contain' => []
    ]);

for that:

$country_id= $this -> Auth -> User()['country_id'];
$book = $this->Books->get($id, [
        'contain' => ['City'],
        'conditions' => ['City.country_id' => $country_id]
    ]);

So, only the user can show the book from the same country. But I have an error: "Record not found in table "book""

If I put the original edit function works perfect, but the user can change the id. If I make above change the user can't edit any book id

  • 写回答

1条回答 默认 最新

  • dongxi2163 2016-09-29 14:29
    关注

    If the get operation does not find any results a Cake\Datasource\Exception\RecordNotFoundException will be raised. You can either catch this exception yourself, or allow CakePHP to convert it into a 404 error.

    Check Documentation Here

    Alternatively uou can check with find() method with result of first()

    $book = $this->Books->find([
            'contain' => ['City'],
            'conditions' => ['City.country_id' => $country_id,'Books.id'=>$id]
        ])->first();
    

    http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#getting-the-first-result

    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭