【问题标题】:Avoid users can change url id on Cakephp避免用户可以在 Cakephp 上更改 url id
【发布时间】:2016-09-17 22:20:59
【问题描述】:

我想避免某些用户可以更改 url 的 id 而他可以编辑另一本书。 例如:这是原始网址:

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

用户可以更改数字1:

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

我希望用户只有可以编辑他所在国家/地区的图书

这是我在 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']);
}

我试图改变这部分代码:

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

为此:

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

因此,只有用户可以显示来自同一国家/地区的图书。 但我有一个错误:“Record not found in table “book”

如果我把原来的编辑功能完美无缺,但用户可以更改id。 如果我进行上述更改,用户将无法编辑任何图书 ID

【问题讨论】:

  • 那里的“城市”真的正确吗?如果你遵循 Cake 的约定,那就是 Cities。虽然我希望如果这是问题,它会给你一个不同的错误消息。
  • @GregSchmidt 没错,错误会有所不同
  • 您是否查看过 Cake 为您的查询生成的原始 SQL?有时这很有帮助;如果它没有给你任何想法,在这里发布它可能会帮助其他人帮助你。

标签: php model-view-controller cakephp-3.0


【解决方案1】:

如果get操作没有找到任何结果a 将引发 Cake\Datasource\Exception\RecordNotFoundException。你 可以自己捕获这个异常,或者允许 CakePHP 转换 它变成了 404 错误。

查Documentation Here

您也可以使用find() 方法检查结果为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

【讨论】:

  • 抱歉,稍后回复。问题是我有多个管理员可以编辑他们的国家书籍。每个管理员都有书。但是一个人不能从他所在的另一个国家改变书
猜你喜欢
  • 1970-01-01
  • 2019-05-10
  • 2017-10-20
  • 1970-01-01
  • 1970-01-01
  • 2018-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多