UserTrait.php 2.4 KB

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