diff --git a/app/AdminController.php b/app/AdminController.php index 1c59c8d..778d1c1 100644 --- a/app/AdminController.php +++ b/app/AdminController.php @@ -11,54 +11,26 @@ namespace app; use app\admin\library\Auth; +use support\Log; use support\Response; use think\helper\Str; + define('AdminSession', 'AdminLogin'); + class AdminController extends BaseController { - /** * 数据库实例 * @var object */ public object $model; - /** - * 是否验证 - * @var bool - */ - public bool $isValidate = true; - - /** - * 验证场景 - * @var string - */ - public string $scene = ''; - /** * 数据表名称 * @var string */ public string $tableName; - /** - * 控制器/类名 - * @var string - */ - public string $controller; - - /** - * 控制器方法 - * @var string - */ - public string $action; - - /** - * 控制器/方法名 - * @var string - */ - public string $method; - /** * 操作状态 * @var mixed @@ -67,7 +39,6 @@ class AdminController extends BaseController /** * 获取模板 - * @access protected * @var string */ public string $template = ''; @@ -80,49 +51,42 @@ class AdminController extends BaseController /** * 当前表字段 - * * @var array */ protected array $tableFields = []; /** * 默认开关 - * * @var string */ protected string $keepField = 'status'; /** * 开启数据限制 - * 默认关闭 * @var boolean */ protected bool $dataLimit = false; /** * 数据限制字段 - * * @var string */ protected string $dataLimitField = 'admin_id'; /** * 需要排除的字段 - * * @var mixed */ protected mixed $ruleOutFields = ''; /** * 查询过滤字段 - * * @var array */ protected array $filterWhere = ['page', 'limit']; /** * 查询转换字段 - * * @var array */ protected array $converTime = ['create_time', 'update_time', 'delete_time']; @@ -143,14 +107,14 @@ class AdminController extends BaseController } /** - * 获取资源 + * 获取资源列表 * @return Response|void */ public function index() { if (request()->isAjax()) { $page = (int)input('page', 1); - $limit = (int)input('limit',18); + $limit = (int)input('limit', 18); $where = $this->buildSelectParams(); $count = $this->model->where($where)->count(); $limit = is_empty($limit) ? 10 : $limit; @@ -168,11 +132,13 @@ class AdminController extends BaseController if (!empty($localKey) && !empty($bind)) { $relation[] = $method->getName(); $expBind = explode(',', $bind[1]); - $relListKey[] = ['key'=>$localKey[1], 'value'=>$expBind[0]]; + $relListKey[] = ['key' => $localKey[1], 'value' => $expBind[0]]; } } - } catch (\ReflectionException $e) {} - $subQuery = $this->model->field('id')->where($where)->order($order, 'desc')->limit((int)$limit)->page((int)$page)->buildSql(); + } catch (\Throwable $th) { + Log::info($th->getMessage()); + } + $subQuery = $this->model->field('id')->where($where)->order($order, 'desc')->limit($limit)->page($page)->buildSql(); $subQuery = '( SELECT object.id FROM ' . $subQuery . ' AS object )'; $list = $this->model->with($relation)->where('id in' . $subQuery)->order($order, 'desc')->select()->toArray(); foreach ($list as $key => $value) { @@ -198,7 +164,7 @@ class AdminController extends BaseController $post = $this->preRuleOutFields(\request()->post()); if ($this->dataLimit) { - $post[$this->dataLimitField] = request()->adminData['id']; + $post[$this->dataLimitField] = get_admin_id(); } $validate = $this->isValidate ? get_class($this->model) : $this->isValidate; @@ -226,7 +192,7 @@ class AdminController extends BaseController // 限制数据调用 if (!$this->auth->SuperAdmin() && $this->dataLimit && in_array($this->dataLimitField, $this->model->getFields())) { - if ($data[$this->dataLimitField] != request()->adminData['id']) { + if ($data[$this->dataLimitField] != get_admin_id()) { return $this->error('没有权限'); } } @@ -266,7 +232,7 @@ class AdminController extends BaseController foreach ($list as $item) { if (!$this->auth->SuperAdmin() && $this->dataLimit && in_array($this->dataLimitField, $this->model->getFields())) { - if ($item[$this->dataLimitField] != request()->adminData['id']) { + if ($item[$this->dataLimitField] != get_admin_id()) { continue; } } @@ -296,7 +262,7 @@ class AdminController extends BaseController $where[] = ['id', '=', input('id')]; if (!$this->auth->SuperAdmin() && $this->dataLimit && in_array($this->dataLimitField, $this->model->getFields())) { - $where[] = [$this->dataLimitField, '=',request()->adminData['id']]; + $where[] = [$this->dataLimitField, '=', get_admin_id()]; } try { @@ -315,7 +281,7 @@ class AdminController extends BaseController /** * 数据表排序 - * @return Response|void + * @return Response */ public function sort() { @@ -396,7 +362,6 @@ class AdminController extends BaseController /** * 获取查询参数 - * @return mixed|void */ protected function buildSelectParams() { @@ -522,7 +487,7 @@ class AdminController extends BaseController // 限制数据字段 if (!$this->auth->SuperAdmin() && $this->dataLimit) { if (in_array($this->dataLimitField, $this->tableFields)) { - $where[] = [$this->dataLimitField, '=', request()->adminData['id']]; + $where[] = [$this->dataLimitField, '=', get_admin_id()]; } } diff --git a/app/BaseController.php b/app/BaseController.php index 5db2aa3..2a3b8df 100644 --- a/app/BaseController.php +++ b/app/BaseController.php @@ -1,5 +1,5 @@ parseClass('validate', $validate); - $v = new $class(); + $class = str_contains($validate, '\\') ? $validate : $this->parseClass('validate', $validate); + $v = new $class(); if (!empty($scene)) { $v->scene($scene); } @@ -132,23 +94,23 @@ class BaseController * 解析应用类的类名 * @access public * @param string $layer 层名 controller model ... - * @param string $name 类名 + * @param string $name 类名 * @return string */ protected function parseClass(string $layer, string $name): string { - $name = str_replace(['/', '.'], '\\', $name); + $name = str_replace(['/', '.'], '\\', $name); $array = explode('\\', $name); $class = Str::studly(array_pop($array)); - $path = $array ? implode('\\', $array) . '\\' : ''; - return 'app'. '\\' . $layer . '\\' . $path . $class; + $path = $array ? implode('\\', $array) . '\\' : ''; + return 'app' . '\\' . $layer . '\\' . $path . $class; } /** * 操作成功跳转的快捷方法 * @access protected * @param mixed $msg 提示信息 - * @param string|null $url 跳转的URL地址 + * @param null $url 跳转的URL地址 * @param mixed $data 返回的数据 * @param int $count * @param int $code @@ -156,7 +118,7 @@ class BaseController * @param array $header 发送的Header信息 * @return Response */ - protected function success($msg = '', string $url = null, $data = '', int $count = 0, int $code = 200, int $wait = 3, array $header = []): Response + protected function success(mixed $msg = '', $url = null, mixed $data = '', int $count = 0, int $code = 200, int $wait = 3, array $header = []): Response { if (is_null($url) && isset($_SERVER["HTTP_REFERER"])) { $url = $_SERVER["HTTP_REFERER"]; @@ -191,7 +153,7 @@ class BaseController * @param array $header 发送的Header信息 * @return Response */ - protected function error($msg = '', $url = null, $data = '', int $code = 101, int $wait = 3, array $header = []): Response + protected function error(mixed $msg = '', $url = null, mixed $data = '', int $code = 101, int $wait = 3, array $header = []): Response { if (is_null($url)) { $url = request()->isAjax() ? '' : 'javascript:history.back(-1);'; @@ -254,9 +216,7 @@ class BaseController /** * 获取模型字段集 - * @access protected - * @param $model - * @return mixed + * @param null $model */ protected function getTableFields($model = null) { @@ -301,6 +261,7 @@ class BaseController if (strtolower($captcha) !== \request()->session()->get('captcha')) { return false; } + return true; } } \ No newline at end of file diff --git a/app/HomeController.php b/app/HomeController.php index dda2d2b..42e5cbe 100644 --- a/app/HomeController.php +++ b/app/HomeController.php @@ -33,30 +33,6 @@ class HomeController extends BaseController */ public object $model; - /** - * 是否验证 - * @var bool - */ - public bool $isValidate = true; - - /** - * 验证场景 - * @var string - */ - public string $scene = ''; - - /** - * 控制器/类名 - * @var string - */ - public string $controller; - - /** - * 控制器方法 - * @var string - */ - public string $action; - /** * 操作状态 * @var mixed @@ -98,6 +74,7 @@ class HomeController extends BaseController * @var string */ public string $JumpUrl = '/user/index'; + /** * 初始化函数 */ diff --git a/app/admin/controller/Login.php b/app/admin/controller/Login.php index e9e0fe7..b3318a1 100644 --- a/app/admin/controller/Login.php +++ b/app/admin/controller/Login.php @@ -37,57 +37,45 @@ class Login extends AdminController public function index(): \support\Response { // 禁止重复访问 - if (isset(request()->adminData['id'])) { + $session = get_admin_info(); + if (isset($session['id'])) { return $this->redirect('/admin/index'); } if (request()->isPost()) { - $user = request()->post('name'); $pwd = request()->post('pwd'); $captcha = request()->post('captcha'); - if ((isset(request()->adminData['count']) - && request()->adminData['count'] >= 5) - && (isset(request()->adminData['time']) - && request()->adminData['time'] >= strtotime('- 5 minutes')) - ) { - $error = '错误次数过多,请稍后再试!'; - $this->writeLoginLogs($error); - return $this->error($error); + if ((isset($session['count']) && $session['count'] >= 5) + && (isset($session['time']) && $session['time'] >= strtotime('- 5 minutes'))) { + return $this->displayResponse('错误次数过多,请稍后再试!'); } // 验证码 - if (isset(request()->adminData['isCaptcha'])) { + if (isset($session['isCaptcha'])) { if (!$captcha || !$this->captchaCheck($captcha)) { - $error = '验证码错误!'; - $this->writeLoginLogs($error); - return $this->error($error); + return $this->displayResponse('验证码错误!'); } } // 验证表单令牌 - if (!request()->checkToken('__token__', \request()->all())) { - $error = '表单令牌错误!'; - $this->writeLoginLogs($error); - return $this->error($error, '', ['token' => token()]); + if (!request()->checkToken('__token__', request()->all())) { + return $this->displayResponse('表单令牌错误!', ['token' => token()]); } else { $result = Admin::checkLogin($user, $pwd); if (empty($result)) { - request()->adminData['time'] = time(); - request()->adminData['isCaptcha'] = true; - request()->adminData['count'] = isset(request()->adminData['count']) ? request()->adminData['count'] + 1 : 1; - request()->session()->set(AdminSession, request()->adminData); - $error = '用户名或密码错误!'; - $this->writeLoginLogs($error); - Event::emit('adminLoginError', \request()->all()); - return $this->error($error, '', ['token' => token()]); + $session['time'] = time(); + $session['isCaptcha'] = true; + $session['count'] = isset($session['count']) ? $session['count'] + 1 : 1; + request()->session()->set(AdminSession, $session); + // 执行登录失败事件 + Event::emit('adminLoginError', request()->all()); + return $this->displayResponse('用户名或密码错误!', ['token' => token()]); } if ($result['status'] !== 1) { - $error = '账号已被禁用!'; - $this->writeLoginLogs($error); - return $this->error($error); + return $this->displayResponse('账号已被禁用!'); } $result->login_ip = request()->getRealIp(); @@ -97,30 +85,41 @@ class Login extends AdminController try { $result->save(); - $session = array_merge(request()->adminData, $result->toArray()); + $session = array_merge($session, $result->toArray()); request()->session()->set(AdminSession, $session); } catch (\Throwable $th) { return $this->error($th->getMessage()); } - $success = '登录成功!'; - $this->writeLoginLogs($success, true); Event::emit('adminLoginSuccess', $result->toArray()); - return $this->success($success, $this->JumpUrl); + return $this->displayResponse('登录成功!', [] , $this->JumpUrl); } } return view('login/index', [ - 'captcha' => request()->adminData['isCaptcha'] ?? false, + 'captcha' => $session['isCaptcha'] ?? false, ]); } + /** + * 退出登录 + * @param string $msg + * @param array $data + * @param string $url + * @return Response + */ + private function displayResponse(string $msg = 'error', array $data = [], string $url = ''): Response + { + $this->adminLoginLog($msg, $url ? 1 : 0); + return empty($url) ? $this->error($msg, $url, $data) : $this->success($msg, $url); + } + /** * 写入登录日志 * @param string $error * @param int $status */ - private function writeLoginLogs(string $error, int $status = 0) + private function adminLoginLog(string $error, int $status = 0) { $name = \request()->input('name'); $userAgent = \request()->header('user-agent'); @@ -131,7 +130,7 @@ class Login extends AdminController $user_os = '未知'; } - $user_browser = preg_replace('/[^(]+\((.*?)[^)]+\) .*?/','$1',$userAgent); + $user_browser = preg_replace('/[^(]+\((.*?)[^)]+\) .*?/', '$1', $userAgent); $data = [ 'user_ip' => request()->getRealIp(), diff --git a/app/admin/controller/system/Admin.php b/app/admin/controller/system/Admin.php index 6e873ba..5d87c0b 100644 --- a/app/admin/controller/system/Admin.php +++ b/app/admin/controller/system/Admin.php @@ -325,7 +325,7 @@ class Admin extends AdminController $page = input('page', 1); $limit = input('limit', 3); // 计算最大页码 - $data = AdminNotice::with(['admin'])->where(['type' => $type, 'admin_id' => \request()->admin_id]) + $data = AdminNotice::with(['admin'])->where(['type' => $type, 'admin_id' => get_admin_id()]) ->order('id', 'desc')->paginate(['list_rows' => $limit, 'page' => $page])->toArray(); return $this->success('获取成功', '', $data); } @@ -333,7 +333,7 @@ class Admin extends AdminController foreach ($array as $item) { $where = [ ['type', '=', $item], - ['admin_id', '=', request()->admin_id] + ['admin_id', '=', get_admin_id()] ]; $count[$item] = AdminNotice::where($where)->where('status', 0)->count(); $list[$item] = AdminNotice::with(['admin'])->withoutField('content')->where($where)->limit(3)->order('id desc')->select()->toArray(); @@ -358,7 +358,7 @@ class Admin extends AdminController $type = input('type', 'notice'); if (!empty($id)) { - $detail = AdminNotice::with(['admin'])->where(['id' => $id, 'admin_id' => \request()->admin_id])->find(); + $detail = AdminNotice::with(['admin'])->where(['id' => $id, 'admin_id' => get_admin_id()])->find(); if (empty($detail)) { return $this->error('404 Not Found'); } @@ -383,7 +383,7 @@ class Admin extends AdminController { if (\request()->post()) { $post = request()->post(); - $post['send_id'] = request()->admin_id; + $post['send_id'] = get_admin_id(); $post['type'] = 'message'; $post['send_ip'] = request()->getRealIp(); $post['create_time'] = time(); @@ -404,7 +404,7 @@ class Admin extends AdminController if (empty($id)) { throw new Exception('参数错误'); } - AdminNotice::where(['id' => $id, 'admin_id' => request()->admin_id])->update(['status' => $status]); + AdminNotice::where(['id' => $id, 'admin_id' => get_admin_id()])->update(['status' => $status]); } catch (Exception $e) { return $this->error('更新失败'); } @@ -424,7 +424,7 @@ class Admin extends AdminController $where = [ ['type', '=', $type], ['status', '=', 1], - ['admin_id', '=', request()->admin_id] + ['admin_id', '=', get_admin_id()] ]; try { AdminNotice::where($where)->delete(); @@ -446,7 +446,7 @@ class Admin extends AdminController $type = input('type', 'notice'); $where = [ ['type', '=', $type], - ['admin_id', '=', request()->admin_id] + ['admin_id', '=', get_admin_id()] ]; try { AdminNotice::where($where)->update(['status' => 1]); @@ -468,10 +468,9 @@ class Admin extends AdminController */ public function center(Request $request): \support\Response { - if (request()->isPost()) { $post = request()->post(); - $post['id'] = $request->admin_id; + $post['id'] = get_admin_id(); if ($this->model->update($post)) { return $this->success(); } @@ -480,7 +479,7 @@ class Admin extends AdminController } $title = []; - $data = $this->model->find($request->admin_id); + $data = $this->model->find(get_admin_id()); if (!empty($data['group_id'])) { $group = AdminGroupModel::field('title') ->whereIn('id', $data['group_id']) @@ -505,7 +504,7 @@ class Admin extends AdminController { if (request()->isAjax()) { $post = request()->post(); - $id = $request->admin_id; + $id = get_admin_id(); try { //code... switch ($post['field']) { @@ -571,7 +570,7 @@ class Admin extends AdminController } // 查找数据 - $where[] = ['id', '=', request()->admin_id]; + $where[] = ['id', '=', get_admin_id()]; $where[] = ['pwd', '=', encryptPwd($pwd)]; $result = $this->model->where($where)->find(); diff --git a/app/admin/controller/system/Plugin.php b/app/admin/controller/system/Plugin.php index 49a5157..5322be6 100644 --- a/app/admin/controller/system/Plugin.php +++ b/app/admin/controller/system/Plugin.php @@ -1,5 +1,6 @@ error('插件名称只能是字母和数字'); } diff --git a/app/admin/library/Auth.php b/app/admin/library/Auth.php index 92b07cb..f81ce42 100644 --- a/app/admin/library/Auth.php +++ b/app/admin/library/Auth.php @@ -103,9 +103,9 @@ class Auth * @param string $mode 执行check的模式 * @param string $relation 如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证 * @return bool 通过验证返回true;失败返回false - * @throws \think\db\exception\DataNotFoundException - * @throws \think\db\exception\DbException - * @throws \think\db\exception\ModelNotFoundException + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function check($name, int $admin_id = 0, int $type = 1, string $mode = 'url', string $relation = 'or'): bool { @@ -203,9 +203,9 @@ class Auth * 获取权限菜单 * @access public * @return mixed - * @throws \think\db\exception\DataNotFoundException - * @throws \think\db\exception\DbException - * @throws \think\db\exception\ModelNotFoundException + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getRulesMenu() { @@ -231,9 +231,9 @@ class Auth * @param $admin_id * @param array $nodes * @return array - * @throws \think\db\exception\DataNotFoundException - * @throws \think\db\exception\DbException - * @throws \think\db\exception\ModelNotFoundException + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function getAuthList($admin_id, array $nodes = []): array { @@ -342,11 +342,11 @@ class Auth /** * 超级管理员 - * @access public - * @return bool - * @throws \think\db\exception\DataNotFoundException - * @throws \think\db\exception\DbException - * @throws \think\db\exception\ModelNotFoundException + * @access public + * @return bool + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function superAdmin(): bool { @@ -363,9 +363,9 @@ class Auth * 管理组分级鉴权 * @param array $groupIDs * @return bool - * @throws \think\db\exception\DataNotFoundException - * @throws \think\db\exception\DbException - * @throws \think\db\exception\ModelNotFoundException + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ public function checkRulesForGroup(array $groupIDs = []): bool { @@ -395,23 +395,22 @@ class Auth * 获取用户信息 * @param $admin_id * @return array - * @throws \think\db\exception\DataNotFoundException - * @throws \think\db\exception\DbException - * @throws \think\db\exception\ModelNotFoundException + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException */ - public function getAdminData($admin_id): array + public function getAdminInfo($admin_id): array { - - $admin_id = $admin_id ?? session('AdminLogin.id'); - static $AdminData = []; + $admin_id = $admin_id ?? get_admin_id(); + static $AdminArray = []; $user = Db::name('admin'); // 获取用户表主键 $_pk = is_string($user->getPk()) ? $user->getPk() : 'id'; - if (!isset($AdminData[$admin_id])) { - $AdminData[$admin_id] = $user->where($_pk, $admin_id)->find(); + if (!isset($AdminArray[$admin_id])) { + $AdminArray[$admin_id] = $user->where($_pk, $admin_id)->find(); } - return $AdminData[$admin_id]; + return $AdminArray[$admin_id]; } /** diff --git a/app/admin/middleware/system/AdminPermissions.php b/app/admin/middleware/system/AdminPermissions.php index a38b1fb..3e89e31 100644 --- a/app/admin/middleware/system/AdminPermissions.php +++ b/app/admin/middleware/system/AdminPermissions.php @@ -41,24 +41,28 @@ class AdminPermissions implements MiddlewareInterface * @throws DataNotFoundException * @throws DbException * @throws InvalidArgumentException - * @throws ModelNotFoundException + * @throws ModelNotFoundException|\ReflectionException */ public function process(Request $request, callable $handler): Response { - $app = request()->getApp(); + $app = request()->getApp(); $controller = request()->getController(); - $action = request()->getAction(); + $action = request()->getAction(); $AdminLogin = request()->session()->get(AdminSession); if (!isset($AdminLogin['id']) && strtolower($controller) !== 'login') { return redirect(url('/login/index')); } - // 判断是否需要鉴权 - $request->admin_id = $AdminLogin['id'] ?? 0; - $request->adminData = $AdminLogin ?? []; - $method = '/' . $controller. '/' .$action; - if (!in_array($method, $this->noNeedAuth) && !in_array('*', $this->noNeedAuth)) { - if (!Auth::instance()->SuperAdmin() && !Auth::instance()->check($method, $request->admin_id)) { + // 获取权限列表 + $class = new \ReflectionClass($request->controller); + $properties = $class->getDefaultProperties(); + $this->noNeedAuth = $properties['noNeedAuth'] ?? $this->noNeedAuth; + + // 控制器鉴权 + $method = '/' . $controller . '/' . $action; + if (!in_array('*', $this->noNeedAuth) + && !in_array(strtolower($method), array_map('strtolower', $this->noNeedAuth))) { + if (!Auth::instance()->SuperAdmin() && !Auth::instance()->check($method, get_admin_id())) { if (request()->isAjax()) { return json(['code' => 101, 'msg' => '没有权限']); } else { @@ -67,9 +71,14 @@ class AdminPermissions implements MiddlewareInterface } } - // 控制器中间件分发 - $id = input('id'); + /** + * Admin应用 + * 控制器权限分发 + */ if (\request()->isPost()) { + + $id = input('id'); + if ($controller == 'system/Admin') { if ($data = AdminModel::getById($id)) { $group_id = input('group_id'); @@ -79,7 +88,9 @@ class AdminPermissions implements MiddlewareInterface return json(ResultCode::AUTH_ERROR); } } - } else if ($controller == 'system/AdminGroup') { + } + + if ($controller == 'system/AdminGroup') { if (!empty($id) && $id >= 1) { if (!Auth::instance()->checkRulesForGroup((array)$id)) { return json(ResultCode::AUTH_ERROR); @@ -88,11 +99,12 @@ class AdminPermissions implements MiddlewareInterface } } + // 分配当前管理员信息 View::assign('app', $app); View::assign('controller', $controller); View::assign('action', $action); View::assign('AdminLogin', $AdminLogin); - $this->writeAdminRequestLogs(); + self::writeAdminRequestLogs(); return $handler($request); } @@ -103,7 +115,7 @@ class AdminPermissions implements MiddlewareInterface * @throws DbException * @throws ModelNotFoundException */ - public function writeAdminRequestLogs() + public static function writeAdminRequestLogs() { if (saenv('system_logs')) { diff --git a/app/admin/view/system/admin/center.html b/app/admin/view/system/admin/center.html index 5a18dcd..825afd5 100644 --- a/app/admin/view/system/admin/center.html +++ b/app/admin/view/system/admin/center.html @@ -160,7 +160,7 @@

{:__('标签')}

-
+
{$vo}
diff --git a/app/api/controller/Ajax.php b/app/api/controller/Ajax.php index e3228ab..c5fbc4e 100644 --- a/app/api/controller/Ajax.php +++ b/app/api/controller/Ajax.php @@ -27,7 +27,6 @@ class Ajax extends ApiController * @return Response|void * @throws DataNotFoundException * @throws DbException - * @throws ModelNotFoundException */ public function smsSend() { @@ -46,10 +45,10 @@ class Ajax extends ApiController return $this->error(__('发送频繁')); } - $userData = User::getByMobile($mobile); - if (in_array($event, ['register', 'changer']) && $userData) { + $user = User::getByMobile($mobile); + if (in_array($event, ['register', 'changer']) && $user) { return $this->error('当前手机号已被占用'); - } else if ($event == 'forgot' && !$userData) { + } else if ($event == 'forgot' && !$user) { return $this->error('当前手机号未注册'); } @@ -89,10 +88,10 @@ class Ajax extends ApiController return $this->error(__('发送频繁')); } - $userData = User::getByEmail($email); - if (in_array($event, ['register', 'changer']) && $userData) { + $user = User::getByEmail($email); + if (in_array($event, ['register', 'changer']) && $user) { return $this->error('当前邮箱已被注册'); - } else if ($event == 'forgot' && !$userData) { + } else if ($event == 'forgot' && !$user) { return $this->error('当前邮箱不存在'); } diff --git a/app/api/middleware/system/ApiPermissions.php b/app/api/middleware/system/ApiPermissions.php index 46dba80..3dd4518 100644 --- a/app/api/middleware/system/ApiPermissions.php +++ b/app/api/middleware/system/ApiPermissions.php @@ -1,4 +1,4 @@ -getApp(); + $app = request()->getApp(); $controller = request()->getController(); - $action = request()->getAction(); - $method = $controller . '/' . $action; - $className = '\app' . $app . '\\controller\\' . $controller; - $className = str_replace('/', '\\', $className); - if (class_exists($className)) { - $refClass = new \ReflectionClass($className); - $property = $refClass->getDefaultProperties(); - $this->needLogin = $property['needLogin'] ?? false; - $this->noNeedAuth = $property['noNeedAuth'] ?? []; - } + $action = request()->getAction(); + $method = $controller . '/' . $action; + + $refClass = new \ReflectionClass($request->controller); + $property = $refClass->getDefaultProperties(); + $this->needLogin = $property['needLogin'] ?? $this->needLogin; + $this->noNeedAuth = $property['noNeedAuth'] ?? $this->noNeedAuth; $auth = Auth::instance(); if ($auth->isLogin()) { - $request->user_id = $auth->userData['id']; - $request->userData = $auth->userData; + // 验证权限 if ($this->authWorkflow && Event::hasListener('apiAuth')) { - $result = Event::emit('apiAuth', ['method' => $method, 'user_id' => $request->user_id], true); + $result = Event::emit('apiAuth', ['method' => $method, 'user_id' => $auth->user_id], true); if (isset($result['code']) && $result['code'] != 200) { return json($result); } diff --git a/app/common/library/Auth.php b/app/common/library/Auth.php index 8dfa2bf..19e7e9c 100644 --- a/app/common/library/Auth.php +++ b/app/common/library/Auth.php @@ -13,8 +13,12 @@ declare(strict_types=1); namespace app\common\library; use app\common\model\system\UserLog; +use Psr\SimpleCache\InvalidArgumentException; use system\Random; use support\Response; +use think\db\exception\DataNotFoundException; +use think\db\exception\DbException; +use think\db\exception\ModelNotFoundException; use think\facade\Cache; use app\common\model\system\User as UserModel; use Webman\Event\Event; @@ -28,11 +32,16 @@ class Auth */ public string $token; + /** + * 用户ID + */ + public int $user_id = 0; + /** * 用户数据 * @var object|array */ - public mixed $userData; + public mixed $userInfo; /** * 保活时间 @@ -79,9 +88,11 @@ class Auth /** * 用户注册 * @param array $post - * @return bool - * @throws \Psr\SimpleCache\InvalidArgumentException - * @throws \think\db\exception\DbException + * @return false|Response + * @throws DataNotFoundException + * @throws DbException + * @throws InvalidArgumentException + * @throws ModelNotFoundException */ public function register(array $post) { @@ -90,10 +101,8 @@ class Auth return false; } - /** - * 禁止批量注册 - */ - $where[] = ['create_ip', '=', ip2long(request()->getRealIp())]; + // 禁止批量注册 + $where[] = ['create_ip', '=', request()->getRealIp()]; $where[] = ['create_time', '>', linux_extime(1)]; $totalMax = UserModel::where($where)->count(); @@ -128,24 +137,24 @@ class Auth $post['pwd'] = encryptPwd($post['pwd'], $post['salt']); } - $this->userData = UserModel::create($post); - - return $this->responseToken($this->userData); - + $user = UserModel::create($post); } catch (\Throwable $th) { $this->setError($th->getMessage()); return false; } + + return $this->responseToken($user); } /** * 用户检测登录 * @param string $nickname * @param string $pwd - * @return mixed - * @throws \think\db\exception\DataNotFoundException - * @throws \think\db\exception\DbException - * @throws \think\db\exception\ModelNotFoundException + * @return false|Response + * @throws DataNotFoundException + * @throws DbException + * @throws InvalidArgumentException + * @throws ModelNotFoundException */ public function login(string $nickname = '', string $pwd = '') { @@ -155,36 +164,37 @@ class Auth } else { $where[] = ['mobile', '=', htmlspecialchars(trim($nickname))]; } - $this->userData = UserModel::where($where)->find(); - if (!empty($this->userData)) { + $user = UserModel::where($where)->find(); - $uPwd = encryptPwd($pwd, $this->userData['salt']); - if ($this->userData['pwd'] !== $uPwd) { + if (!empty($user)) { + + $uPwd = encryptPwd($pwd, $user['salt']); + if ($user['pwd'] !== $uPwd) { $this->setError('用户名或密码错误'); - UserLog::write($this->getError(), $this->userData->nickname, $this->userData->id); + UserLog::write($this->getError(), $user['nickname'], $user['id']); return false; } - if (!$this->userData['status']) { + if (!$user['status']) { $this->setError('用户异常或未审核,请联系管理员'); - UserLog::write($this->getError(), $this->userData->nickname, $this->userData->id); + UserLog::write($this->getError(), $user['nickname'], $user['id']); return false; } // 更新登录数据 - $userUpdate = [ - 'id' => $this->userData['id'], + $update = [ + 'id' => $user['id'], 'login_time' => time(), 'login_ip' => request()->getRealIp(), - 'login_count' => $this->userData['login_count'] + 1, + 'login_count' => $user['login_count'] + 1, ]; - if (UserModel::update($userUpdate)) { - Event::emit('userLoginSuccess', $this->userData); - UserLog::write('登录成功', $this->userData->nickname, $this->userData->id, 1); - return $this->responseToken($this->userData); + if (UserModel::update($update)) { + Event::emit('userLoginSuccess', $user); + UserLog::write('登录成功', $user['nickname'], $user['id'], 1); + return $this->responseToken($user); } } @@ -195,9 +205,9 @@ class Auth /** * 验证是否登录 * @return bool - * @throws \think\db\exception\DataNotFoundException - * @throws \think\db\exception\DbException - * @throws \think\db\exception\ModelNotFoundException + * @throws DataNotFoundException + * @throws DbException + * @throws ModelNotFoundException|InvalidArgumentException */ public function isLogin(): bool { @@ -205,46 +215,67 @@ class Auth if (!$token) { return false; } - $uid = $this->checkToken($token); - if (!empty($uid)) { - $this->token = $token; - $this->userData = UserModel::with('group')->find($uid); - return true; + // 验证token + $user = $this->checkToken($token); + if (isset($user['id'])) { + $this->userInfo = UserModel::with('group')->find($user['id']); + if (!empty($this->userInfo)) { + $this->token = $token; + $this->user_id = $user['id']; + $this->refreshUserInfo($token, $this->userInfo); + return true; + } } return false; } /** - * 退出登录 - * @return void - * @throws \Psr\SimpleCache\InvalidArgumentException + * 获取用户信息 */ - public function logout() + public function getUserInfo() { - Cache::delete($this->token); + $token = $this->getToken(); + if (!$token) { + return false; + } + + // 获取用户信息 + return $this->checkToken($token); } /** * * 返回前端令牌 - * @param mixed $userData + * @param $user * @param bool $token - * @return mixed - * @throws \Psr\SimpleCache\InvalidArgumentException + * @return Response + * @throws InvalidArgumentException */ - public function responseToken($userData, bool $token = false) + public function responseToken($user, bool $token = false): Response { - $this->token = $token ? $this->getToken() : $this->buildToken($userData['id']); + $this->token = $token ? $this->getToken() : $this->buildToken($user['id']); $response = response(); - $response->cookie('uid', $userData['id'],$this->keepTime, '/'); - $response->cookie('token', $this->token,$this->keepTime, '/'); - $response->cookie('nickname', $userData['nickname'],$this->keepTime, '/'); - Cache::set($this->token, $userData['id'], $this->keepTime); - Event::emit("userLoginSuccess", $userData); + $response->cookie('uid', $user['id'], $this->keepTime, '/'); + $response->cookie('token', $this->token, $this->keepTime, '/'); + $response->cookie('nickname', $user['nickname'], $this->keepTime, '/'); + $this->refreshUserInfo($this->token, $user); + // 执行登录成功事件 + Event::emit("userLoginSuccess", $user); return $response; + } + /** + * 刷新用户信息 + * @param $token + * @param $user + * @return void + * @throws InvalidArgumentException + */ + private function refreshUserInfo($token, $user): void + { + Cache::set($token, $user, $this->keepTime); } /** @@ -260,7 +291,6 @@ class Auth /** * 获取token - * @return array|string|null */ public function getToken($token = 'token') { @@ -269,15 +299,20 @@ class Auth /** * 校验token - * @access protected - * @param $token - * @return void - * @throws \Psr\SimpleCache\InvalidArgumentException */ public function checkToken($token) { - $user_id = Cache::get($token); - return $user_id ?? false; + return Cache::get($token); + } + + /** + * 退出登录 + * @return void + * @throws InvalidArgumentException + */ + public function logout() + { + Cache::delete($this->token); } /** diff --git a/app/common/library/ParseData.php b/app/common/library/ParseData.php index 57bf387..c59d113 100644 --- a/app/common/library/ParseData.php +++ b/app/common/library/ParseData.php @@ -118,7 +118,7 @@ class ParseData } /** - * 自动补全图片 + * cdn前缀 * @access public * @param string $image * @param $data diff --git a/app/functions.php b/app/functions.php index e776012..e9dd18a 100644 --- a/app/functions.php +++ b/app/functions.php @@ -3,6 +3,7 @@ * 全局公共函数库 */ +use app\common\library\Auth; use app\common\model\system\UserThird; use think\facade\Cache; use app\common\model\system\Config; @@ -123,6 +124,51 @@ if (!function_exists('token_field')) { } } +if (!function_exists('get_user_id')) { + /** + * 获取会员ID + */ + function get_user_id() + { + return get_user_info('id'); + } +} + +if (!function_exists('get_user_info')) { + /** + * 获取会员信息 + */ + function get_user_info($field = '') + { + $data = Auth::instance()->getUserInfo(); + if ($field && isset($data[$field])) { + return $data[$field]; + } + + return $data; + } +} + +if (!function_exists('get_admin_id')) { + /** + * 获取管理员ID + */ + function get_admin_id(string $name = 'AdminLogin') + { + return get_admin_info($name . '.id'); + } +} + +if (!function_exists('get_admin_info')) { + /** + * 获取管理员信息 + */ + function get_admin_info(string $name = 'AdminLogin') + { + return session($name); + } +} + // +---------------------------------------------------------------------- // | 文件操作函数开始 // +---------------------------------------------------------------------- diff --git a/app/index/controller/Ajax.php b/app/index/controller/Ajax.php index 9d7bcd7..2b86217 100644 --- a/app/index/controller/Ajax.php +++ b/app/index/controller/Ajax.php @@ -62,10 +62,10 @@ class Ajax extends HomeController return $this->error(__('发送频繁')); } - $userData = User::getByMobile($mobile); - if (in_array($event, ['register', 'changer']) && $userData) { + $user = User::getByMobile($mobile); + if (in_array($event, ['register', 'changer']) && $user) { return $this->error('当前手机号已被占用'); - } else if ($event == 'forgot' && !$userData) { + } else if ($event == 'forgot' && !$user) { return $this->error('当前手机号未注册'); } @@ -103,10 +103,10 @@ class Ajax extends HomeController return $this->error(__('发送频繁')); } - $userData = User::getByEmail($email); - if (in_array($event, ['register', 'changer']) && $userData) { + $user = User::getByEmail($email); + if (in_array($event, ['register', 'changer']) && $user) { return $this->error('当前邮箱已被注册'); - } else if ($event == 'forgot' && !$userData) { + } else if ($event == 'forgot' && !$user) { return $this->error('当前邮箱不存在'); } diff --git a/app/index/controller/Third.php b/app/index/controller/Third.php index 6a638c5..60563ad 100644 --- a/app/index/controller/Third.php +++ b/app/index/controller/Third.php @@ -99,40 +99,37 @@ class Third extends HomeController } catch (\Exception $e) { return $this->error($e->getMessage()); } - $userData = $this->oauth->getUserInfo(); - if (!empty($userData) && !$this->auth->isLogin()) { - return $this->register($userData, $this->type); + $user = $this->oauth->getUserInfo(); + if (!empty($user) && !$this->auth->isLogin()) { + return $this->register($user, $this->type); } else if ($this->auth->isLogin()) { // 绑定用户 - return $this->doBind($userData, $this->type); + return $this->doBind($user, $this->type); } } /** * 用户注册操作 - * @param array $userDatas + * @param array $info * @param string|null $type * @return Response * @throws DataNotFoundException * @throws DbException * @throws ModelNotFoundException */ - protected function register(array $userDatas = [], string $type = null) + protected function register(array $info = [], string $type = null) { - $openid = $userDatas['openid'] ?? $userDatas['id']; - $nickname = $userDatas['userData']['name'] ?? $userDatas['userData']['nickname']; - $userData = UserThird::alias('th') - ->view('user', '*', 'user.id=th.user_id') - ->where(['openid' => $openid, 'type' => $type]) - ->find(); + $openid = $info['openid'] ?? $info['id']; + $nickname = $info['userData']['name'] ?? $info['userData']['nickname']; + $userInfo = UserThird::alias('th')->view('user', '*', 'user.id=th.user_id')->where(['openid' => $openid, 'type' => $type])->find(); - if (!empty($userData)) { - $array['id'] = $userData['id']; + if (!empty($userInfo)) { + $array['id'] = $userInfo['id']; $array['login_time'] = time(); $array['login_ip'] = request()->getRealIp(); - $array['login_count'] = $userData['login_count'] + 1; + $array['login_count'] = $userInfo['login_count'] + 1; if (User::update($array)) { - $response = $this->auth->responseToken($userData); + $response = $this->auth->responseToken($userInfo); $response->withBody(json_encode(ResultCode::LOGINSUCCESS))->redirect(request()->cookie('redirectUrl', '/')); } @@ -140,7 +137,7 @@ class Third extends HomeController // 注册本地用户 $data['nickname'] = $nickname; - $data['avatar'] = $userDatas['userData']['avatar']; + $data['avatar'] = $info['userData']['avatar']; if (User::getByNickname($nickname)) { $data['nickname'] .= Random::alpha(3); } @@ -155,11 +152,11 @@ class Third extends HomeController 'user_id' => $result['id'], 'openid' => $openid, 'nickname' => $nickname, - 'access_token' => $userDatas['access_token'], - 'refresh_token' => $userDatas['refresh_token'], - 'expires_in' => $userDatas['expires_in'], + 'access_token' => $info['access_token'], + 'refresh_token' => $info['refresh_token'], + 'expires_in' => $info['expires_in'], 'login_time' => time(), - 'expiretime' => time() + $userDatas['expires_in'], + 'expiretime' => time() + $info['expires_in'], ]; } @@ -207,7 +204,7 @@ class Third extends HomeController } if ($this->auth->isLogin()) { - $result = $this->auth->userData; + $result = $this->auth->userInfo; if (!empty($result)) { if (empty($result['email']) || empty($result['pwd'])) { @@ -227,18 +224,18 @@ class Third extends HomeController /** * 用户绑定操作实例 - * @param array $userDatas + * @param array $info * @param string|null $type * @return Response|null * @throws DataNotFoundException * @throws DbException * @throws ModelNotFoundException */ - protected function doBind(array $userDatas = [], string $type = null) + protected function doBind(array $info = [], string $type = null) { - $openid = $userDatas['openid'] ?? $userDatas['id']; - $nickname = $userDatas['userData']['name'] ?? $userDatas['userData']['nickname']; + $openid = $info['openid'] ?? $info['id']; + $nickname = $info['userData']['name'] ?? $info['userData']['nickname']; // 查询是否被注册 $where['openid'] = $openid; @@ -251,11 +248,11 @@ class Third extends HomeController 'user_id' => request()->cookie('uid'), 'openid' => $openid, 'nickname' => $nickname, - 'access_token' => $userDatas['access_token'], - 'refresh_token' => $userDatas['refresh_token'], - 'expires_in' => $userDatas['expires_in'], + 'access_token' => $info['access_token'], + 'refresh_token' => $info['refresh_token'], + 'expires_in' => $info['expires_in'], 'login_time' => time(), - 'expiretime' => time() + $userDatas['expires_in'], + 'expiretime' => time() + $info['expires_in'], ]; if (UserThird::create($third)) { @@ -283,6 +280,4 @@ class Third extends HomeController request()->cookie('redirectUrl', null,1); return $this->redirect($referer); } - - } diff --git a/app/index/controller/User.php b/app/index/controller/User.php index 3168bcf..7fa1668 100644 --- a/app/index/controller/User.php +++ b/app/index/controller/User.php @@ -62,7 +62,7 @@ class User extends HomeController public function index(): Response { // 未读短消息 - $unread = UserNotice::where('user_id', \request()->user_id)->where('status', 0)->count(); + $unread = UserNotice::where('user_id', get_user_id())->where('status', 0)->count(); return view('/user/index', [ 'unread' => $unread, ]); @@ -165,16 +165,15 @@ class User extends HomeController } $where = $email ? ['email' => $email] : ['mobile' => $mobile]; - $userData = $this->model->where($where)->find(); - if (!$userData) { + $user = $this->model->where($where)->find(); + if (!$user) { return $this->error('用户不存在'); } try { $salt = Random::alpha(); $pwd = encryptPwd($pwd, $salt); - $this->model->update(['id' => $userData['id'], 'pwd' => $pwd, 'salt' => $salt]); - + $this->model->update(['id' => $user['id'], 'pwd' => $pwd, 'salt' => $salt]); } catch (\Exception $e) { return $this->error('修改密码失败,请联系管理员'); } @@ -207,7 +206,7 @@ class User extends HomeController return $this->error('当前昵称已被占用,请更换!'); } - if ($this->model->update(['id' => $request->user_id, 'nickname' => $nickname])) { + if ($this->model->update(['id' => get_user_id(), 'nickname' => $nickname])) { return $this->success('修改昵称成功!', (string)url('/user/index')); } @@ -231,7 +230,7 @@ class User extends HomeController return view('/user/center', [ 'newsHtml' => $result ?? '服务器错误', 'userList' => $this->model->order('login_count', 'desc')->limit(12)->select()->toArray(), - 'invite_count' => $this->model->where('invite_id', $request->user_id)->count(), + 'invite_count' => $this->model->where('invite_id', get_user_id())->count(), ]); } @@ -254,7 +253,7 @@ class User extends HomeController $where[] = ['status', '=', $status]; } - $where[] = ['user_id', '=', \request()->user_id]; + $where[] = ['user_id', '=', get_user_id()]; $count = UserNotice::where($where)->count(); $page = ($count <= $limit) ? 1 : $page; $list = UserNotice::where($where)->order('id', 'desc')->limit((int)$limit)->page((int)$page)->select()->toArray(); @@ -279,7 +278,7 @@ class User extends HomeController return $this->error('消息不存在'); } - if ($info['user_id'] != \request()->user_id) { + if ($info['user_id'] != get_user_id()) { return $this->error('非法操作'); } @@ -293,7 +292,7 @@ class User extends HomeController } // 更新未读 - $unread = UserNotice::where(['user_id' => \request()->user_id, 'status' => 0])->count(); + $unread = UserNotice::where(['user_id' => get_user_id(), 'status' => 0])->count(); return view('/user/viewMessage', [ 'info' => $info, 'unread' => $unread, @@ -311,7 +310,7 @@ class User extends HomeController $ids = input('id'); $type = input('type', 'del'); $where[] = ['id', 'in', implode(',', $ids)]; - $where[] = ['user_id', '=', \request()->user_id]; + $where[] = ['user_id', '=', get_user_id()]; if ($type === 'del') { if (UserNotice::where($where)->delete()) { return $this->success('删除成功'); @@ -346,14 +345,14 @@ class User extends HomeController return $this->error($post); } - if ($nickname != \request()->userData['nickname'] + if ($nickname != get_user_info()['nickname'] &&$this->model->where('nickname', $nickname)->find()) { return $this->error('当前昵称已被占用,请更换!'); } unset($post['money']); unset($post['score']); - $user = $this->model->find(\request()->user_id); + $user = $this->model->find(get_user_id()); if ($user->save($post)) { return $this->success('更新资料成功'); } @@ -361,9 +360,7 @@ class User extends HomeController return $this->error(); } - return view('/user/profile',[ - 'user' => \request()->userData, - ]); + return view('/user/profile'); } /** @@ -372,14 +369,14 @@ class User extends HomeController */ public function certification(): Response { - + $userInfo = get_user_info(); if (request()->isPost()) { $name = input('name'); $mobile = input('mobile'); $idCard = input('idCard'); $captcha = input('captcha'); - if (!empty(\request()->userData['prove'])) { + if (!empty($userInfo['prove'])) { return $this->error('您已经实名认证过了!'); } @@ -405,7 +402,7 @@ class User extends HomeController } // 更新系统认证信息 - $this->model->where('id', \request()->user_id)->update([ + $this->model->where('id', get_user_id())->update([ 'prove' => 1, 'name' => $name, 'idCard' => $idCard, @@ -420,7 +417,7 @@ class User extends HomeController return $this->success('实名认证成功!'); } - return view('/user/certification',['prove' => \request()->userData['prove']]); + return view('/user/certification',['prove' => $userInfo['prove']]); } /** @@ -437,7 +434,7 @@ class User extends HomeController // 获取数据 $page = input('page', 1); $limit = input('limit', 1); - $where[] = ['login_id', '=', \request()->user_id]; + $where[] = ['login_id', '=', get_user_id()]; $count = UserLog::where($where)->count(); $page = ($count <= $limit) ? 1 : $page; $list = UserLog::where($where)->order('id', 'desc')->limit((int)$limit)->page((int)$page)->select()->toArray(); @@ -460,15 +457,16 @@ class User extends HomeController // 获取参数 $pwd = input('pwd'); $oldPwd = input('oldpwd'); - $yPwd = encryptPwd($oldPwd, $request->userData->salt); + $userInfo = get_user_info(); + $yPwd = encryptPwd($oldPwd, $userInfo['salt']); - if ($yPwd != $request->userData->pwd) { + if ($yPwd != $userInfo['pwd']) { return $this->error('原密码输入错误!'); } $salt = Random::alpha(); $pwd = encryptPwd($pwd, $salt); - $result = $this->model->update(['id' => $request->user_id, 'pwd' => $pwd, 'salt' => $salt]); + $result = $this->model->update(['id' => get_user_id(), 'pwd' => $pwd, 'salt' => $salt]); if (!empty($result)) { return $this->success('修改密码成功!'); } @@ -487,8 +485,8 @@ class User extends HomeController { if (request()->isPost()) { $data = array(); - $data['id'] = $request->user_id; - $data['app_id'] = 10000 + $request->user_id; + $data['id'] = get_user_id(); + $data['app_id'] = 10000 + get_user_id(); $data['app_secret'] = Random::alpha(22); if ($this->model->update($data)) { return $this->success(); @@ -527,7 +525,7 @@ class User extends HomeController if (!empty($email) && !empty($captcha)) { if ($Ems->check($email, $captcha, $event)) { - $this->model->update(['id' => $request->user_id, 'email' => $email]); + $this->model->update(['id' => get_user_id(), 'email' => $email]); return $this->success('修改邮箱成功!'); } @@ -578,7 +576,7 @@ class User extends HomeController if (!empty($mobile) && !empty($captcha)) { if ($Sms->check($mobile, $captcha, $event)) { - $this->model->update(['id' => $request->user_id, 'mobile' => (int)$mobile]); + $this->model->update(['id' => get_user_id(), 'mobile' => (int)$mobile]); return $this->success('修改手机号成功!'); } @@ -627,9 +625,10 @@ class User extends HomeController } try { - $request->userData->question = $question; - $request->userData->answer = $answer; - $request->userData->save(); + $userInfo = get_user_info(); + $userInfo->question = $question; + $userInfo->answer = $answer; + $userInfo->save(); } catch (\Throwable $th) { return $this->error(); } @@ -651,20 +650,21 @@ class User extends HomeController { $maxProgress = 5; $thisProgress = 1; + $userInfo = get_user_info(); - if ($request->userData->email) { + if ($userInfo->email) { $thisProgress++; } - if ($request->userData->mobile) { + if ($userInfo->mobile) { $thisProgress++; } - if ($request->userData->answer) { + if ($userInfo->answer) { $thisProgress++; } - if ($request->userData->wechat) { + if ($userInfo->wechat) { $thisProgress++; } @@ -691,8 +691,9 @@ class User extends HomeController if (!$response) { return $this->error(Upload::instance()->getError()); } - $request->userData->avatar = $response['url'] . '?' . Random::alpha(12); - if ($request->userData->save()) { + $userInfo = get_user_info(); + $userInfo->avatar = $response['url'] . '?' . Random::alpha(12); + if ($userInfo->save()) { return json($response); } } diff --git a/app/index/middleware/system/IndexPermissions.php b/app/index/middleware/system/IndexPermissions.php index cb09b55..de26d0b 100644 --- a/app/index/middleware/system/IndexPermissions.php +++ b/app/index/middleware/system/IndexPermissions.php @@ -38,50 +38,45 @@ class IndexPermissions implements MiddlewareInterface * 跳转URL地址 * @var string */ - public string $JumpUrl = '/user/index'; + public string $JumpUrl = '/index/user/index'; /** * 校验权限 * @param Request $request * @param callable $handler * @return Response + * @throws \ReflectionException */ public function process(Request $request, callable $handler): Response { - $app = request()->getApp(); + $app = request()->getApp(); $controller = request()->getController(); - $action = request()->getAction(); + $action = request()->getAction(); - // 控制器是否存在 - $className = '\app' . $app . '\\controller\\' . $controller; - $className = str_replace('/', '\\', $className); - - if (class_exists($className)) { - $refClass = new \ReflectionClass($className); - $property = $refClass->getDefaultProperties(); - $this->needLogin = $property['needLogin'] ?? false; - $this->noNeedAuth = $property['noNeedAuth'] ?? []; - $this->repeatLogin = $property['repeatLogin'] ?? ['login', 'register']; - $this->JumpUrl = $property['JumpUrl'] ?? '/user/index'; - } + $refClass = new \ReflectionClass($request->controller); + $property = $refClass->getDefaultProperties(); + $this->needLogin = $property['needLogin'] ?? false; + $this->noNeedAuth = $property['noNeedAuth'] ?? $this->noNeedAuth; + $this->repeatLogin = $property['repeatLogin'] ?? $this->repeatLogin; + $this->JumpUrl = $property['JumpUrl'] ?? $this->JumpUrl; // 是否验证登录器 $auth = Auth::instance(); if ($auth->isLogin()) { - $request->user_id = $auth->userData['id']; - $request->userData = $auth->userData; + // 禁止重复登录 if (in_array($action, $this->repeatLogin)) { return redirect($this->JumpUrl); } - View::assign('user', $auth->userData); + View::assign('user', $auth->userInfo); } else { + if ($this->needLogin && !in_array($action, $this->noNeedAuth)) { if (\request()->isAjax()) { return json(ResultCode::PLEASELOGININ); } else { - return redirect('/user/login'); + return redirect('/index/user/login'); } } } diff --git a/app/index/view/user/include.html b/app/index/view/user/include.html index 15c2ddf..9a3d422 100644 --- a/app/index/view/user/include.html +++ b/app/index/view/user/include.html @@ -5,12 +5,11 @@ + - -