request->action(); $apiActions = ['getUsers', 'getBaseUrl', 'addUser', 'deleteUser', 'setBaseUrl', 'resetUserPassword']; if (in_array($action, $apiActions)) { // 检查登录状态 if (!Session::has('username')) { header('Content-Type: application/json; charset=utf-8'); echo json_encode([ 'code' => 0, 'msg' => '请先登录', ], JSON_UNESCAPED_UNICODE); exit; } // 检查管理员权限 if (!Session::get('is_admin', false)) { header('Content-Type: application/json; charset=utf-8'); echo json_encode([ 'code' => 0, 'msg' => '无权限访问,需要管理员权限', ], JSON_UNESCAPED_UNICODE); exit; } // 设置JSON响应头 header('Content-Type: application/json; charset=utf-8'); } } /** * 显示管理首页 */ public function index() { return View::fetch(); } /** * 获取所有账号列表 */ public function getUsers() { // 强制返回JSON,设置响应头 header('Content-Type: application/json; charset=utf-8'); try { $service = new UserService(); $users = $service->getAllUsers(); // 格式化数据 $result = []; foreach ($users as $user) { $result[] = [ 'username' => $user['username'] ?? '', 'created_at' => $user['created_at'] ?? '', ]; } return json([ 'code' => 1, 'data' => $result, 'msg' => '获取成功', ]); } catch (\Exception $e) { return json([ 'code' => 0, 'msg' => '获取失败: ' . $e->getMessage(), ]); } } /** * 添加账号 */ public function addUser() { // 强制返回JSON,设置响应头 header('Content-Type: application/json; charset=utf-8'); $username = $this->request->param('username', ''); $password = $this->request->param('password', ''); $service = new UserService(); $result = $service->addUser($username, $password); return json($result); } /** * 删除账号 */ public function deleteUser() { // 强制返回JSON,设置响应头 header('Content-Type: application/json; charset=utf-8'); $username = $this->request->param('username', ''); if (empty($username)) { return json([ 'code' => 0, 'msg' => '用户名不能为空', ]); } $service = new UserService(); $result = $service->deleteUser($username); return json($result); } /** * 获取BASE_URL配置 */ public function getBaseUrl() { // 强制返回JSON,设置响应头 header('Content-Type: application/json; charset=utf-8'); try { $service = new ConfigService(); $baseUrl = $service->getBaseUrl(); return json([ 'code' => 1, 'data' => [ 'base_url' => $baseUrl, ], 'msg' => '获取成功', ]); } catch (\Exception $e) { return json([ 'code' => 0, 'msg' => '获取失败: ' . $e->getMessage(), ]); } } /** * 设置BASE_URL配置 */ public function setBaseUrl() { // 强制返回JSON,设置响应头 header('Content-Type: application/json; charset=utf-8'); $baseUrl = $this->request->param('base_url', ''); $service = new ConfigService(); $result = $service->setBaseUrl($baseUrl); return json($result); } /** * 重置普通用户密码(管理员) */ public function resetUserPassword() { header('Content-Type: application/json; charset=utf-8'); $username = $this->request->param('username', ''); $newPassword = $this->request->param('new_password', ''); $service = new UserService(); $result = $service->resetUserPassword($username, $newPassword); return json($result); } }