UserTrait.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace Modules\Video\Http\Controllers;
  3. use Catch\Base\CatchController;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Collection;
  6. use Illuminate\Support\Facades\DB;
  7. use Modules\Common\Errors\Errors;
  8. use Modules\Common\Exceptions\CommonBusinessException;
  9. use Modules\User\Models\User;
  10. trait UserTrait
  11. {
  12. // 当前登录用户
  13. protected $currentUser;
  14. /**
  15. * 获取当前登录用户
  16. * @return User
  17. */
  18. protected function getCurrentUser(): User {
  19. if(!$this->currentUser) {
  20. $this->currentUser = $this->getLoginUser();
  21. }
  22. return $this->currentUser;
  23. }
  24. /**
  25. * 当前用户的所有的角色标识的结合
  26. * @return Collection
  27. */
  28. protected function listUserRoles():Collection {
  29. return $this->getCurrentUser()->roles->pluck('identify');
  30. }
  31. /**
  32. * 当前用户是否是cp角色
  33. * @return bool
  34. */
  35. public function userIsCp():bool {
  36. return $this->listUserRoles()->contains('cp');
  37. }
  38. /**
  39. * 如果当前用户是cp角色,返回cp_name,否则返回null
  40. * @return string
  41. */
  42. public function getUserCpName():string|null {
  43. if($this->userIsCp()) {
  44. return DB::table('user_belong_to_cp')
  45. ->where([
  46. 'is_enabled' => 1,
  47. 'user_id' => $this->getCurrentUser()->id,
  48. ])->value('cp_name');
  49. } else {
  50. return null;
  51. }
  52. }
  53. protected function getUserContext($operateUserId) {
  54. $loginUser = $this->getLoginUser();
  55. $loginUserRoles = $this->listUserRoles();
  56. if($operateUserId) {
  57. $operateUser = User::find($operateUserId);
  58. $operateUserRoles = $operateUser->roles->pluck('identify');
  59. if($loginUser->id != $operateUser->pid) {
  60. CommonBusinessException::throwError(Errors::NO_OPERATE_PERMISSION);
  61. }
  62. if(!$operateUserRoles->contains('optimizer')) {
  63. CommonBusinessException::throwError(Errors::NO_OPERATE_PERMISSION);
  64. }
  65. } else {
  66. $operateUser = $loginUser;
  67. $operateUserRoles = $loginUserRoles;
  68. }
  69. return compact('loginUser', 'loginUserRoles', 'operateUserRoles', 'operateUser');
  70. }
  71. }