From cdf796af99f1e8145bb6627abd9b152e22754198 Mon Sep 17 00:00:00 2001 From: "qian.guo" Date: Sun, 18 Oct 2026 03:59:40 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E6=94=B9=E4=B8=BA=E5=A4=9A?= =?UTF-8?q?=E5=BA=94=E7=94=A8=E6=A8=A1=E5=BC=8F=EF=BC=8C=E6=8E=A7=E5=88=B6?= =?UTF-8?q?=E5=99=A8=E5=9B=9E=E5=88=B0=20app/api/controller/=EF=BC=88?= =?UTF-8?q?=E7=AC=A6=E5=90=88=E4=BB=A3=E7=A0=81=E8=A7=84=E8=8C=83=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 规范《代码规范.md》第 27 行要求控制器位于 app/api/controller/Xxx.php。 上一轮为修复 404 曾挪到 app/controller/,属于违规且与规范冲突。 改动: - app/controller/* -> app/api/controller/*,命名空间改为 app\api\controller - 路由 app/api/route/api.php:规则去掉 api 前缀(多应用中间件会剥掉应用名), 只写 v1/xxx,URL 仍是 /api/v1/xxx - 根 route/ 清空:多应用下与应用内路由同时定义会让命中顺序不可预期 - 新增 app/index/ 默认应用:访问域名根路径返回服务状态与可用接口,便于排错 - composer.json 显式声明 topthink/think-multi-app(否则下次 composer install 会卸掉) 注意:部署后需 composer update topthink/think-multi-app 以刷新 composer.lock。 --- app/api/controller/Auth.php | 158 ++++++++++++++++++++++++++++++++++++ app/api/controller/Common.php | 142 ++++++++++++++++++++++++++++++++ app/api/controller/Quiz.php | 169 ++++++++++++++++++++++++++++++++++++++ app/api/controller/User.php | 179 +++++++++++++++++++++++++++++++++++++++++ app/api/route/api.php | 80 ++++++++++++++++++ app/controller/Auth.php | 158 ------------------------------------ app/controller/Common.php | 142 -------------------------------- app/controller/Index.php | 18 ----- app/controller/Quiz.php | 169 -------------------------------------- app/controller/User.php | 179 ----------------------------------------- app/index/controller/Index.php | 57 +++++++++++++ composer.json | 3 +- route/api.php | 67 --------------- route/app.php | 27 +++---- 14 files changed, 799 insertions(+), 749 deletions(-) create mode 100644 app/api/controller/Auth.php create mode 100644 app/api/controller/Common.php create mode 100644 app/api/controller/Quiz.php create mode 100644 app/api/controller/User.php create mode 100644 app/api/route/api.php delete mode 100644 app/controller/Auth.php delete mode 100644 app/controller/Common.php delete mode 100644 app/controller/Index.php delete mode 100644 app/controller/Quiz.php delete mode 100644 app/controller/User.php create mode 100644 app/index/controller/Index.php delete mode 100644 route/api.php diff --git a/app/api/controller/Auth.php b/app/api/controller/Auth.php new file mode 100644 index 0000000..43b0680 --- /dev/null +++ b/app/api/controller/Auth.php @@ -0,0 +1,158 @@ +wx_service = $wx_service; + $this->jwt_service = $jwt_service; + } + + /** + * 登录(不存在则自动注册) + * login + * @param Request $request 请求对象 + * @return \think\response\Json + */ + public function login(Request $request) + { + $param = []; + $param['code'] = (string) $request->param('code', ''); + + // 微信凭证不合法时 WxService 会抛业务异常,由全局异常处理统一出 400 + $wx_data = $this->wx_service->code2Session($param['code']); + $openid = $wx_data['openid']; + + $user_info = UserModel::getUserInfoByOpenid($openid); + + $is_new_user = false; + if (empty($user_info)) { + $is_new_user = true; + $user_info = $this->createUser($openid, $wx_data, $request); + } else { + // 业务校验:禁用账号不允许登录 + if (intval($user_info['is_enable']) !== 0) { + return json([ + 'code' => config('code.fail'), + 'msg' => '账号已被限制', + 'data' => [ + 'err_code' => config('code.err.user_banned') + ] + ]); + } + + UserModel::loginNumInc(intval($user_info['user_id'])); + } + + $token_data = $this->jwt_service->createToken(intval($user_info['user_id'])); + + $user = []; + $user['user_id'] = intval($user_info['user_id']); + $user['nickname'] = (string) ($user_info['nickname'] ?? ''); + $user['avatar'] = (string) ($user_info['avatar'] ?? ''); + $user['create_time'] = (string) ($user_info['create_time'] ?? ''); + + $data = []; + $data['token'] = $token_data['token']; + $data['expires_at'] = $token_data['expires_at']; + $data['expires_in'] = $token_data['expires_in']; + $data['is_new_user'] = $is_new_user; + $data['user'] = $user; + + return json([ + 'code' => config('code.success'), + 'msg' => 'success', + 'data' => $data + ]); + } + + /** + * 校验 token 是否有效 + * checkToken + * @return \think\response\Json + * + * 必须挂在 LoginCheck 下:能返回就说明 token 有效 + * 前端冷启动用它判断「直接进首页」还是「重新静默登录」 + */ + public function checkToken() + { + $data = []; + $data['user_id'] = $this->account_id; + $data['is_auth'] = true; + + return json([ + 'code' => config('code.success'), + 'msg' => 'success', + 'data' => $data + ]); + } + + /** + * 创建用户 + * createUser + * @param string $openid 微信 openid + * @param array $wx_data 微信返回数据 + * @param Request $request 请求对象 + * @return array 新建的用户信息 + */ + private function createUser($openid, $wx_data, Request $request) + { + $now = date('Y-m-d H:i:s'); + + // 昵称只做长度截断,不做非空/格式校验(规范:参数校验交给前端) + $nickname = (string) $request->param('nickname', ''); + $nickname = mb_substr($nickname, 0, 32); + + $avatar = (string) $request->param('avatar', ''); + $avatar = mb_substr($avatar, 0, 512); + + $data = []; + $data['openid'] = $openid; + $data['unionid'] = (string) ($wx_data['unionid'] ?? ''); + $data['nickname'] = $nickname; + $data['avatar'] = $avatar; + $data['is_enable'] = 0; + $data['is_delete'] = 0; + $data['login_num'] = 1; + $data['create_time'] = $now; + $data['update_time'] = $now; + + $user_id = UserModel::userAdd($data); + + return UserModel::getUserInfoById($user_id); + } +} diff --git a/app/api/controller/Common.php b/app/api/controller/Common.php new file mode 100644 index 0000000..ee3a96a --- /dev/null +++ b/app/api/controller/Common.php @@ -0,0 +1,142 @@ +score_service = $score_service; + $this->wx_service = $wx_service; + } + + /** + * 健康检查 + * health + * @param Request $request 请求对象 + * @return \think\response\Json + */ + public function health(Request $request) + { + $data = []; + $data['service'] = 'zhunxin-api'; + $data['status'] = 'ok'; + $data['timestamp'] = date('Y-m-d H:i:s'); + $data['client_ip'] = $request->ip(); + $data['wx'] = $this->wx_service->getConfigSummary(); + $data['site'] = $this->getSiteSummary(); + $data['db'] = $this->getDbSummary(); + + return json([ + 'code' => config('code.success'), + 'msg' => 'success', + 'data' => $data + ]); + } + + /** + * 站点配置摘要 + * getSiteSummary + * + * 只回带「配了没」与地址本身,不含任何密钥。 + * 联调时最常见的两个问题靠它一眼判定: + * - 前端请求的域名与后端认知的域名不一致(分享链接会指向错误地址) + * - APP_URL 根本没读进来(.env 写了但键名拼错) + * + * @return array + */ + private function getSiteSummary() + { + $url = (string) config('site.url'); + + $summary = []; + $summary['url'] = $url; + $summary['configured'] = $url !== ''; + $summary['api_prefix'] = (string) config('site.api_prefix'); + + return $summary; + } + + /** + * 数据库配置摘要 + * getDbSummary + * + * 只回答一个问题:连库信息配齐了没。 + * 不返回主机、库名、账号 —— health 是公开接口, + * 这些信息足够拼出内网拓扑,不该对未登录者开放。 + * + * 注意:configured=true 不代表能连上。本接口**刻意不查库** —— + * 健康检查一旦依赖数据库,库挂时会连「进程是否活着」都判断不了。 + * + * @return array + */ + private function getDbSummary() + { + $database = (string) config('database.connections.mysql.database'); + + $summary = []; + $summary['configured'] = $database !== ''; + + return $summary; + } + + /** + * 获取已注册的评分策略清单 + * getStrategyList + * @return \think\response\Json + */ + public function getStrategyList() + { + if (!app()->isDebug()) { + return json([ + 'code' => config('code.fail'), + 'msg' => '接口不存在', + 'data' => [ + 'err_code' => config('code.err.not_found') + ] + ]); + } + + $data = []; + $data['default'] = $this->score_service->getDefaultStrategy(); + $data['strategies'] = $this->score_service->getStrategyList(); + + return json([ + 'code' => config('code.success'), + 'msg' => 'success', + 'data' => $data + ]); + } +} diff --git a/app/api/controller/Quiz.php b/app/api/controller/Quiz.php new file mode 100644 index 0000000..261bbb0 --- /dev/null +++ b/app/api/controller/Quiz.php @@ -0,0 +1,169 @@ +score_service = $score_service; + } + + /** + * 获取试卷与题目 + * getPaperInfo + * @return \think\response\Json + */ + public function getPaperInfo() + { + $paper = QuizModel::getPaperInfo(); + + if (empty($paper)) { + return json([ + 'code' => config('code.fail'), + 'msg' => '试卷不存在', + 'data' => [ + 'err_code' => config('code.err.paper_not_found') + ] + ]); + } + + $question_list = QuizModel::getPublicQuestionList(); + + if (empty($question_list)) { + return json([ + 'code' => config('code.success'), + 'msg' => '暂无数据', + 'data' => [], + 'total' => 0 + ]); + } + + $data = []; + $data['paper_code'] = (string) ($paper['code'] ?? ''); + $data['title'] = (string) ($paper['title'] ?? ''); + $data['version'] = (string) ($paper['version'] ?? ''); + $data['question_count'] = QuizModel::getQuestionTotal(); + $data['notice'] = (string) ($paper['notice'] ?? ''); + $data['questions'] = $question_list; + + return json([ + 'code' => config('code.success'), + 'msg' => 'success', + 'data' => $data + ]); + } + + /** + * 交卷并评分 + * submitAnswers + * + * 请求体:answers = { "1": "A", "2": "B", ... }(键为题号,值为选项 key) + * 免登录,不落库,不写文件:答案是「随传随算」的。 + * + * 为什么不存:本期不建库,而写本地文件在多机部署下会不一致; + * 存一份对不上号的数据,比不存更糟。 + * 代价是用户关掉小程序就丢失结果,所以前端把结果存本地并允许从结果页重进。 + * + * @param Request $request 请求对象 + * @return \think\response\Json + */ + public function submitAnswers(Request $request) + { + $answer_list = $request->post('answers', []); + + // 参数必须是「题号 => 选项 key」的映射 + if (!is_array($answer_list)) { + return json([ + 'code' => config('code.fail'), + 'msg' => '作答格式不正确', + 'data' => [ + 'err_code' => config('code.err.param') + ] + ]); + } + + if (count($answer_list) === 0) { + return json([ + 'code' => config('code.fail'), + 'msg' => '还没有作答', + 'data' => [ + 'err_code' => config('code.err.quiz_unfinished') + ] + ]); + } + + $question_total = QuizModel::getQuestionTotal(); + + /* + * 缺题直接失败,不静默补默认值。 + * 补默认值会让「只答了 30 题」也算出一个看上去合法的人格类型, + * 那是把「数据不完整」伪装成「结果有效」—— 比报错危险得多。 + */ + if (count($answer_list) < $question_total) { + return json([ + 'code' => config('code.fail'), + 'msg' => '还有 ' . ($question_total - count($answer_list)) . ' 题未作答', + 'data' => [ + 'err_code' => config('code.err.quiz_unfinished'), + 'unfinished_count' => $question_total - count($answer_list) + ] + ]); + } + + try { + $result = $this->score_service->score($answer_list); + } catch (\Throwable $e) { + // 评分失败的原因多是配置问题(策略未注册 / 题库文件损坏), + // 记日志便于定位,但对外只给「评分失败」,不把内部细节吐给客户端 + Log::error('[Quiz::submitAnswers] ' . $e->getMessage()); + + return json([ + 'code' => config('code.error'), + 'msg' => '评分失败,请稍后重试', + 'data' => [ + 'err_code' => config('code.err.score_failed') + ] + ]); + } + + return json([ + 'code' => config('code.success'), + 'msg' => 'success', + 'data' => $result->getData() + ]); + } +} diff --git a/app/api/controller/User.php b/app/api/controller/User.php new file mode 100644 index 0000000..4071012 --- /dev/null +++ b/app/api/controller/User.php @@ -0,0 +1,179 @@ +account_id +* - 只做业务校验(存在性/状态),参数非空与格式交给前端 +* - 不提供登出接口:JWT 是无状态的,前端清掉本地 token 即完成登出 +* 真要强制下线需要 Redis 黑名单(jti),尚未接入 +* 与其给一个只在单机上有效的假登出,不如不做 +*/ +class User extends BaseController +{ + /** + * 获取当前用户资料 + * getProfileInfo + * @return \think\response\Json + */ + public function getProfileInfo() + { + $user_info = UserModel::getUserInfoById($this->account_id); + + if (empty($user_info)) { + return json([ + 'code' => config('code.fail'), + 'msg' => '用户不存在', + 'data' => [ + 'err_code' => config('code.err.user_not_found') + ] + ]); + } + + if (intval($user_info['is_enable']) !== 0) { + return json([ + 'code' => config('code.fail'), + 'msg' => '账号已被限制', + 'data' => [ + 'err_code' => config('code.err.user_banned') + ] + ]); + } + + return json([ + 'code' => config('code.success'), + 'msg' => 'success', + 'data' => $this->formatUser($user_info) + ]); + } + + /** + * 更新当前用户资料 + * profileUpdate + * @param Request $request 请求对象 + * @return \think\response\Json + * + * 只取实际传入的字段:不能把未传的字段也写进待更新数组 + * 否则未传时会写入空值,只改头像就把昵称清掉了 + */ + public function profileUpdate(Request $request) + { + $user_info = UserModel::getUserInfoById($this->account_id); + + if (empty($user_info)) { + return json([ + 'code' => config('code.fail'), + 'msg' => '用户不存在', + 'data' => [ + 'err_code' => config('code.err.user_not_found') + ] + ]); + } + + $param = []; + if ($request->has('nickname')) { + $nickname = (string) $request->param('nickname', ''); + $param['nickname'] = mb_substr($nickname, 0, 32); + } + if ($request->has('avatar')) { + $avatar = (string) $request->param('avatar', ''); + $param['avatar'] = mb_substr($avatar, 0, 512); + } + + if (empty($param)) { + return json([ + 'code' => config('code.fail'), + 'msg' => '没有可更新的字段', + 'data' => [ + 'err_code' => config('code.err.param') + ] + ]); + } + + $param['update_time'] = date('Y-m-d H:i:s'); + + UserModel::userUpdate($this->account_id, $param); + + $user_info = UserModel::getUserInfoById($this->account_id); + + return json([ + 'code' => config('code.success'), + 'msg' => 'success', + 'data' => $this->formatUser($user_info) + ]); + } + + /** + * 注销账号 + * accountDeactivate + * @return \think\response\Json + * + * 只置 is_delete=1,不物理删除:删掉后同一 openid 再次登录会变成全新用户 + * 历史测评结果将永久失去归属,而用户预期是「注销后数据不再被使用」 + * 不是「同一个人换个身份重新开始」。真正的数据清除应走独立的合规流程 + */ + public function accountDeactivate() + { + $user_info = UserModel::getUserInfoById($this->account_id); + + if (empty($user_info)) { + return json([ + 'code' => config('code.fail'), + 'msg' => '用户不存在', + 'data' => [ + 'err_code' => config('code.err.user_not_found') + ] + ]); + } + + $param = []; + $param['is_delete'] = 1; + $param['update_time'] = date('Y-m-d H:i:s'); + + UserModel::userUpdate($this->account_id, $param); + + return json([ + 'code' => config('code.success'), + 'msg' => 'success', + 'data' => [ + 'deactivated' => true + ] + ]); + } + + /** + * 格式化对外用户数据 + * formatUser + * @param array $user_info 用户信息 + * @return array 只含对外字段 + * + * 白名单:openid / unionid / login_num 等 服务端字段不出现在响应里 + * 避免身份标识与运营数据外泄 + */ + private function formatUser($user_info) + { + $data = []; + $data['user_id'] = intval($user_info['user_id']); + $data['nickname'] = (string) ($user_info['nickname'] ?? ''); + $data['avatar'] = (string) ($user_info['avatar'] ?? ''); + $data['create_time'] = (string) ($user_info['create_time'] ?? ''); + + return $data; + } +} diff --git a/app/api/route/api.php b/app/api/route/api.php new file mode 100644 index 0000000..e70334f --- /dev/null +++ b/app/api/route/api.php @@ -0,0 +1,80 @@ +middleware(RateLimitCheck::class, 'auth_login', 20, 60); + + // 校验 token 是否仍有效(前端冷启动用),必须挂在鉴权下 + Route::get('check', 'Auth/checkToken') + ->middleware(LoginCheck::class); + }); + + /* ---------------- 用户资料(全部需登录) ---------------- */ + Route::group('user', function () { + Route::get('profile', 'User/getProfileInfo'); + Route::post('profile', 'User/profileUpdate'); + Route::post('deactivate', 'User/accountDeactivate'); + })->middleware(LoginCheck::class); + + /* ---------------- 测评 ---------------- */ + Route::group('quiz', function () { + // 取试卷免登录:用户在「开始测评」时才登录,登录前就要能渲染首页 + Route::get('paper', 'Quiz/getPaperInfo'); + + /* + * 交卷评分:免登录,但必须限流。 + * 不限流的话,这里是唯一「免鉴权 + 会消耗 CPU」的入口, + * 一个循环就能把服务器打满。 + * 阈值 10 次/分钟/IP:正常人 3 分钟内只会交一次卷, + * 留余量是为了容忍弱网重试与多人共用同一个出口 IP(如公司/学校)。 + */ + Route::post('submit', 'Quiz/submitAnswers') + ->middleware(RateLimitCheck::class, 'quiz_submit', 10, 60); + }); + + /* ---------------- 运维/调试 ---------------- */ + Route::group('system', function () { + Route::get('strategies', 'Common/getStrategyList') + ->middleware(RateLimitCheck::class, 'system', 30, 60); + }); +}); diff --git a/app/controller/Auth.php b/app/controller/Auth.php deleted file mode 100644 index c42bd2f..0000000 --- a/app/controller/Auth.php +++ /dev/null @@ -1,158 +0,0 @@ -wx_service = $wx_service; - $this->jwt_service = $jwt_service; - } - - /** - * 登录(不存在则自动注册) - * login - * @param Request $request 请求对象 - * @return \think\response\Json - */ - public function login(Request $request) - { - $param = []; - $param['code'] = (string) $request->param('code', ''); - - // 微信凭证不合法时 WxService 会抛业务异常,由全局异常处理统一出 400 - $wx_data = $this->wx_service->code2Session($param['code']); - $openid = $wx_data['openid']; - - $user_info = UserModel::getUserInfoByOpenid($openid); - - $is_new_user = false; - if (empty($user_info)) { - $is_new_user = true; - $user_info = $this->createUser($openid, $wx_data, $request); - } else { - // 业务校验:禁用账号不允许登录 - if (intval($user_info['is_enable']) !== 0) { - return json([ - 'code' => config('code.fail'), - 'msg' => '账号已被限制', - 'data' => [ - 'err_code' => config('code.err.user_banned') - ] - ]); - } - - UserModel::loginNumInc(intval($user_info['user_id'])); - } - - $token_data = $this->jwt_service->createToken(intval($user_info['user_id'])); - - $user = []; - $user['user_id'] = intval($user_info['user_id']); - $user['nickname'] = (string) ($user_info['nickname'] ?? ''); - $user['avatar'] = (string) ($user_info['avatar'] ?? ''); - $user['create_time'] = (string) ($user_info['create_time'] ?? ''); - - $data = []; - $data['token'] = $token_data['token']; - $data['expires_at'] = $token_data['expires_at']; - $data['expires_in'] = $token_data['expires_in']; - $data['is_new_user'] = $is_new_user; - $data['user'] = $user; - - return json([ - 'code' => config('code.success'), - 'msg' => 'success', - 'data' => $data - ]); - } - - /** - * 校验 token 是否有效 - * checkToken - * @return \think\response\Json - * - * 必须挂在 LoginCheck 下:能返回就说明 token 有效 - * 前端冷启动用它判断「直接进首页」还是「重新静默登录」 - */ - public function checkToken() - { - $data = []; - $data['user_id'] = $this->account_id; - $data['is_auth'] = true; - - return json([ - 'code' => config('code.success'), - 'msg' => 'success', - 'data' => $data - ]); - } - - /** - * 创建用户 - * createUser - * @param string $openid 微信 openid - * @param array $wx_data 微信返回数据 - * @param Request $request 请求对象 - * @return array 新建的用户信息 - */ - private function createUser($openid, $wx_data, Request $request) - { - $now = date('Y-m-d H:i:s'); - - // 昵称只做长度截断,不做非空/格式校验(规范:参数校验交给前端) - $nickname = (string) $request->param('nickname', ''); - $nickname = mb_substr($nickname, 0, 32); - - $avatar = (string) $request->param('avatar', ''); - $avatar = mb_substr($avatar, 0, 512); - - $data = []; - $data['openid'] = $openid; - $data['unionid'] = (string) ($wx_data['unionid'] ?? ''); - $data['nickname'] = $nickname; - $data['avatar'] = $avatar; - $data['is_enable'] = 0; - $data['is_delete'] = 0; - $data['login_num'] = 1; - $data['create_time'] = $now; - $data['update_time'] = $now; - - $user_id = UserModel::userAdd($data); - - return UserModel::getUserInfoById($user_id); - } -} diff --git a/app/controller/Common.php b/app/controller/Common.php deleted file mode 100644 index 7f9d239..0000000 --- a/app/controller/Common.php +++ /dev/null @@ -1,142 +0,0 @@ -score_service = $score_service; - $this->wx_service = $wx_service; - } - - /** - * 健康检查 - * health - * @param Request $request 请求对象 - * @return \think\response\Json - */ - public function health(Request $request) - { - $data = []; - $data['service'] = 'zhunxin-api'; - $data['status'] = 'ok'; - $data['timestamp'] = date('Y-m-d H:i:s'); - $data['client_ip'] = $request->ip(); - $data['wx'] = $this->wx_service->getConfigSummary(); - $data['site'] = $this->getSiteSummary(); - $data['db'] = $this->getDbSummary(); - - return json([ - 'code' => config('code.success'), - 'msg' => 'success', - 'data' => $data - ]); - } - - /** - * 站点配置摘要 - * getSiteSummary - * - * 只回带「配了没」与地址本身,不含任何密钥。 - * 联调时最常见的两个问题靠它一眼判定: - * - 前端请求的域名与后端认知的域名不一致(分享链接会指向错误地址) - * - APP_URL 根本没读进来(.env 写了但键名拼错) - * - * @return array - */ - private function getSiteSummary() - { - $url = (string) config('site.url'); - - $summary = []; - $summary['url'] = $url; - $summary['configured'] = $url !== ''; - $summary['api_prefix'] = (string) config('site.api_prefix'); - - return $summary; - } - - /** - * 数据库配置摘要 - * getDbSummary - * - * 只回答一个问题:连库信息配齐了没。 - * 不返回主机、库名、账号 —— health 是公开接口, - * 这些信息足够拼出内网拓扑,不该对未登录者开放。 - * - * 注意:configured=true 不代表能连上。本接口**刻意不查库** —— - * 健康检查一旦依赖数据库,库挂时会连「进程是否活着」都判断不了。 - * - * @return array - */ - private function getDbSummary() - { - $database = (string) config('database.connections.mysql.database'); - - $summary = []; - $summary['configured'] = $database !== ''; - - return $summary; - } - - /** - * 获取已注册的评分策略清单 - * getStrategyList - * @return \think\response\Json - */ - public function getStrategyList() - { - if (!app()->isDebug()) { - return json([ - 'code' => config('code.fail'), - 'msg' => '接口不存在', - 'data' => [ - 'err_code' => config('code.err.not_found') - ] - ]); - } - - $data = []; - $data['default'] = $this->score_service->getDefaultStrategy(); - $data['strategies'] = $this->score_service->getStrategyList(); - - return json([ - 'code' => config('code.success'), - 'msg' => 'success', - 'data' => $data - ]); - } -} diff --git a/app/controller/Index.php b/app/controller/Index.php deleted file mode 100644 index 27c1c62..0000000 --- a/app/controller/Index.php +++ /dev/null @@ -1,18 +0,0 @@ -*{ padding: 0; margin: 0; }'; - } - - public function hello($name = 'ThinkPHP8') - { - return 'hello,' . $name; - } -} diff --git a/app/controller/Quiz.php b/app/controller/Quiz.php deleted file mode 100644 index 86adc0f..0000000 --- a/app/controller/Quiz.php +++ /dev/null @@ -1,169 +0,0 @@ -score_service = $score_service; - } - - /** - * 获取试卷与题目 - * getPaperInfo - * @return \think\response\Json - */ - public function getPaperInfo() - { - $paper = QuizModel::getPaperInfo(); - - if (empty($paper)) { - return json([ - 'code' => config('code.fail'), - 'msg' => '试卷不存在', - 'data' => [ - 'err_code' => config('code.err.paper_not_found') - ] - ]); - } - - $question_list = QuizModel::getPublicQuestionList(); - - if (empty($question_list)) { - return json([ - 'code' => config('code.success'), - 'msg' => '暂无数据', - 'data' => [], - 'total' => 0 - ]); - } - - $data = []; - $data['paper_code'] = (string) ($paper['code'] ?? ''); - $data['title'] = (string) ($paper['title'] ?? ''); - $data['version'] = (string) ($paper['version'] ?? ''); - $data['question_count'] = QuizModel::getQuestionTotal(); - $data['notice'] = (string) ($paper['notice'] ?? ''); - $data['questions'] = $question_list; - - return json([ - 'code' => config('code.success'), - 'msg' => 'success', - 'data' => $data - ]); - } - - /** - * 交卷并评分 - * submitAnswers - * - * 请求体:answers = { "1": "A", "2": "B", ... }(键为题号,值为选项 key) - * 免登录,不落库,不写文件:答案是「随传随算」的。 - * - * 为什么不存:本期不建库,而写本地文件在多机部署下会不一致; - * 存一份对不上号的数据,比不存更糟。 - * 代价是用户关掉小程序就丢失结果,所以前端把结果存本地并允许从结果页重进。 - * - * @param Request $request 请求对象 - * @return \think\response\Json - */ - public function submitAnswers(Request $request) - { - $answer_list = $request->post('answers', []); - - // 参数必须是「题号 => 选项 key」的映射 - if (!is_array($answer_list)) { - return json([ - 'code' => config('code.fail'), - 'msg' => '作答格式不正确', - 'data' => [ - 'err_code' => config('code.err.param') - ] - ]); - } - - if (count($answer_list) === 0) { - return json([ - 'code' => config('code.fail'), - 'msg' => '还没有作答', - 'data' => [ - 'err_code' => config('code.err.quiz_unfinished') - ] - ]); - } - - $question_total = QuizModel::getQuestionTotal(); - - /* - * 缺题直接失败,不静默补默认值。 - * 补默认值会让「只答了 30 题」也算出一个看上去合法的人格类型, - * 那是把「数据不完整」伪装成「结果有效」—— 比报错危险得多。 - */ - if (count($answer_list) < $question_total) { - return json([ - 'code' => config('code.fail'), - 'msg' => '还有 ' . ($question_total - count($answer_list)) . ' 题未作答', - 'data' => [ - 'err_code' => config('code.err.quiz_unfinished'), - 'unfinished_count' => $question_total - count($answer_list) - ] - ]); - } - - try { - $result = $this->score_service->score($answer_list); - } catch (\Throwable $e) { - // 评分失败的原因多是配置问题(策略未注册 / 题库文件损坏), - // 记日志便于定位,但对外只给「评分失败」,不把内部细节吐给客户端 - Log::error('[Quiz::submitAnswers] ' . $e->getMessage()); - - return json([ - 'code' => config('code.error'), - 'msg' => '评分失败,请稍后重试', - 'data' => [ - 'err_code' => config('code.err.score_failed') - ] - ]); - } - - return json([ - 'code' => config('code.success'), - 'msg' => 'success', - 'data' => $result->getData() - ]); - } -} diff --git a/app/controller/User.php b/app/controller/User.php deleted file mode 100644 index 43d975b..0000000 --- a/app/controller/User.php +++ /dev/null @@ -1,179 +0,0 @@ -account_id -* - 只做业务校验(存在性/状态),参数非空与格式交给前端 -* - 不提供登出接口:JWT 是无状态的,前端清掉本地 token 即完成登出 -* 真要强制下线需要 Redis 黑名单(jti),尚未接入 -* 与其给一个只在单机上有效的假登出,不如不做 -*/ -class User extends BaseController -{ - /** - * 获取当前用户资料 - * getProfileInfo - * @return \think\response\Json - */ - public function getProfileInfo() - { - $user_info = UserModel::getUserInfoById($this->account_id); - - if (empty($user_info)) { - return json([ - 'code' => config('code.fail'), - 'msg' => '用户不存在', - 'data' => [ - 'err_code' => config('code.err.user_not_found') - ] - ]); - } - - if (intval($user_info['is_enable']) !== 0) { - return json([ - 'code' => config('code.fail'), - 'msg' => '账号已被限制', - 'data' => [ - 'err_code' => config('code.err.user_banned') - ] - ]); - } - - return json([ - 'code' => config('code.success'), - 'msg' => 'success', - 'data' => $this->formatUser($user_info) - ]); - } - - /** - * 更新当前用户资料 - * profileUpdate - * @param Request $request 请求对象 - * @return \think\response\Json - * - * 只取实际传入的字段:不能把未传的字段也写进待更新数组 - * 否则未传时会写入空值,只改头像就把昵称清掉了 - */ - public function profileUpdate(Request $request) - { - $user_info = UserModel::getUserInfoById($this->account_id); - - if (empty($user_info)) { - return json([ - 'code' => config('code.fail'), - 'msg' => '用户不存在', - 'data' => [ - 'err_code' => config('code.err.user_not_found') - ] - ]); - } - - $param = []; - if ($request->has('nickname')) { - $nickname = (string) $request->param('nickname', ''); - $param['nickname'] = mb_substr($nickname, 0, 32); - } - if ($request->has('avatar')) { - $avatar = (string) $request->param('avatar', ''); - $param['avatar'] = mb_substr($avatar, 0, 512); - } - - if (empty($param)) { - return json([ - 'code' => config('code.fail'), - 'msg' => '没有可更新的字段', - 'data' => [ - 'err_code' => config('code.err.param') - ] - ]); - } - - $param['update_time'] = date('Y-m-d H:i:s'); - - UserModel::userUpdate($this->account_id, $param); - - $user_info = UserModel::getUserInfoById($this->account_id); - - return json([ - 'code' => config('code.success'), - 'msg' => 'success', - 'data' => $this->formatUser($user_info) - ]); - } - - /** - * 注销账号 - * accountDeactivate - * @return \think\response\Json - * - * 只置 is_delete=1,不物理删除:删掉后同一 openid 再次登录会变成全新用户 - * 历史测评结果将永久失去归属,而用户预期是「注销后数据不再被使用」 - * 不是「同一个人换个身份重新开始」。真正的数据清除应走独立的合规流程 - */ - public function accountDeactivate() - { - $user_info = UserModel::getUserInfoById($this->account_id); - - if (empty($user_info)) { - return json([ - 'code' => config('code.fail'), - 'msg' => '用户不存在', - 'data' => [ - 'err_code' => config('code.err.user_not_found') - ] - ]); - } - - $param = []; - $param['is_delete'] = 1; - $param['update_time'] = date('Y-m-d H:i:s'); - - UserModel::userUpdate($this->account_id, $param); - - return json([ - 'code' => config('code.success'), - 'msg' => 'success', - 'data' => [ - 'deactivated' => true - ] - ]); - } - - /** - * 格式化对外用户数据 - * formatUser - * @param array $user_info 用户信息 - * @return array 只含对外字段 - * - * 白名单:openid / unionid / login_num 等 服务端字段不出现在响应里 - * 避免身份标识与运营数据外泄 - */ - private function formatUser($user_info) - { - $data = []; - $data['user_id'] = intval($user_info['user_id']); - $data['nickname'] = (string) ($user_info['nickname'] ?? ''); - $data['avatar'] = (string) ($user_info['avatar'] ?? ''); - $data['create_time'] = (string) ($user_info['create_time'] ?? ''); - - return $data; - } -} diff --git a/app/index/controller/Index.php b/app/index/controller/Index.php new file mode 100644 index 0000000..a7fc8b4 --- /dev/null +++ b/app/index/controller/Index.php @@ -0,0 +1,57 @@ + config('code.success'), + 'msg' => 'success', + 'data' => $data + ]); + } +} diff --git a/composer.json b/composer.json index 6d2ca60..83bb821 100644 --- a/composer.json +++ b/composer.json @@ -23,7 +23,8 @@ "php": ">=8.0.0", "topthink/framework": "^8.0", "topthink/think-orm": "^3.0|^4.0", - "topthink/think-filesystem": "^2.0|^3.0" + "topthink/think-filesystem": "^2.0|^3.0", + "topthink/think-multi-app": "^1.0" }, "require-dev": { "topthink/think-dumper": "^1.0", diff --git a/route/api.php b/route/api.php deleted file mode 100644 index 58db3ab..0000000 --- a/route/api.php +++ /dev/null @@ -1,67 +0,0 @@ -middleware(RateLimitCheck::class, 'auth_login', 20, 60); - - // 校验 token 是否仍有效(前端冷启动用),必须挂在鉴权下 - Route::get('check', 'Auth/checkToken') - ->middleware(LoginCheck::class); - }); - - /* ---------------- 用户资料(全部需登录) ---------------- */ - Route::group('user', function () { - Route::get('profile', 'User/getProfileInfo'); - Route::post('profile', 'User/profileUpdate'); - Route::post('deactivate', 'User/accountDeactivate'); - })->middleware(LoginCheck::class); - - /* ---------------- 测评 ---------------- */ - Route::group('quiz', function () { - // 取试卷免登录:用户在「开始测评」时才登录,登录前就要能渲染首页 - Route::get('paper', 'Quiz/getPaperInfo'); - - /* - * 交卷评分:免登录,但必须限流。 - * 不限流的话,这里是唯一「免鉴权 + 会消耗 CPU」的入口, - * 一个循环就能把服务器打满。 - * 阈值 10 次/分钟/IP:正常人 3 分钟内只会交一次卷, - * 留余量是为了容忍弱网重试与多人共用同一个出口 IP(如公司/学校)。 - */ - Route::post('submit', 'Quiz/submitAnswers') - ->middleware(RateLimitCheck::class, 'quiz_submit', 10, 60); - }); - - /* ---------------- 运维/调试 ---------------- */ - Route::group('system', function () { - Route::get('strategies', 'Common/getStrategyList') - ->middleware(RateLimitCheck::class, 'system', 30, 60); - }); -}); diff --git a/route/app.php b/route/app.php index e32780c..430d3cf 100644 --- a/route/app.php +++ b/route/app.php @@ -4,26 +4,23 @@ declare(strict_types=1); /** * app.php * Created by PhpStorm. - * Date: 2026/10/17 - * Time: 16:40 + * Date: 2026/10/18 + * Time: 03:55 * Author: qian.guo * E-mail: yiyezhiqiutel@gmail.com * - * 路由加载入口 + * 根路由文件(多应用模式下**刻意留空**) * - * 官方骨架的 app.php 带两条示例路由(GET /think、GET /hello/:name),已删除: - * - 它们是脚手架演示用,不是本项目接口 - * - 留在生产环境等于对外暴露两个无用端点,还会被扫描器记成"可访问路径" + * 为什么留空: + * 装 think-multi-app 后,路由按应用拆分,定义在 + * app/{应用名}/route/*.php + * 本项目 API 的路由在 app/api/route/api.php。 * - * 真正的接口定义在同目录的 api.php。本文件只做一件事:确保它被加载。 + * 根 route/ 只在「未进入任何应用」时才生效。如果这里也定义规则, + * 会出现两套规则争抢同一 URL 的情况,而命中顺序取决于加载次序, + * 排查时会非常痛苦(同一请求有时对有时错)。 * - * 为什么要显式 require: - * 多数 TP8 版本会扫描 route/ 下所有 php 文件,但也有只加载 route/app.php 的情况。 - * 靠"应该会扫到"是赌运气,赌输的表现是全部接口 404, - * 而报错只说"控制器不存在",很难联想到是路由文件没被加载。 - * - * 用 require_once 而不是 require: - * 若框架同时也扫到了 api.php,require_once 会走已加载判断,不会重复执行。 + * 所以:根路由不写任何规则。需要全局拦截请用中间件,不要用路由。 */ -require_once __DIR__ . '/api.php'; +// 有意为空。请勿在此添加 Route:: 规则,原因见上方说明。