UserService.php 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. function getPermittingLogisticIds($user=null){
  33. if(!$user)return [];
  34. return $this->cacheService->getOrExecute("user{$user['id']}->getPermittingLogisticIds",function()use($user){
  35. return $user->getPermittingLogisticIdsAttribute() ?? [];
  36. })??[];
  37. }
  38. /**
  39. * 检查用户的管理员身份
  40. *
  41. * @param integer $userId
  42. *
  43. * @return bool
  44. */
  45. public function checkAdminIdentity(int $userId):bool
  46. {
  47. if ($userId == Auth::id())return array_search(Auth::user()["name"],config("users.superAdmin"))!==false;
  48. /** @var User|\stdClass $user */
  49. $user = User::query()->select("name")->find($userId);
  50. if (!$user)return false;
  51. return array_search($user->name,config("users.superAdmin"))!==false;
  52. }
  53. /**
  54. * @param integer|null $userId
  55. *
  56. * @return array
  57. */
  58. public function getUserHasOwners($userId = null)
  59. {
  60. if (!$userId)$userId = Auth::id();
  61. $key = "owners:user_".$userId;
  62. if (!Cache::has($key)){
  63. if ($this->checkAdminIdentity($userId))Cache::forever($key,array_column(Owner::query()->select("id")->whereNull("deleted_at")->get()->toArray(),"id"));
  64. else{
  65. $owners = [];
  66. /** @var User|\stdClass $user */
  67. $user = new User();
  68. $user->id = $userId;
  69. $user->load("roles.owners");
  70. $user->roles->each(function ($role)use (&$owners){
  71. $owners = array_merge($owners,array_column($role->owners->toArray(),"id"));
  72. });
  73. Cache::forever($key,$owners);
  74. }
  75. }
  76. return Cache::get($key);
  77. }
  78. /**
  79. * @param integer|null $userId
  80. *
  81. * @return array
  82. */
  83. public function getUserHasUserWorkGroups($userId = null)
  84. {
  85. if (!$userId)$userId = Auth::id();
  86. $key = "userWorkGroups:user_".$userId;
  87. if (!Cache::has($key)){
  88. if ($this->checkAdminIdentity($userId))Cache::forever($key,array_column(UserWorkgroup::query()->select("id")->get()->toArray(),"id"));
  89. else{
  90. $userWorkGroups = [];
  91. /** @var User|\stdClass $user */
  92. $user = new User();
  93. $user->id = $userId;
  94. $user->load("roles.userWorkGroups");
  95. $user->roles->each(function ($role)use (&$userWorkGroups){
  96. $userWorkGroups = array_merge($userWorkGroups,array_column($role->userWorkGroups->toArray(),"id"));
  97. });
  98. Cache::forever($key,$userWorkGroups);
  99. }
  100. }
  101. return Cache::get($key);
  102. }
  103. /**
  104. * 清除用户缓存
  105. *
  106. * @param User $user
  107. */
  108. public function clearUserCache(User $user)
  109. {
  110. Cache::tags("authorities:user")->forget("authorities:user_".$user->id);
  111. Cache::tags("authorities:user")->forget("authorities:android:user_".$user->id);
  112. Cache::forget("owners:user_".$user->id);
  113. Cache::forget("userWorkGroups:user_".$user->id);
  114. Cache::tags("AUTHORITY_MENU_MAPPING")->forget("am_mapping_".$user->id);
  115. Cache::tags("USERS")->pull("user_info_".$user->id);
  116. }
  117. /**
  118. * 获取JWT token
  119. *
  120. * @param User|\stdClass $user
  121. * @param mixed $key
  122. * @return string
  123. */
  124. public function getJWTToken($user,$key):string
  125. {
  126. $time = time();
  127. $payload = [
  128. 'iss' => $_SERVER["HTTP_HOST"], //签发者
  129. 'iat' => $time,
  130. 'nbf' => $time,
  131. 'exp' => $time+config("api.timeliness_limits.token","7200"),
  132. 'data' => [
  133. 'id' => $user->id,
  134. 'username' => $user->name
  135. ]
  136. ];
  137. $alg = 'RS256';
  138. return JWT::encode($payload, $key, $alg);
  139. }
  140. /**
  141. * 设置或刷新缓存
  142. *
  143. * @param User|\stdClass|Model $user
  144. * @param null $exp
  145. */
  146. public function setOrRefreshCache($user, $exp = null)
  147. {
  148. if (!$exp)$exp = config("api.timeliness_limits.token","7200");
  149. Cache::tags("USERS")->put("user_info_".$user->id,$user,$exp);
  150. }
  151. /**
  152. * @param integer $id
  153. * @param integer $exp
  154. * @return User|\stdClass|null
  155. */
  156. public function getOrRefreshCache(int $id,int $exp):?Model
  157. {
  158. $user = Cache::tags("USERS")->get("user_info_".$id);
  159. if ($user)return $user;
  160. $user = User::query()->find($id);
  161. if (!$user)return null;
  162. $time = $exp-time();
  163. $this->setOrRefreshCache($user,$time>0 ? $time : 7200);
  164. return $user;
  165. }
  166. }