Consolidate Post visibility logic into the PostPolicy

A post can only be seen if the discussion in which it resides can be
seen. The logic for this belongs in the policy, not the model.
This commit is contained in:
Toby Zerner 2018-11-11 16:54:15 +10:30
parent 9de786d1e6
commit 17fdc0ebe0
2 changed files with 13 additions and 22 deletions

View File

@ -12,6 +12,7 @@
namespace Flarum\Post; namespace Flarum\Post;
use Flarum\Database\AbstractModel; use Flarum\Database\AbstractModel;
use Flarum\Database\ScopeVisibilityTrait;
use Flarum\Discussion\Discussion; use Flarum\Discussion\Discussion;
use Flarum\Event\GetModelIsPrivate; use Flarum\Event\GetModelIsPrivate;
use Flarum\Event\ScopeModelVisibility; use Flarum\Event\ScopeModelVisibility;
@ -42,6 +43,7 @@ use Illuminate\Database\Eloquent\Builder;
class Post extends AbstractModel class Post extends AbstractModel
{ {
use EventGeneratorTrait; use EventGeneratorTrait;
use ScopeVisibilityTrait;
protected $table = 'posts'; protected $table = 'posts';
@ -109,28 +111,6 @@ class Post extends AbstractModel
static::addGlobalScope(new RegisteredTypesScope); static::addGlobalScope(new RegisteredTypesScope);
} }
/**
* @param Builder $query
* @param User $actor
*/
public function scopeWhereVisibleTo(Builder $query, User $actor)
{
static::$dispatcher->dispatch(
new ScopeModelVisibility($query, $actor, 'view')
);
// Make sure the post's discussion is visible as well
$query->whereExists(function ($query) use ($actor) {
$query->selectRaw('1')
->from('discussions')
->whereColumn('discussions.id', 'posts.discussion_id');
static::$dispatcher->dispatch(
new ScopeModelVisibility(Discussion::query()->setQuery($query), $actor, 'view')
);
});
}
/** /**
* Determine whether or not this post is visible to the given user. * Determine whether or not this post is visible to the given user.
* *

View File

@ -66,6 +66,17 @@ class PostPolicy extends AbstractPolicy
*/ */
public function find(User $actor, $query) public function find(User $actor, $query)
{ {
// Make sure the post's discussion is visible as well.
$query->whereExists(function ($query) use ($actor) {
$query->selectRaw('1')
->from('discussions')
->whereColumn('discussions.id', 'posts.discussion_id');
$this->events->dispatch(
new ScopeModelVisibility(Discussion::query()->setQuery($query), $actor, 'view')
);
});
// Hide private posts by default. // Hide private posts by default.
$query->where(function ($query) use ($actor) { $query->where(function ($query) use ($actor) {
$query->where('posts.is_private', false) $query->where('posts.is_private', false)