SysAdminUserService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: ywl
  5. * Date: 2017/4/14
  6. * Time: 11:38
  7. */
  8. namespace App\User\Services;
  9. use App\Exceptions\ApiException;
  10. use App\Services\CommonBaseService;
  11. use App\User\Facades\SysLogFacade;
  12. use App\User\Facades\SysMenuFuncAuthFacade;
  13. use App\User\Models\SysAdminUserModel;
  14. use Illuminate\Support\Facades\Cache;
  15. use Illuminate\Http\Request;
  16. use Illuminate\Support\Facades\DB;
  17. use Illuminate\Support\Facades\Mail;
  18. class SysAdminUserService extends CommonBaseService
  19. {
  20. protected $cache = true;
  21. protected $cacheBucket = 'SysAdminUser:';
  22. protected $tokenBucket = 'AdminToken:';
  23. protected $activeBucket = "Active:";
  24. /**
  25. * 设置token缓存时间
  26. * @param $token
  27. * @param $user
  28. */
  29. public function setToken($token, $user)
  30. {
  31. Cache::put($this->getTokenKey($token), $user, config('cache.token'));
  32. }
  33. /**
  34. * 移除token缓存
  35. * */
  36. public function forgotToken($token)
  37. {
  38. return Cache::pull($this->getTokenKey($token));
  39. }
  40. /**
  41. * 获取token缓存key
  42. * @param $token
  43. * @return string
  44. */
  45. private function getTokenKey($token)
  46. {
  47. return $this->tokenBucket . $token;
  48. }
  49. /**
  50. * 获取后台用户列表
  51. * */
  52. public function getAdminUserList($params)
  53. {
  54. $pageSize = empty($params['page_size']) ? 10 : $params['page_size'];
  55. $page = empty($params['page']) ? 1 : $params['page'];
  56. $skip = ($page - 1) * $pageSize; //页面记录的开始位置,即偏移量
  57. $where = [];
  58. $where[] = ['a.status', '<', '2'];
  59. $query = $this->model->alias('a')
  60. ->leftJoin('sys_role as b','a.role_id','=','b.id')
  61. ->where($where);
  62. if (!empty($params['keyword'])) {
  63. $keyword = $params['keyword'];
  64. $query->where(function ($queryStr) use ($keyword) {
  65. $queryStr->where('a.user_name', 'like', "%" . $keyword . "%")
  66. ->orWhere('a.real_name', 'like', "%" . $keyword . "%");
  67. });
  68. }
  69. $totalCount = $query->count();
  70. $list = $query->skip($skip)
  71. ->limit($pageSize)
  72. ->selectRaw('a.id,a.user_name,a.real_name,a.phone,a.last_login_time,a.status,a.create_time,a.role_id,b.role_name')
  73. ->get()->toArray();
  74. $results = buildPage($list, $skip, $page, $pageSize, $totalCount);
  75. return $results;
  76. }
  77. /**
  78. * 新增后台修改用户信息
  79. * @return array
  80. * */
  81. public function saveAdminUser($params)
  82. {
  83. $userData = $this->buildAddAdminUser($params);
  84. if (!empty($userData['id'])) {
  85. $id = $userData['id'];
  86. $this->updateBy(['id' => $userData['id']], $userData);
  87. //求改当前用户的信息需要更新redis缓存
  88. if ($id == $this->getAuthUserId()) {
  89. $this->updateUserInfoCache();
  90. }
  91. } else {
  92. $id = $this->model->insertGetId($userData);
  93. }
  94. return $id;
  95. }
  96. /**
  97. * 构造编辑用户详情数据
  98. * @return array
  99. * */
  100. private function buildAddAdminUser($params)
  101. {
  102. $userData = [];
  103. if (isset($params['password'])) {
  104. $userData['salt'] = getRandomStr('PW');
  105. $password = $userData['salt'] . $params['password'];
  106. $userData['password'] = md5($password);
  107. }
  108. $time = nowTime();
  109. $userData['update_time'] = $time;
  110. if (!empty($params['id'])) {
  111. if (isset($params['password'])) {
  112. //修改密码要校验
  113. $this->checkLoginPassword($params['login_password']);
  114. }
  115. $userData['id'] = $params['id'];
  116. if (isset($params['real_name'])) {
  117. $userData['real_name'] = $params['real_name'];
  118. }
  119. if (isset($params['phone'])) {
  120. $userData['phone'] = $params['phone'];
  121. $info=$this->model
  122. ->where('status','<',2)
  123. ->where('id','<>',$params['id'])
  124. ->where('phone', $userData['phone'])->first();
  125. if(!empty($info)){
  126. throw new ApiException(10011,['phone'=>$userData['phone']]);
  127. }
  128. }
  129. if (isset($params['status'])) {
  130. $userData['status'] = $params['status'];
  131. }
  132. if (isset($params['role_id'])) {
  133. $userData['role_id'] = $params['role_id'];
  134. }
  135. } else {
  136. $userData['user_name'] = $params['user_name'] ?? '';
  137. $userData['real_name'] = $params['real_name'] ?? '';
  138. $userData['phone'] = $params['phone'] ?? '';
  139. $info=$this->model->where('status','<',2)
  140. ->where(function ($queryStr) use ($userData) {
  141. $queryStr->where('user_name', '=',$userData['user_name'])
  142. ->orWhere('phone', '=', $userData['phone']);
  143. })->first();
  144. if(!empty($info)){
  145. $info=$info->toArray();
  146. if($info['phone']==$userData['phone']){
  147. throw new ApiException(10011,['phone'=>$userData['phone']]);
  148. }else{
  149. throw new ApiException(10010,['user_name'=>$userData['user_name']]);
  150. }
  151. }
  152. $userData['create_time'] = $time;
  153. if (isset($params['status'])) {
  154. $userData['status'] = $params['status'];
  155. } else {
  156. $userData['status'] = SysAdminUserModel::STATUS_DISABLED;
  157. }
  158. if (isset($params['role_id'])) {
  159. $userData['role_id'] = $params['role_id'];
  160. }
  161. }
  162. return $userData;
  163. }
  164. /**
  165. * 根据id获取用户详情
  166. * */
  167. public function getUserInfoById($id)
  168. {
  169. $info = $this->model->where(['id' => $id])->first();
  170. $dataInfo = [];
  171. if (!empty($info)) {
  172. $dataInfo = $info->toArray();
  173. }
  174. return $dataInfo;
  175. }
  176. /**
  177. * 校验登陆密码
  178. * */
  179. private function checkLoginPassword($loginPassword)
  180. {
  181. $userInfo = $this->getAuthUser();
  182. if (!empty($userInfo)) {
  183. $prefixed = $userInfo['salt'];
  184. $password = $prefixed . $loginPassword;
  185. $loginPasswordMd5 = md5($password);
  186. if ($loginPasswordMd5 === $userInfo['password']) {
  187. return true;
  188. }
  189. }
  190. throw new ApiException(10001);
  191. }
  192. /**
  193. * 更新用户缓存
  194. * */
  195. public function updateUserInfoCache($token = '', $user = [])
  196. {
  197. if (empty($user)) {
  198. $userId = $this->getAuthUserId();
  199. $newUser = $this->getUserInfoById($userId);
  200. } else {
  201. $newUser = $user;
  202. }
  203. if (empty($token)) {
  204. if (config('app.login_singleton')) {
  205. $key = $this->cacheBucket . $this->tokenBucket . $userId . 'admin_token';
  206. $token = Cache::get($key);
  207. } else {
  208. $token = $this->getAuthToken();
  209. }
  210. }
  211. $CacheTokenTimeMinute = config('cache.token');
  212. $nowTime = time();
  213. $expiration_time = $nowTime + 60 * $CacheTokenTimeMinute;
  214. $newUser['expiration_time'] = $expiration_time;//过期时间
  215. $newUser['token'] = $token;
  216. $newUser['permission'] = $this->getPermission($newUser['role_id']);
  217. $this->setToken($token, $newUser);
  218. return $newUser;
  219. }
  220. /**
  221. * 根据用户名密码登陆
  222. * */
  223. public function adminLoginByPassword($params)
  224. {
  225. $ret = ['code' => 0, 'data' => []];
  226. if (empty($params)) {
  227. return;
  228. }
  229. $where = [];
  230. $where['user_name'] = $params['user_name'];
  231. $where['status'] = 0;
  232. $userInfo = $this->model->alias('a')
  233. ->where($where)->selectRaw('a.*')->first();
  234. if (!empty($userInfo)) {
  235. $prefixed = $userInfo->salt;
  236. $password = $prefixed . $params['password'];
  237. $loginPasswordMd5 = md5($password);
  238. if ($loginPasswordMd5 == $userInfo->password) {
  239. $now = nowTime();
  240. $userInfo->last_login_time = $now;
  241. $randomStr = getRandomStr('ADMIN_TOKEN');
  242. $token = md5($userInfo['user_name'] . $randomStr);
  243. $userInfo->save();
  244. $userInfo = $userInfo->toArray();
  245. $CacheTokenTimeMinute = config('cache.token');
  246. $nowTime = time();
  247. $expiration_time = $nowTime + 60 * $CacheTokenTimeMinute;
  248. $userInfo['expiration_time'] = $expiration_time;//过期时间
  249. $userInfo['token']=$token;
  250. $userInfo['permission']=$this->getPermission($userInfo['role_id']);
  251. if (config('app.login_singleton')) {
  252. $this->setCacheToken($userInfo['id'], $token);
  253. }
  254. $this->setToken($token, $userInfo);
  255. SysLogFacade::saveSysLoginLog($userInfo['id']);
  256. $ret['data']['token'] = $token;
  257. }else{
  258. $ret['code'] = 10001;
  259. }
  260. } else {
  261. $ret['code'] = 10006;
  262. }
  263. return $ret;
  264. }
  265. private function getPermission($roleId){
  266. $data=SysMenuFuncAuthFacade::adminRoleAuth($roleId);
  267. $permission=[];
  268. foreach ($data as $value){
  269. if(!empty($value['route_path'])){
  270. $permission[]=$value['route_path'];
  271. }
  272. }
  273. return $permission;
  274. }
  275. /**
  276. * 用户登出
  277. * */
  278. public function logout($token)
  279. {
  280. if (empty($token)) {
  281. return;
  282. }
  283. $this->forgotToken($token);
  284. return true;
  285. }
  286. /**
  287. * 根据token获取用户
  288. * @param $token
  289. * @return SysAdminUserModel | mixed
  290. */
  291. public function findOneByToken($token)
  292. {
  293. return Cache::get($this->getTokenKey($token));
  294. }
  295. /**
  296. * 获取用户的详细信息
  297. * @param int $type 0 简略详细 1详细信息
  298. * */
  299. public function getUserDetail($type = 0)
  300. {
  301. $ret = ['code' => 0, 'data' => []];
  302. $baseFields=['id','user_name','real_name','is_super','permission'];
  303. $detailFields=['id','user_name','real_name','phone','is_super','permission','role_id','area_id'];
  304. $user = $this->getAuthUser();
  305. $resultUser = [];
  306. if ($type) {
  307. $resultFields = $detailFields;
  308. } else {
  309. $resultFields = $baseFields;
  310. }
  311. foreach ($resultFields as $value) {
  312. $resultUser[$value] = $user[$value];
  313. }
  314. $ret['data'] = $resultUser;
  315. return $ret;
  316. }
  317. /**
  318. * 设置当前用户token
  319. * @param $userId
  320. * @param $token
  321. */
  322. public function setCacheToken($userId, $token)
  323. {
  324. $key = $this->cacheBucket . $this->tokenBucket . $userId . 'admin_token';
  325. Cache::put($key, $token, config('cache.token'));
  326. }
  327. /**
  328. * 是否最近登录的一个账号
  329. * @param $userId
  330. * @param $token
  331. * @return bool
  332. */
  333. public function isLastToken($userId, $token)
  334. {
  335. $key = $this->cacheBucket . $this->tokenBucket . $userId . 'admin_token';
  336. $insideToken = Cache::get($key);
  337. //如果缓存中不存在token
  338. if (!$insideToken) {
  339. $this->setCacheToken($userId, $token);
  340. return true;
  341. }
  342. //如果缓存中的token跟用户传入的token一致
  343. if ($insideToken == $token) {
  344. return true;
  345. }
  346. return false;
  347. }
  348. public function heartbeat($token)
  349. {
  350. if ($token) {
  351. $data = $this->findOneByToken($token);
  352. if (!empty($data)) {
  353. return $this->updateUserInfoCache($token, $data);
  354. }
  355. }
  356. }
  357. }