// +---------------------------------------------------------------------- namespace app\services\system\admin; use app\model\system\admin\SystemAdmin; use Firebase\JWT\ExpiredException; use Psr\SimpleCache\InvalidArgumentException; use qiniu\basic\BaseServices; //use app\webscoket\SocketPush; use qiniu\exceptions\AdminException; use qiniu\exceptions\AuthException; use qiniu\services\CacheService; use qiniu\services\SystemConfigService; use qiniu\utils\ApiErrorCode; use qiniu\utils\JwtAuth; use think\db\exception\DataNotFoundException; use think\db\exception\DbException; use think\db\exception\ModelNotFoundException; use think\facade\Cache; use think\Model; /** * 管理员service * Class SystemAdminServices * @package app\services\system\admin */ class SystemAdminServices extends BaseServices { /** * SystemAdminServices constructor. * @param SystemAdmin $model */ public function __construct(SystemAdmin $model) { $this->model = $model; } /** * 管理员登陆 * @param string $account * @param string $password * @param int $adminType * @return array|Model */ public function verifyLogin(string $account, string $password, int $adminType = 1) { $key = 'login_captcha_' . $account; $adminInfo = $this->accountByAdmin($account, $adminType); if (!$adminInfo) { Cache::inc($key); throw new AdminException('管理员不存在!'); } if (!$adminInfo->status) { Cache::inc($key); throw new AdminException('您已被禁止登录!'); } if (!password_verify($password, $adminInfo->pwd)) { Cache::inc($key); throw new AdminException('账号或密码错误,请重新输入'); } $adminInfo->last_time = time(); $adminInfo->last_ip = app('request')->ip(); $adminInfo->login_count++; $adminInfo->save(); return $adminInfo; } /** * 后台登陆获取菜单获取token * @param string $account * @param string $password * @param string $type * @return array * @throws DbException * @throws DataNotFoundException * @throws ModelNotFoundException */ public function login(string $account, string $password, string $type) { $adminInfo = $this->verifyLogin($account, $password); $tokenInfo = $this->createToken($adminInfo->id, $type, $adminInfo['pwd']); /** @var SystemMenusServices $services */ $services = app()->make(SystemMenusServices::class); [$menus, $uniqueAuth] = $services->getMenusList($adminInfo['roles'], (int)$adminInfo['level']); $data = SystemConfigService::more(['site_logo', 'site_logo_square','site_name']); return [ 'token' => $tokenInfo['token'], 'expires_time' => $tokenInfo['params']['exp'], 'menus' => $menus, 'unique_auth' => $uniqueAuth, 'user_info' => [ 'id' => $adminInfo['id'], 'account' => $adminInfo['account'], 'real_name' => $adminInfo['real_name'], 'head_pic' => $adminInfo['head_pic'], ], 'logo' => $data['site_logo'], 'site_name' => $data['site_name'], 'logo_square' => $data['site_logo_square'], 'prefix' => config('admin.admin_prefix') ]; } /** * 获取Admin授权信息 * @param string $token * @return array * @throws DataNotFoundException * @throws DbException * @throws InvalidArgumentException * @throws ModelNotFoundException */ public function parseToken(string $token): array { /** @var CacheService $cacheService */ $cacheService = app()->make(CacheService::class); if (!$token || $token === 'undefined') { throw new AuthException(ApiErrorCode::ERR_LOGIN); } /** @var JwtAuth $jwtAuth */ $jwtAuth = app()->make(JwtAuth::class); //设置解析token [$id, $type, $auth] = $jwtAuth->parseToken($token); //检测token是否过期 $md5Token = md5($token); if (!$cacheService->hasToken($md5Token) || !($cacheToken = $cacheService->getTokenBucket($md5Token))) { throw new AuthException(ApiErrorCode::ERR_LOGIN); } //是否超出有效次数 if (isset($cacheToken['invalidNum']) && $cacheToken['invalidNum'] >= 3) { if (!request()->isCli()) { $cacheService->clearToken($md5Token); } throw new AuthException(ApiErrorCode::ERR_LOGIN_INVALID); } //验证token try { $jwtAuth->verifyToken(); $cacheService->setTokenBucket($md5Token, $cacheToken, $cacheToken['exp']); } catch (ExpiredException $e) { $cacheToken['invalidNum'] = isset($cacheToken['invalidNum']) ? $cacheToken['invalidNum']++ : 1; $cacheService->setTokenBucket($md5Token, $cacheToken, $cacheToken['exp']); } catch (\Throwable $e) { if (!request()->isCli()) { $cacheService->clearToken($md5Token); } throw new AuthException(ApiErrorCode::ERR_LOGIN_INVALID); } //获取管理员信息 $adminInfo = $this->model->get($id); if (!$adminInfo || !$adminInfo->id) { if (!request()->isCli()) { $cacheService->clearToken($md5Token); } throw new AuthException(ApiErrorCode::ERR_LOGIN_STATUS); } //修改密码后token立刻过期 if ($auth !== md5($adminInfo['pwd'])) { throw new AuthException(ApiErrorCode::ERR_LOGIN_STATUS); } $adminInfo->type = $type; return $adminInfo->hidden(['pwd', 'status'])->toArray(); } /** * 管理员列表 * @param array $where * @return array */ public function getAdminList(array $where) { [$page, $limit] = $this->getPageValue(); $list = $this->getList($where,'*', $page, $limit); $count = $this->getCount($where); /** @var SystemRoleServices $service */ $service = app()->make(SystemRoleServices::class); $allRole = $service->getRoleArray(['type' => 0]); foreach ($list as &$item) { if ($item['roles']) { $roles = []; foreach ($item['roles'] as $id) { if (isset($allRole[$id])) $roles[] = $allRole[$id]; } if ($roles) { $item['roles'] = implode(',', $roles); } else { $item['roles'] = ''; } } $item['_add_time'] = date('Y-m-d H:i:s', $item['add_time']); $item['_last_time'] = $item['last_time'] ? date('Y-m-d H:i:s', $item['last_time']) : ''; } return compact('list', 'count'); } /** * 创建管理员 * @param array $data * @return bool * @throws DbException */ public function create(array $data) { if ($data['conf_pwd'] != $data['pwd']) { throw new AdminException('两次输入的密码不相同'); } unset($data['conf_pwd']); if ($this->model->be(['account' => $data['account'], 'admin_type' => $data['admin_type'] ?? 1])) { throw new AdminException('管理员账号已存在'); } if ($this->model->be(['phone' => $data['phone'], 'admin_type' => $data['admin_type'] ?? 1])) { throw new AdminException('管理员电话已存在'); } $data['pwd'] = $this->passwordHash($data['pwd']); $data['add_time'] = time(); $data['roles'] = implode(',', $data['roles']); return $this->transaction(function () use ($data) { if ($this->model->save($data)) { CacheService::clear(); return true; } else { throw new AdminException('添加失败'); } }); } /** * 修改管理员 * @param int $id * @param array $data * @return bool * @throws DbException * @throws DataNotFoundException * @throws ModelNotFoundException */ public function save(int $id, array $data) { if (!$adminInfo = $this->model->get($id)) { throw new AdminException('管理员不存在,无法修改'); } //修改密码 if ($data['pwd']) { if (!$data['conf_pwd']) { throw new AdminException('请输入确认密码'); } if ($data['conf_pwd'] != $data['pwd']) { throw new AdminException('上次输入的密码不相同'); } $adminInfo->pwd = $this->passwordHash($data['pwd']); } //修改账号 if (isset($data['account']) && $data['account'] != $adminInfo->account && $this->model->be(['account' => $data['account'], 'admin_type' => 1])) { throw new AdminException('管理员账号已存在'); } if (isset($data['phone']) && $data['phone'] != $adminInfo->phone && $this->model->be(['phone' => $data['phone'], 'admin_type' => 1])) { throw new AdminException('管理员电话已存在'); } if (isset($data['roles'])) { $adminInfo->roles = implode(',', $data['roles']); } $adminInfo->real_name = $data['real_name'] ?? $adminInfo->real_name; $adminInfo->phone = $data['phone'] ?? $adminInfo->phone; $adminInfo->account = $data['account'] ?? $adminInfo->account; $adminInfo->head_pic = $data['head_pic'] ?? $adminInfo->head_pic; $adminInfo->status = $data['status']; if ($adminInfo->save()) { CacheService::clear(); return true; } else { return false; } } /** * 修改当前管理员信息 * @param int $id * @param array $data * @return bool * @throws DbException * @throws InvalidArgumentException * @throws DataNotFoundException * @throws ModelNotFoundException */ public function updateAdmin(int $id, array $data) { $adminInfo = $this->model->get($id); if (!$adminInfo) throw new AdminException('管理员信息未查到'); if ($data['head_pic'] != '') { $adminInfo->head_pic = $data['head_pic']; } elseif ($data['real_name'] != '') { $adminInfo->real_name = $data['real_name']; } elseif ($data['pwd'] != '') { if (!password_verify($data['pwd'], $adminInfo['pwd'])) throw new AdminException('原始密码错误'); if (!$data['new_pwd']) throw new AdminException('请输入新密码'); if (!$data['conf_pwd']) throw new AdminException('请输入确认密码'); if ($data['new_pwd'] != $data['conf_pwd']) throw new AdminException('两次输入的密码不一致'); $adminInfo->pwd = $this->passwordHash($data['new_pwd']); } elseif ($data['phone'] != '') { check_sms_captcha($data['phone'], 'admin_update', $data['code']); $adminInfo->phone = $data['phone']; } if ($adminInfo->save()) { CacheService::delete('code_' . $data['phone']); return true; } else { return false; } } // /** // * 后台订单下单,评论,支付成功,后台消息提醒 // */ // public function adminNewPush() // { // try { // /** @var StoreOrderServices $orderServices */ // $orderServices = app()->make(StoreOrderServices::class); // $data['ordernum'] = $orderServices->count(['is_del' => 0, 'status' => 1, 'shipping_type' => 1]); // /** @var StoreProductServices $productServices */ // $productServices = app()->make(StoreProductServices::class); // $data['inventory'] = $productServices->count(['type' => 5]); // /** @var StoreProductReplyServices $replyServices */ // $replyServices = app()->make(StoreProductReplyServices::class); // $data['commentnum'] = $replyServices->count(['is_reply' => 0]); // /** @var UserExtractServices $extractServices */ // $extractServices = app()->make(UserExtractServices::class); // $data['reflectnum'] = $extractServices->getCount(['status' => 0]);//提现 // $data['msgcount'] = intval($data['ordernum']) + intval($data['inventory']) + intval($data['commentnum']) + intval($data['reflectnum']); // SocketPush::admin()->type('ADMIN_NEW_PUSH')->data($data)->push(); // } catch (\Exception $e) { // } // } public function accountByAdmin(string $account, int $adminType) { return $this->model->getOne(['account' => $account, 'status' => 1, 'admin_type' => $adminType]); } /** * 获取adminid * @param int $level * @return array */ public function getAdminIds(int $level) { return $this->model->where('level', '>=', $level)->column('id', 'id'); } }