SystemAdminServices.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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']);
  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. 'head_pic' => $adminInfo['head_pic'],
  99. ],
  100. 'logo' => $data['site_logo'],
  101. 'logo_square' => $data['site_logo_square'],
  102. 'prefix' => config('admin.admin_prefix')
  103. ];
  104. }
  105. /**
  106. * 获取Admin授权信息
  107. * @param string $token
  108. * @return array
  109. * @throws DataNotFoundException
  110. * @throws DbException
  111. * @throws InvalidArgumentException
  112. * @throws ModelNotFoundException
  113. */
  114. public function parseToken(string $token): array
  115. {
  116. /** @var CacheService $cacheService */
  117. $cacheService = app()->make(CacheService::class);
  118. if (!$token || $token === 'undefined') {
  119. throw new AuthException(ApiErrorCode::ERR_LOGIN);
  120. }
  121. /** @var JwtAuth $jwtAuth */
  122. $jwtAuth = app()->make(JwtAuth::class);
  123. //设置解析token
  124. [$id, $type, $auth] = $jwtAuth->parseToken($token);
  125. //检测token是否过期
  126. $md5Token = md5($token);
  127. if (!$cacheService->hasToken($md5Token) || !($cacheToken = $cacheService->getTokenBucket($md5Token))) {
  128. throw new AuthException(ApiErrorCode::ERR_LOGIN);
  129. }
  130. //是否超出有效次数
  131. if (isset($cacheToken['invalidNum']) && $cacheToken['invalidNum'] >= 3) {
  132. if (!request()->isCli()) {
  133. $cacheService->clearToken($md5Token);
  134. }
  135. throw new AuthException(ApiErrorCode::ERR_LOGIN_INVALID);
  136. }
  137. //验证token
  138. try {
  139. $jwtAuth->verifyToken();
  140. $cacheService->setTokenBucket($md5Token, $cacheToken, $cacheToken['exp']);
  141. } catch (ExpiredException $e) {
  142. $cacheToken['invalidNum'] = isset($cacheToken['invalidNum']) ? $cacheToken['invalidNum']++ : 1;
  143. $cacheService->setTokenBucket($md5Token, $cacheToken, $cacheToken['exp']);
  144. } catch (\Throwable $e) {
  145. if (!request()->isCli()) {
  146. $cacheService->clearToken($md5Token);
  147. }
  148. throw new AuthException(ApiErrorCode::ERR_LOGIN_INVALID);
  149. }
  150. //获取管理员信息
  151. $adminInfo = $this->model->get($id);
  152. if (!$adminInfo || !$adminInfo->id) {
  153. if (!request()->isCli()) {
  154. $cacheService->clearToken($md5Token);
  155. }
  156. throw new AuthException(ApiErrorCode::ERR_LOGIN_STATUS);
  157. }
  158. //修改密码后token立刻过期
  159. if ($auth !== md5($adminInfo['pwd'])) {
  160. throw new AuthException(ApiErrorCode::ERR_LOGIN_STATUS);
  161. }
  162. $adminInfo->type = $type;
  163. return $adminInfo->hidden(['pwd', 'status'])->toArray();
  164. }
  165. /**
  166. * 管理员列表
  167. * @param array $where
  168. * @return array
  169. */
  170. public function getAdminList(array $where)
  171. {
  172. [$page, $limit] = $this->getPageValue();
  173. $list = $this->getList($where,'*', $page, $limit);
  174. $count = $this->count($where);
  175. /** @var SystemRoleServices $service */
  176. $service = app()->make(SystemRoleServices::class);
  177. $allRole = $service->getRoleArray(['type' => 0]);
  178. foreach ($list as &$item) {
  179. if ($item['roles']) {
  180. $roles = [];
  181. foreach ($item['roles'] as $id) {
  182. if (isset($allRole[$id])) $roles[] = $allRole[$id];
  183. }
  184. if ($roles) {
  185. $item['roles'] = implode(',', $roles);
  186. } else {
  187. $item['roles'] = '';
  188. }
  189. }
  190. $item['_add_time'] = date('Y-m-d H:i:s', $item['add_time']);
  191. $item['_last_time'] = $item['last_time'] ? date('Y-m-d H:i:s', $item['last_time']) : '';
  192. }
  193. return compact('list', 'count');
  194. }
  195. /**
  196. * 创建管理员
  197. * @param array $data
  198. * @return bool
  199. * @throws DbException
  200. */
  201. public function create(array $data)
  202. {
  203. if ($data['conf_pwd'] != $data['pwd']) {
  204. throw new AdminException('两次输入的密码不相同');
  205. }
  206. unset($data['conf_pwd']);
  207. if ($this->model->be(['account' => $data['account'], 'admin_type' => $data['admin_type'] ?? 1])) {
  208. throw new AdminException('管理员账号已存在');
  209. }
  210. if ($this->model->be(['phone' => $data['phone'], 'admin_type' => $data['admin_type'] ?? 1])) {
  211. throw new AdminException('管理员电话已存在');
  212. }
  213. $data['pwd'] = $this->passwordHash($data['pwd']);
  214. $data['add_time'] = time();
  215. $data['roles'] = implode(',', $data['roles']);
  216. return $this->transaction(function () use ($data) {
  217. if ($this->model->save($data)) {
  218. CacheService::clear();
  219. return true;
  220. } else {
  221. throw new AdminException('添加失败');
  222. }
  223. });
  224. }
  225. /**
  226. * 修改管理员
  227. * @param int $id
  228. * @param array $data
  229. * @return bool
  230. * @throws DbException
  231. * @throws DataNotFoundException
  232. * @throws ModelNotFoundException
  233. */
  234. public function save(int $id, array $data)
  235. {
  236. if (!$adminInfo = $this->model->get($id)) {
  237. throw new AdminException('管理员不存在,无法修改');
  238. }
  239. //修改密码
  240. if ($data['pwd']) {
  241. if (!$data['conf_pwd']) {
  242. throw new AdminException('请输入确认密码');
  243. }
  244. if ($data['conf_pwd'] != $data['pwd']) {
  245. throw new AdminException('上次输入的密码不相同');
  246. }
  247. $adminInfo->pwd = $this->passwordHash($data['pwd']);
  248. }
  249. //修改账号
  250. if (isset($data['account']) && $data['account'] != $adminInfo->account && $this->model->be(['account' => $data['account'], 'admin_type' => 1])) {
  251. throw new AdminException('管理员账号已存在');
  252. }
  253. if (isset($data['phone']) && $data['phone'] != $adminInfo->phone && $this->model->be(['phone' => $data['phone'], 'admin_type' => 1])) {
  254. throw new AdminException('管理员电话已存在');
  255. }
  256. if (isset($data['roles'])) {
  257. $adminInfo->roles = implode(',', $data['roles']);
  258. }
  259. $adminInfo->real_name = $data['real_name'] ?? $adminInfo->real_name;
  260. $adminInfo->phone = $data['phone'] ?? $adminInfo->phone;
  261. $adminInfo->account = $data['account'] ?? $adminInfo->account;
  262. $adminInfo->head_pic = $data['head_pic'] ?? $adminInfo->head_pic;
  263. $adminInfo->status = $data['status'];
  264. if ($adminInfo->save()) {
  265. CacheService::clear();
  266. return true;
  267. } else {
  268. return false;
  269. }
  270. }
  271. /**
  272. * 修改当前管理员信息
  273. * @param int $id
  274. * @param array $data
  275. * @return bool
  276. * @throws DbException
  277. * @throws InvalidArgumentException
  278. * @throws DataNotFoundException
  279. * @throws ModelNotFoundException
  280. */
  281. public function updateAdmin(int $id, array $data)
  282. {
  283. $adminInfo = $this->model->get($id);
  284. if (!$adminInfo)
  285. throw new AdminException('管理员信息未查到');
  286. if ($data['head_pic'] != '') {
  287. $adminInfo->head_pic = $data['head_pic'];
  288. } elseif ($data['real_name'] != '') {
  289. $adminInfo->real_name = $data['real_name'];
  290. } elseif ($data['pwd'] != '') {
  291. if (!password_verify($data['pwd'], $adminInfo['pwd']))
  292. throw new AdminException('原始密码错误');
  293. if (!$data['new_pwd'])
  294. throw new AdminException('请输入新密码');
  295. if (!$data['conf_pwd'])
  296. throw new AdminException('请输入确认密码');
  297. if ($data['new_pwd'] != $data['conf_pwd'])
  298. throw new AdminException('两次输入的密码不一致');
  299. $adminInfo->pwd = $this->passwordHash($data['new_pwd']);
  300. } elseif ($data['phone'] != '') {
  301. $verifyCode = CacheService::get('code_' . $data['phone']);
  302. if (!$verifyCode)
  303. throw new AdminException('请先获取验证码');
  304. $verifyCode = substr($verifyCode, 0, 6);
  305. if ($verifyCode != $data['code']) {
  306. CacheService::delete('code_' . $data['phone']);
  307. throw new AdminException('验证码错误');
  308. }
  309. $adminInfo->phone = $data['phone'];
  310. }
  311. if ($adminInfo->save()) {
  312. CacheService::delete('code_' . $data['phone']);
  313. return true;
  314. } else {
  315. return false;
  316. }
  317. }
  318. // /**
  319. // * 后台订单下单,评论,支付成功,后台消息提醒
  320. // */
  321. // public function adminNewPush()
  322. // {
  323. // try {
  324. // /** @var StoreOrderServices $orderServices */
  325. // $orderServices = app()->make(StoreOrderServices::class);
  326. // $data['ordernum'] = $orderServices->count(['is_del' => 0, 'status' => 1, 'shipping_type' => 1]);
  327. // /** @var StoreProductServices $productServices */
  328. // $productServices = app()->make(StoreProductServices::class);
  329. // $data['inventory'] = $productServices->count(['type' => 5]);
  330. // /** @var StoreProductReplyServices $replyServices */
  331. // $replyServices = app()->make(StoreProductReplyServices::class);
  332. // $data['commentnum'] = $replyServices->count(['is_reply' => 0]);
  333. // /** @var UserExtractServices $extractServices */
  334. // $extractServices = app()->make(UserExtractServices::class);
  335. // $data['reflectnum'] = $extractServices->getCount(['status' => 0]);//提现
  336. // $data['msgcount'] = intval($data['ordernum']) + intval($data['inventory']) + intval($data['commentnum']) + intval($data['reflectnum']);
  337. // SocketPush::admin()->type('ADMIN_NEW_PUSH')->data($data)->push();
  338. // } catch (\Exception $e) {
  339. // }
  340. // }
  341. public function accountByAdmin(string $account, int $adminType)
  342. {
  343. return $this->model->getOne(['account' => $account, 'status' => 1, 'admin_type' => $adminType]);
  344. }
  345. /**
  346. * 获取adminid
  347. * @param int $level
  348. * @return array
  349. */
  350. public function getAdminIds(int $level)
  351. {
  352. return $this->model->where('level', '>=', $level)->column('id', 'id');
  353. }
  354. }