Skip to content

Commit

Permalink
Merge pull request #164 from daydevelops/article_policy
Browse files Browse the repository at this point in the history
added policy for commenting on an article. check auth and is_draft
  • Loading branch information
jcc authored Mar 18, 2019
2 parents 81d3a0c + 0dcd448 commit 941ce81
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 15 deletions.
11 changes: 8 additions & 3 deletions app/Http/Controllers/Api/CommentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,14 @@ public function index(Request $request)
*/
public function store(CommentRequest $request)
{
$data = array_merge($request->all(), [
'user_id' => Auth::user()->id,
]);

$data = $request->all();
if ($data['commentable_type'] === 'articles') {
$article = \App\Article::find($data['commentable_id']);
if (!auth()->user()->can('comment',$article)) return response()->json([],403);
}

$data['user_id'] = Auth::user()->id;

$mention = new Mention();
$data['content'] = $mention->parse($data['content']);
Expand Down
23 changes: 23 additions & 0 deletions app/Policies/ArticlePolicy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace App\Policies;

use App\User;
use App\Article;
use Illuminate\Auth\Access\HandlesAuthorization;

class ArticlePolicy
{
use HandlesAuthorization;

/**
* Determine whether the user can comment to this article.
*
* @param \App\User $user
* @param \App\Article $article
* @return bool
*/
public function comment(User $user, Article $article) {
return auth()->check() && !$article->is_draft;
}
}
1 change: 1 addition & 0 deletions app/Providers/AuthServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ class AuthServiceProvider extends ServiceProvider
*/
protected $policies = [
\App\User::class => \App\Policies\UserPolicy::class,
\App\Article::class => \App\Policies\ArticlePolicy::class,
\App\Comment::class => \App\Policies\CommentPolicy::class,
\App\Discussion::class => \App\Policies\DiscussionPolicy::class,
];
Expand Down
21 changes: 9 additions & 12 deletions resources/views/article/show.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,18 +46,15 @@
</div>
</div>

@if(Auth::guest())
<comment title="评论"
commentable-type="articles"
commentable-id="{{ $article->id }}"></comment>
@else
<comment title="评论"
username="{{ Auth::user()->name }}"
user-avatar="{{ Auth::user()->avatar }}"
commentable-type="articles"
commentable-id="{{ $article->id }}"
can-comment></comment>
@endif
<comment title="Comments"
commentable-type="articles"
commentable-id="{{ $article->id }}"
@can('comment',$article)
username="{{ Auth::user()->name }}"
user-avatar="{{ Auth::user()->avatar }}"
can-comment
@endcan
></comment>

@endsection

Expand Down

0 comments on commit 941ce81

Please sign in to comment.