PostPolicy.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. /*
  3. * This file is part of the Jiannei/lumen-api-starter.
  4. *
  5. * (c) Jiannei <longjian.huang@foxmail.com>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace App\Policies;
  11. use App\Repositories\Enums\PermissionEnum;
  12. use App\Repositories\Models\Post;
  13. use App\Repositories\Models\User;
  14. use Illuminate\Auth\Access\HandlesAuthorization;
  15. class PostPolicy
  16. {
  17. use HandlesAuthorization;
  18. /**
  19. * Determine whether the user can view any posts.
  20. *
  21. * @param User $user
  22. * @return mixed
  23. */
  24. public function viewAny(User $user)
  25. {
  26. if ($user->can(PermissionEnum::ROUTE_POSTS_VIEW_ANY()->name)) {
  27. return true;
  28. }
  29. return false;
  30. }
  31. /**
  32. * Determine whether the user can view the post.
  33. *
  34. * @param User|null $user
  35. * @param Post $post
  36. * @return mixed
  37. */
  38. public function view(?User $user, Post $post)
  39. {
  40. if ($post->published) {
  41. return true;
  42. }
  43. // visitors cannot view unpublished items
  44. if ($user === null) {
  45. return false;
  46. }
  47. // admin overrides published status
  48. if ($user->can(PermissionEnum::ROUTE_POSTS_VIEW()->name)) {
  49. return true;
  50. }
  51. // authors can view their own unpublished posts
  52. return $user->isOwnerOf($post);
  53. }
  54. /**
  55. * Determine whether the user can create posts.
  56. *
  57. * @param User $user
  58. * @return mixed
  59. */
  60. public function create(User $user)
  61. {
  62. if ($user->can(PermissionEnum::ROUTE_POSTS_CREATE()->name)) {
  63. return true;
  64. }
  65. return false;
  66. }
  67. /**
  68. * Determine whether the user can update the post.
  69. *
  70. * @param User $user
  71. * @param Post $post
  72. * @return mixed
  73. */
  74. public function update(User $user, Post $post)
  75. {
  76. if ($user->isOwnerOf($post) || $user->can('edit all posts')) {
  77. return true;
  78. }
  79. return false;
  80. }
  81. /**
  82. * Determine whether the user can delete the post.
  83. *
  84. * @param User $user
  85. * @param Post $post
  86. * @return mixed
  87. */
  88. public function delete(User $user, Post $post)
  89. {
  90. if ($user->isOwnerOf($post) || $user->can(PermissionEnum::ROUTE_POSTS_DELETE()->name)) {
  91. return true;
  92. }
  93. return false;
  94. }
  95. }