From 7d74890bae2cd985b39a73052fb66436f0f0d4e5 Mon Sep 17 00:00:00 2001 From: Nafies Luthfi Date: Sun, 5 Aug 2018 10:49:37 +0800 Subject: [PATCH] Add edit comment policy --- app/Policies/Projects/CommentPolicy.php | 30 ++++++++++++++++++++++++++++++ app/Providers/AuthServiceProvider.php | 1 + tests/Unit/Policies/CommentPolicyTest.php | 29 +++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 app/Policies/Projects/CommentPolicy.php create mode 100644 tests/Unit/Policies/CommentPolicyTest.php diff --git a/app/Policies/Projects/CommentPolicy.php b/app/Policies/Projects/CommentPolicy.php new file mode 100644 index 0000000..1a17331 --- /dev/null +++ b/app/Policies/Projects/CommentPolicy.php @@ -0,0 +1,30 @@ + + */ +class CommentPolicy +{ + use HandlesAuthorization; + + /** + * Determine whether the user can update the comment. + * + * @param \App\Entities\Users\User $user + * @param \App\Entities\Projects\Comment $comment + * @return bool + */ + public function update(User $user, Comment $comment) + { + return $user->hasRole('admin') + || ($user->hasRole('worker') && $comment->creator_id == $user->id); + } +} diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php index cf30140..4584098 100644 --- a/app/Providers/AuthServiceProvider.php +++ b/app/Providers/AuthServiceProvider.php @@ -16,6 +16,7 @@ class AuthServiceProvider extends ServiceProvider 'App\Entities\Partners\Vendor' => 'App\Policies\Partners\VendorPolicy', 'App\Entities\Partners\Customer' => 'App\Policies\Partners\CustomerPolicy', 'App\Entities\Projects\Project' => 'App\Policies\Projects\ProjectPolicy', + 'App\Entities\Projects\Comment' => 'App\Policies\Projects\CommentPolicy', 'App\Entities\Projects\Job' => 'App\Policies\Projects\JobPolicy', 'App\Entities\Projects\Task' => 'App\Policies\Projects\TaskPolicy', 'App\Entities\Payments\Payment' => 'App\Policies\PaymentPolicy', diff --git a/tests/Unit/Policies/CommentPolicyTest.php b/tests/Unit/Policies/CommentPolicyTest.php new file mode 100644 index 0000000..21bada2 --- /dev/null +++ b/tests/Unit/Policies/CommentPolicyTest.php @@ -0,0 +1,29 @@ +createUser('admin'); + $comment = factory(Comment::class)->create(); + + $this->assertTrue($admin->can('update', $comment)); + } + + /** @test */ + public function worker_can_only_edit_their_comments() + { + $admin = $this->createUser('admin'); + $worker = $this->createUser('worker'); + $comment = factory(Comment::class)->create(['creator_id' => $worker->id]); + + $this->assertTrue($admin->can('update', $comment)); + $this->assertTrue($worker->can('update', $comment)); + } +}