SystemAdminServices.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\services\system\admin;
  12. use app\model\system\admin\SystemAdmin;
  13. use Firebase\JWT\ExpiredException;
  14. use Psr\SimpleCache\InvalidArgumentException;
  15. use qiniu\basic\BaseServices;
  16. //use app\webscoket\SocketPush;
  17. use qiniu\exceptions\AdminException;
  18. use qiniu\exceptions\AuthException;
  19. use qiniu\services\CacheService;
  20. use qiniu\services\SystemConfigService;
  21. use qiniu\utils\ApiErrorCode;
  22. use qiniu\utils\JwtAuth;
  23. use think\db\exception\DataNotFoundException;
  24. use think\db\exception\DbException;
  25. use think\db\exception\ModelNotFoundException;
  26. use think\facade\Cache;
  27. use think\Model;
  28. /**
  29. * 管理员service
  30. * Class SystemAdminServices
  31. * @package app\services\system\admin
  32. */
  33. class SystemAdminServices extends BaseServices
  34. {
  35. /**
  36. * SystemAdminServices constructor.
  37. * @param SystemAdmin $model
  38. */
  39. public function __construct(SystemAdmin $model)
  40. {
  41. $this->model = $model;
  42. }
  43. /**
  44. * 管理员登陆
  45. * @param string $account
  46. * @param string $password
  47. * @param int $adminType
  48. * @return array|Model
  49. */
  50. public function verifyLogin(string $account, string $password, int $adminType = 1)
  51. {
  52. $key = 'login_captcha_' . $account;
  53. $adminInfo = $this->accountByAdmin($account, $adminType);
  54. if (!$adminInfo) {
  55. Cache::inc($key);
  56. throw new AdminException('管理员不存在!');
  57. }
  58. if (!$adminInfo->status) {
  59. Cache::inc($key);
  60. throw new AdminException('您已被禁止登录!');
  61. }
  62. if (!password_verify($password, $adminInfo->pwd)) {
  63. Cache::inc($key);
  64. throw new AdminException('账号或密码错误,请重新输入');
  65. }
  66. $adminInfo->last_time = time();
  67. $adminInfo->last_ip = app('request')->ip();
  68. $adminInfo->login_count++;
  69. $adminInfo->save();
  70. return $adminInfo;
  71. }
  72. /**
  73. * 后台登陆获取菜单获取token
  74. * @param string $account
  75. * @param string $password
  76. * @param string $type
  77. * @return array
  78. * @throws DbException
  79. * @throws DataNotFoundException
  80. * @throws ModelNotFoundException
  81. */
  82. public function login(string $account, string $password, string $type)
  83. {
  84. $adminInfo = $this->verifyLogin($account, $password);
  85. $tokenInfo = $this->createToken($adminInfo->id, $type, $adminInfo['pwd']);
  86. /** @var SystemMenusServices $services */
  87. $services = app()->make(SystemMenusServices::class);
  88. [$menus, $uniqueAuth] = $services->getMenusList($adminInfo['roles'], (int)$adminInfo['level']);
  89. $data = SystemConfigService::more(['site_logo', 'site_logo_square','site_name']);
  90. return [
  91. 'token' => $tokenInfo['token'],
  92. 'expires_time' => $tokenInfo['params']['exp'],
  93. 'menus' => $menus,
  94. 'unique_auth' => $uniqueAuth,
  95. 'user_info' => [
  96. 'id' => $adminInfo['id'],
  97. 'account' => $adminInfo['account'],
  98. 'real_name' => $adminInfo['real_name'],
  99. 'head_pic' => $adminInfo['head_pic'],
  100. ],
  101. 'logo' => $data['site_logo'],
  102. 'site_name' => $data['site_name'],
  103. 'logo_square' => $data['site_logo_square'],
  104. 'prefix' => config('admin.admin_prefix')
  105. ];
  106. }
  107. /**
  108. * 获取Admin授权信息
  109. * @param string $token
  110. * @return array
  111. * @throws DataNotFoundException
  112. * @throws DbException
  113. * @throws InvalidArgumentException
  114. * @throws ModelNotFoundException
  115. */
  116. public function parseToken(string $token): array
  117. {
  118. /** @var CacheService $cacheService */
  119. $cacheService = app()->make(CacheService::class);
  120. if (!$token || $token === 'undefined') {
  121. throw new AuthException(ApiErrorCode::ERR_LOGIN);
  122. }
  123. /** @var JwtAuth $jwtAuth */
  124. $jwtAuth = app()->make(JwtAuth::class);
  125. //设置解析token
  126. [$id, $type, $auth] = $jwtAuth->parseToken($token);
  127. //检测token是否过期
  128. $md5Token = md5($token);
  129. if (!$cacheService->hasToken($md5Token) || !($cacheToken = $cacheService->getTokenBucket($md5Token))) {
  130. throw new AuthException(ApiErrorCode::ERR_LOGIN);
  131. }
  132. //是否超出有效次数
  133. if (isset($cacheToken['invalidNum']) && $cacheToken['invalidNum'] >= 3) {
  134. if (!request()->isCli()) {
  135. $cacheService->clearToken($md5Token);
  136. }
  137. throw new AuthException(ApiErrorCode::ERR_LOGIN_INVALID);
  138. }
  139. //验证token
  140. try {
  141. $jwtAuth->verifyToken();
  142. $cacheService->setTokenBucket($md5Token, $cacheToken, $cacheToken['exp']);
  143. } catch (ExpiredException $e) {
  144. $cacheToken['invalidNum'] = isset($cacheToken['invalidNum']) ? $cacheToken['invalidNum']++ : 1;
  145. $cacheService->setTokenBucket($md5Token, $cacheToken, $cacheToken['exp']);
  146. } catch (\Throwable $e) {
  147. if (!request()->isCli()) {
  148. $cacheService->clearToken($md5Token);
  149. }
  150. throw new AuthException(ApiErrorCode::ERR_LOGIN_INVALID);
  151. }
  152. //获取管理员信息
  153. $adminInfo = $this->model->get($id);
  154. if (!$adminInfo || !$adminInfo->id) {
  155. if (!request()->isCli()) {
  156. $cacheService->clearToken($md5Token);
  157. }
  158. throw new AuthException(ApiErrorCode::ERR_LOGIN_STATUS);
  159. }
  160. //修改密码后token立刻过期
  161. if ($auth !== md5($adminInfo['pwd'])) {
  162. throw new AuthException(ApiErrorCode::ERR_LOGIN_STATUS);
  163. }
  164. $adminInfo->type = $type;
  165. return $adminInfo->hidden(['pwd', 'status'])->toArray();
  166. }
  167. /**
  168. * 管理员列表
  169. * @param array $where
  170. * @return array
  171. */
  172. public function getAdminList(array $where)
  173. {
  174. [$page, $limit] = $this->getPageValue();
  175. $list = $this->getList($where,'*', $page, $limit);
  176. $count = $this->getCount($where);
  177. /** @var SystemRoleServices $service */
  178. $service = app()->make(SystemRoleServices::class);
  179. $allRole = $service->getRoleArray(['type' => 0]);
  180. foreach ($list as &$item) {
  181. if ($item['roles']) {
  182. $roles = [];
  183. foreach ($item['roles'] as $id) {
  184. if (isset($allRole[$id])) $roles[] = $allRole[$id];
  185. }
  186. if ($roles) {
  187. $item['roles'] = implode(',', $roles);
  188. } else {
  189. $item['roles'] = '';
  190. }
  191. }
  192. $item['_add_time'] = date('Y-m-d H:i:s', $item['add_time']);
  193. $item['_last_time'] = $item['last_time'] ? date('Y-m-d H:i:s', $item['last_time']) : '';
  194. }
  195. return compact('list', 'count');
  196. }
  197. /**
  198. * 创建管理员
  199. * @param array $data
  200. * @return bool
  201. * @throws DbException
  202. */
  203. public function create(array $data)
  204. {
  205. if ($data['conf_pwd'] != $data['pwd']) {
  206. throw new AdminException('两次输入的密码不相同');
  207. }
  208. unset($data['conf_pwd']);
  209. if ($this->model->be(['account' => $data['account'], 'admin_type' => $data['admin_type'] ?? 1])) {
  210. throw new AdminException('管理员账号已存在');
  211. }
  212. if ($this->model->be(['phone' => $data['phone'], 'admin_type' => $data['admin_type'] ?? 1])) {
  213. throw new AdminException('管理员电话已存在');
  214. }
  215. $data['pwd'] = $this->passwordHash($data['pwd']);
  216. $data['add_time'] = time();
  217. $data['roles'] = implode(',', $data['roles']);
  218. return $this->transaction(function () use ($data) {
  219. if ($this->model->save($data)) {
  220. CacheService::clear();
  221. return true;
  222. } else {
  223. throw new AdminException('添加失败');
  224. }
  225. });
  226. }
  227. /**
  228. * 修改管理员
  229. * @param int $id
  230. * @param array $data
  231. * @return bool
  232. * @throws DbException
  233. * @throws DataNotFoundException
  234. * @throws ModelNotFoundException
  235. */
  236. public function save(int $id, array $data)
  237. {
  238. if (!$adminInfo = $this->model->get($id)) {
  239. throw new AdminException('管理员不存在,无法修改');
  240. }
  241. //修改密码
  242. if ($data['pwd']) {
  243. if (!$data['conf_pwd']) {
  244. throw new AdminException('请输入确认密码');
  245. }
  246. if ($data['conf_pwd'] != $data['pwd']) {
  247. throw new AdminException('上次输入的密码不相同');
  248. }
  249. $adminInfo->pwd = $this->passwordHash($data['pwd']);
  250. }
  251. //修改账号
  252. if (isset($data['account']) && $data['account'] != $adminInfo->account && $this->model->be(['account' => $data['account'], 'admin_type' => 1])) {
  253. throw new AdminException('管理员账号已存在');
  254. }
  255. if (isset($data['phone']) && $data['phone'] != $adminInfo->phone && $this->model->be(['phone' => $data['phone'], 'admin_type' => 1])) {
  256. throw new AdminException('管理员电话已存在');
  257. }
  258. if (isset($data['roles'])) {
  259. $adminInfo->roles = implode(',', $data['roles']);
  260. }
  261. $adminInfo->real_name = $data['real_name'] ?? $adminInfo->real_name;
  262. $adminInfo->phone = $data['phone'] ?? $adminInfo->phone;
  263. $adminInfo->account = $data['account'] ?? $adminInfo->account;
  264. $adminInfo->head_pic = $data['head_pic'] ?? $adminInfo->head_pic;
  265. $adminInfo->status = $data['status'];
  266. if ($adminInfo->save()) {
  267. CacheService::clear();
  268. return true;
  269. } else {
  270. return false;
  271. }
  272. }
  273. /**
  274. * 修改当前管理员信息
  275. * @param int $id
  276. * @param array $data
  277. * @return bool
  278. * @throws DbException
  279. * @throws InvalidArgumentException
  280. * @throws DataNotFoundException
  281. * @throws ModelNotFoundException
  282. */
  283. public function updateAdmin(int $id, array $data)
  284. {
  285. $adminInfo = $this->model->get($id);
  286. if (!$adminInfo)
  287. throw new AdminException('管理员信息未查到');
  288. if ($data['head_pic'] != '') {
  289. $adminInfo->head_pic = $data['head_pic'];
  290. } elseif ($data['real_name'] != '') {
  291. $adminInfo->real_name = $data['real_name'];
  292. } elseif ($data['pwd'] != '') {
  293. if (!password_verify($data['pwd'], $adminInfo['pwd']))
  294. throw new AdminException('原始密码错误');
  295. if (!$data['new_pwd'])
  296. throw new AdminException('请输入新密码');
  297. if (!$data['conf_pwd'])
  298. throw new AdminException('请输入确认密码');
  299. if ($data['new_pwd'] != $data['conf_pwd'])
  300. throw new AdminException('两次输入的密码不一致');
  301. $adminInfo->pwd = $this->passwordHash($data['new_pwd']);
  302. } elseif ($data['phone'] != '') {
  303. check_sms_captcha($data['phone'], 'admin_update', $data['code']);
  304. $adminInfo->phone = $data['phone'];
  305. }
  306. if ($adminInfo->save()) {
  307. CacheService::delete('code_' . $data['phone']);
  308. return true;
  309. } else {
  310. return false;
  311. }
  312. }
  313. // /**
  314. // * 后台订单下单,评论,支付成功,后台消息提醒
  315. // */
  316. // public function adminNewPush()
  317. // {
  318. // try {
  319. // /** @var StoreOrderServices $orderServices */
  320. // $orderServices = app()->make(StoreOrderServices::class);
  321. // $data['ordernum'] = $orderServices->count(['is_del' => 0, 'status' => 1, 'shipping_type' => 1]);
  322. // /** @var StoreProductServices $productServices */
  323. // $productServices = app()->make(StoreProductServices::class);
  324. // $data['inventory'] = $productServices->count(['type' => 5]);
  325. // /** @var StoreProductReplyServices $replyServices */
  326. // $replyServices = app()->make(StoreProductReplyServices::class);
  327. // $data['commentnum'] = $replyServices->count(['is_reply' => 0]);
  328. // /** @var UserExtractServices $extractServices */
  329. // $extractServices = app()->make(UserExtractServices::class);
  330. // $data['reflectnum'] = $extractServices->getCount(['status' => 0]);//提现
  331. // $data['msgcount'] = intval($data['ordernum']) + intval($data['inventory']) + intval($data['commentnum']) + intval($data['reflectnum']);
  332. // SocketPush::admin()->type('ADMIN_NEW_PUSH')->data($data)->push();
  333. // } catch (\Exception $e) {
  334. // }
  335. // }
  336. public function accountByAdmin(string $account, int $adminType)
  337. {
  338. return $this->model->getOne(['account' => $account, 'status' => 1, 'admin_type' => $adminType]);
  339. }
  340. /**
  341. * 获取adminid
  342. * @param int $level
  343. * @return array
  344. */
  345. public function getAdminIds(int $level)
  346. {
  347. return $this->model->where('level', '>=', $level)->column('id', 'id');
  348. }
  349. }