3

我无法让我的身份验证策略之一正确运行,导致授权尝试总是返回错误。为了测试,我什至只是强制函数返回 true。我正在使用 Laravel 5.4,这是我的策略功能:

public function can_modify_or_delete(User $user, Comment $comment)
{
    return true;
}

在我的AuthServiceProvider.php文件中,我已将其添加CommentPolicy到我现有的政策注册中。

protected $policies = [
    'App\Models\Post' => 'App\Policies\PostPolicy',
    'App\Models\Comment' => 'App\Policies\CommentPolicy',
];

奇怪的是,该职位政策一直运作良好。评论似乎要么没有被注册,要么没有被正确调用。

在我的路线中:

Route::delete('/comments/{comment}', 'CommentsController@destroy');

并且在CommentsController

public function destroy(Request $request, Comment $comment)
{   
    $this->authorize('can_modify_or_delete', $comment);
    $comment->delete();

    return response(['status' => 'Comment deleted'], 200);
}

不幸的是,无论如何,该授权检查都返回错误。我错过了什么吗?非常仔细地检查了错别字,找不到任何错别字。我还确认路由模型绑定正在按预期工作,因此这不是空资源问题。我尝试dd()了该政策,但它甚至没有被调用。

4

1 回答 1

8

哇,所以这实际上是我的错字(典型!)。在我的Comment模型中,我不小心models在我的命名空间中有一个小写字母,即:

namespace App\models;

什么时候应该是:

namespace App\Models;

这只是让我措手不及,因为在我的控制器中我有:

use App\Models\Comment;

并且该destroy()方法注入了一条评论,实际上工作正常,评论正常填充。似乎策略注册路径必须比use声明更准确。

于 2017-05-14T12:20:41.273 回答