UserService.php 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. <?php
  2. namespace App\Services;
  3. use App\Owner;
  4. use App\User;
  5. use App\UserWorkgroup;
  6. use Firebase\JWT\JWT;
  7. use Illuminate\Database\Eloquent\Model;
  8. use Illuminate\Support\Facades\Auth;
  9. use Illuminate\Support\Facades\Cache;
  10. use App\Traits\ServiceAppAop;
  11. class UserService
  12. {
  13. use ServiceAppAop;
  14. protected $modelClass=User::class;
  15. /** @var CacheService $cacheService */
  16. private $cacheService;
  17. function __construct(){
  18. $this->cacheService = app('CacheService');
  19. }
  20. function hasRoles(User $user, $roles){
  21. $thisRoles=$this->cacheService->getOrExecute("user{$user['id']}->roles",function()use($user){
  22. return $user->roles;
  23. });
  24. return !!$roles->intersect($thisRoles)->count();
  25. }
  26. function getPermittingOwnerIds($user=null){
  27. if(!$user)return [];
  28. return $this->cacheService->getOrExecute("user{$user['id']}->getPermittingOwnerIds",function()use($user){
  29. return $user->getPermittingOwnerIdsAttribute() ?? [];
  30. })??[];
  31. }
  32. /**
  33. * 检查用户的管理员身份
  34. *
  35. * @param integer $userId
  36. *
  37. * @return bool
  38. */
  39. public function checkAdminIdentity(int $userId):bool
  40. {
  41. if ($userId == Auth::id())return array_search(Auth::user()["name"],config("users.superAdmin"))!==false;
  42. /** @var User|\stdClass $user */
  43. $user = User::query()->select("name")->find($userId);
  44. if (!$user)return false;
  45. return array_search($user->name,config("users.superAdmin"))!==false;
  46. }
  47. /**
  48. * @param integer|null $userId
  49. *
  50. * @return array
  51. */
  52. public function getUserHasOwners($userId = null)
  53. {
  54. if (!$userId)$userId = Auth::id();
  55. $key = "owners:user_".$userId;
  56. if (!Cache::has($key)){
  57. if ($this->checkAdminIdentity($userId))Cache::forever($key,array_column(Owner::query()->select("id")->whereNull("deleted_at")->get()->toArray(),"id"));
  58. else{
  59. $owners = [];
  60. /** @var User|\stdClass $user */
  61. $user = new User();
  62. $user->id = $userId;
  63. $user->load("roles.owners");
  64. $user->roles->each(function ($role)use (&$owners){
  65. $owners = array_merge($owners,array_column($role->owners->toArray(),"id"));
  66. });
  67. Cache::forever($key,$owners);
  68. }
  69. }
  70. return Cache::get($key);
  71. }
  72. /**
  73. * @param integer|null $userId
  74. *
  75. * @return array
  76. */
  77. public function getUserHasUserWorkGroups($userId = null)
  78. {
  79. if (!$userId)$userId = Auth::id();
  80. $key = "userWorkGroups:user_".$userId;
  81. if (!Cache::has($key)){
  82. if ($this->checkAdminIdentity($userId))Cache::forever($key,array_column(UserWorkgroup::query()->select("id")->get()->toArray(),"id"));
  83. else{
  84. $userWorkGroups = [];
  85. /** @var User|\stdClass $user */
  86. $user = new User();
  87. $user->id = $userId;
  88. $user->load("roles.userWorkGroups");
  89. $user->roles->each(function ($role)use (&$userWorkGroups){
  90. $userWorkGroups = array_merge($userWorkGroups,array_column($role->userWorkGroups->toArray(),"id"));
  91. });
  92. Cache::forever($key,$userWorkGroups);
  93. }
  94. }
  95. return Cache::get($key);
  96. }
  97. /**
  98. * 清除用户缓存
  99. *
  100. * @param User $user
  101. */
  102. public function clearUserCache(User $user)
  103. {
  104. Cache::tags("authorities:user")->forget("authorities:user_".$user->id);
  105. Cache::tags("authorities:user")->forget("authorities:android:user_".$user->id);
  106. Cache::forget("owners:user_".$user->id);
  107. Cache::forget("userWorkGroups:user_".$user->id);
  108. Cache::tags("AUTHORITY_MENU_MAPPING")->forget("am_mapping_".$user->id);
  109. Cache::tags("USERS")->pull("user_info_".$user->id);
  110. }
  111. /**
  112. * 获取JWT token
  113. *
  114. * @param User|\stdClass $user
  115. * @param mixed $key
  116. * @return string
  117. */
  118. public function getJWTToken($user,$key):string
  119. {
  120. $time = time();
  121. $payload = [
  122. 'iss' => $_SERVER["HTTP_HOST"], //签发者
  123. 'iat' => $time,
  124. 'nbf' => $time,
  125. 'exp' => $time+config("api.timeliness_limits.token","7200"),
  126. 'data' => [
  127. 'id' => $user->id,
  128. 'username' => $user->name
  129. ]
  130. ];
  131. $alg = 'RS256';
  132. return JWT::encode($payload, $key, $alg);
  133. }
  134. /**
  135. * 设置或刷新缓存
  136. *
  137. * @param User|\stdClass|Model $user
  138. * @param null $exp
  139. */
  140. public function setOrRefreshCache($user, $exp = null)
  141. {
  142. if (!$exp)$exp = config("api.timeliness_limits.token","7200");
  143. Cache::tags("USERS")->put("user_info_".$user->id,$user,$exp);
  144. }
  145. /**
  146. * @param integer $id
  147. * @param integer $exp
  148. * @return User|\stdClass|null
  149. */
  150. public function getOrRefreshCache(int $id,int $exp):?Model
  151. {
  152. $user = Cache::tags("USERS")->get("user_info_".$id);
  153. if ($user)return $user;
  154. $user = User::query()->find($id);
  155. if (!$user)return null;
  156. $time = $exp-time();
  157. $this->setOrRefreshCache($user,$time>0 ? $time : 7200);
  158. return $user;
  159. }
  160. }