123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382 |
- <?php
- // +----------------------------------------------------------------------
- // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
- // +----------------------------------------------------------------------
- // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
- // +----------------------------------------------------------------------
- // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
- // +----------------------------------------------------------------------
- // | Author: CRMEB Team <admin@crmeb.com>
- // +----------------------------------------------------------------------
- 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');
- }
- }
|