UserService.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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. use Illuminate\Support\Facades\DB;
  12. use Illuminate\Support\Facades\Log;
  13. class UserService
  14. {
  15. use ServiceAppAop;
  16. protected $modelClass=User::class;
  17. /** @var CacheService $cacheService */
  18. private $cacheService;
  19. function __construct(){
  20. $this->cacheService = app('CacheService');
  21. }
  22. function hasRoles(User $user, $roles){
  23. $thisRoles=$this->cacheService->getOrExecute("user{$user['id']}->roles",function()use($user){
  24. return $user->roles;
  25. });
  26. return !!$roles->intersect($thisRoles)->count();
  27. }
  28. function getPermittingLogisticIds($user=null){
  29. if(!$user)return [];
  30. return $this->cacheService->getOrExecute("user{$user['id']}->getPermittingLogisticIds",function()use($user){
  31. return $user->getPermittingLogisticIdsAttribute() ?? [];
  32. })??[];
  33. }
  34. /**
  35. * 检查用户的管理员身份
  36. *
  37. * @param integer $userId
  38. *
  39. * @return bool
  40. */
  41. public function checkAdminIdentity(int $userId):bool
  42. {
  43. if ($userId == Auth::id())return array_search(Auth::user()["name"],config("users.superAdmin"))!==false;
  44. /** @var User|\stdClass $user */
  45. $user = User::query()->select("name")->find($userId);
  46. if (!$user)return false;
  47. return array_search($user->name,config("users.superAdmin"))!==false;
  48. }
  49. /**
  50. * @param integer|null $userId
  51. *
  52. * @return array
  53. */
  54. public function getUserHasUserWorkGroups($userId = null)
  55. {
  56. if (!$userId)$userId = Auth::id();
  57. $key = "userWorkGroups:user_".$userId;
  58. if (!Cache::has($key)){
  59. if ($this->checkAdminIdentity($userId))Cache::forever($key,array_column(UserWorkgroup::query()->select("id")->get()->toArray(),"id"));
  60. else{
  61. $userWorkGroups = [];
  62. /** @var User|\stdClass $user */
  63. $user = new User();
  64. $user->id = $userId;
  65. $user->load("roles.userWorkGroups");
  66. $user->roles->each(function ($role)use (&$userWorkGroups){
  67. $userWorkGroups = array_merge($userWorkGroups,array_column($role->userWorkGroups->toArray(),"id"));
  68. });
  69. Cache::forever($key,$userWorkGroups);
  70. }
  71. }
  72. return Cache::get($key);
  73. }
  74. /**
  75. * 清除用户缓存
  76. *
  77. * @param User $user
  78. */
  79. public function clearUserCache(User $user)
  80. {
  81. Cache::tags("authorities:user")->forget("authorities:user_".$user->id);
  82. Cache::tags("authorities:user")->forget("authorities:android:user_".$user->id);
  83. Cache::forget("userWorkGroups:user_".$user->id);
  84. Cache::tags("AUTHORITY_MENU_MAPPING")->forget("am_mapping_".$user->id);
  85. Cache::tags("USERS")->pull("user_info_".$user->id);
  86. }
  87. /**
  88. * 获取JWT token
  89. *
  90. * @param User|\stdClass $user
  91. * @param mixed $key
  92. * @return string
  93. */
  94. public function getJWTToken($user,$key):string
  95. {
  96. $time = time();
  97. $payload = [
  98. 'iss' => $_SERVER["HTTP_HOST"], //签发者
  99. 'iat' => $time,
  100. 'nbf' => $time,
  101. 'exp' => $time+config("api.timeliness_limits.token","7200"),
  102. 'data' => [
  103. 'id' => $user->id,
  104. 'username' => $user->name
  105. ]
  106. ];
  107. $alg = 'RS256';
  108. return JWT::encode($payload, $key, $alg);
  109. }
  110. /**
  111. * 设置或刷新缓存
  112. *
  113. * @param User|\stdClass|Model $user
  114. * @param null $exp
  115. */
  116. public function setOrRefreshCache($user, $exp = null)
  117. {
  118. if (!$exp)$exp = config("api.timeliness_limits.token","7200");
  119. Cache::tags("USERS")->put("user_info_".$user->id,$user,$exp);
  120. }
  121. /**
  122. * @param integer $id
  123. * @param integer $exp
  124. * @return User|\stdClass|null
  125. */
  126. public function getOrRefreshCache(int $id,int $exp):?Model
  127. {
  128. $user = Cache::tags("USERS")->get("user_info_".$id);
  129. if ($user)return $user;
  130. $user = User::query()->find($id);
  131. if (!$user)return null;
  132. $time = $exp-time();
  133. $this->setOrRefreshCache($user,$time>0 ? $time : 7200);
  134. return $user;
  135. }
  136. public function setSingleTag($key, $token)
  137. {
  138. $val = $token."#".md5($_SERVER['HTTP_USER_AGENT']);
  139. Cache::tags(User::ANDROID_SINGLE_TAG)->put($key,$val,
  140. config("api.timeliness_limits.token","7200"));
  141. }
  142. public function verifySingleTag($key, $token):bool
  143. {
  144. $tV = Cache::tags(User::ANDROID_SINGLE_TAG)->get($key);
  145. if ($tV===null)return true;
  146. $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? "#".md5($_SERVER['HTTP_USER_AGENT']) : "";
  147. return $tV===($token.$userAgent);
  148. }
  149. /**
  150. * 这里与ownerService的getIdArr区别为映射真实ID,摒弃其余因素干扰(超管身份,超级权限等)
  151. *
  152. * @param int|null $userId
  153. * @return array
  154. */
  155. public function getUserUnderOwnerIdArr(?int $userId = null) :array
  156. {
  157. if (!$userId){
  158. /**@var $user User*/
  159. $user = Auth::user();
  160. }else{
  161. $user = new User();
  162. $user->id = $userId;
  163. }
  164. $user->load("owners:id");
  165. return array_column($user->owners->toArray(),"id");
  166. }
  167. public function bindOwner($workGroupIds, $ownerGroupIds, User $user){
  168. $ownerIds = [];
  169. if ($workGroupIds){
  170. $ownerIds = app("ObligationService")->getObligationUnderOwner($workGroupIds);
  171. }
  172. if ($ownerGroupIds){
  173. $ownerIds = array_merge($ownerIds, app("OwnerService")->getOwnerGroupUnderOwner($ownerGroupIds));
  174. }
  175. $ownerIds = array_unique($ownerIds);
  176. $user->owners()->sync($ownerIds);
  177. }
  178. /**
  179. * 获取工作组关联用户ID
  180. *
  181. * @param $groupIds
  182. * @return array
  183. */
  184. private function getGroupUser($groupIds) {
  185. return User::query()->select("id")->whereHas("userWorkgroups", function ($builder) use($groupIds) {
  186. $builder->whereIn("id", $groupIds);
  187. })->pluck("id")->toArray();
  188. }
  189. /**
  190. * 移除工作组用户的绑定货主
  191. *
  192. * @param array $groupIds
  193. * @param $ownerId
  194. */
  195. public function removeGroupUserBindOwner($groupIds, $ownerId) {
  196. if (!$groupIds || count($groupIds) == 0) {
  197. return;
  198. }
  199. $userId = $this->getGroupUser($groupIds);
  200. if (!$userId || count($userId) == 0) {
  201. return;
  202. }
  203. DB::table("owner_user")->where("owner_id", $ownerId)
  204. ->whereIn("user_id", $userId)
  205. ->delete();
  206. }
  207. /**
  208. * 新增工作组用户的绑定货主
  209. *
  210. * @param $groupIds
  211. * @param $ownerId
  212. */
  213. public function insertGroupUserBindOwner($groupIds, $ownerId) {
  214. if (!$groupIds || count($groupIds) == 0) {
  215. return;
  216. }
  217. $userId = User::query()->select("id")
  218. ->whereHas("owners", function ($builder)use($ownerId) {
  219. $builder->where("id", '!=' , $ownerId);
  220. })->whereHas("userWorkgroups", function ($builder) use($groupIds) {
  221. $builder->whereIn("id", $groupIds);
  222. })->pluck("id");
  223. if (!$userId || $userId->count() == 0) {
  224. return;
  225. }
  226. foreach ($userId as $user) {
  227. DB::insert("INSERT INTO owner_user(owner_id,user_id) VALUES ({$ownerId},{$user})");
  228. }
  229. }
  230. }