diff --git a/app/controller/Admin.php b/app/controller/Admin.php new file mode 100644 index 0000000..855b9a1 --- /dev/null +++ b/app/controller/Admin.php @@ -0,0 +1,114 @@ +getAllUsers(); + + // 格式化数据 + $result = []; + foreach ($users as $user) { + $result[] = [ + 'username' => $user['username'] ?? '', + 'created_at' => $user['created_at'] ?? '', + ]; + } + + return json([ + 'code' => 1, + 'data' => $result, + 'msg' => '获取成功', + ]); + } + + /** + * 添加账号 + */ + public function addUser() + { + $username = $this->request->param('username', ''); + $password = $this->request->param('password', ''); + + $service = new UserService(); + $result = $service->addUser($username, $password); + + return json($result); + } + + /** + * 删除账号 + */ + public function deleteUser() + { + $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() + { + $service = new ConfigService(); + $baseUrl = $service->getBaseUrl(); + + return json([ + 'code' => 1, + 'data' => [ + 'base_url' => $baseUrl, + ], + 'msg' => '获取成功', + ]); + } + + /** + * 设置BASE_URL配置 + */ + public function setBaseUrl() + { + $baseUrl = $this->request->param('base_url', ''); + + $service = new ConfigService(); + $result = $service->setBaseUrl($baseUrl); + + return json($result); + } +} diff --git a/app/controller/Auth.php b/app/controller/Auth.php index 313f420..46d55ff 100644 --- a/app/controller/Auth.php +++ b/app/controller/Auth.php @@ -18,9 +18,14 @@ class Auth extends BaseController */ public function login() { - // 如果已登录,跳转到爬虫页面 + // 如果已登录,根据账号类型跳转到不同页面 if (Session::has('username')) { - return redirect('/crawler'); + $isAdmin = Session::get('is_admin', false); + if ($isAdmin) { + return redirect('/admin'); + } else { + return redirect('/crawler'); + } } return View::fetch(); } diff --git a/app/controller/User.php b/app/controller/User.php index cbea179..e69de29 100644 --- a/app/controller/User.php +++ b/app/controller/User.php @@ -1,114 +0,0 @@ - 0, - 'msg' => '无权限访问', - ]); - } - - return View::fetch(); - } - - /** - * 获取所有账号列表 - */ - public function getUsers() - { - // 检查是否为管理员 - if (!Session::get('is_admin', false)) { - return json([ - 'code' => 0, - 'msg' => '无权限访问', - ]); - } - - $service = new UserService(); - $users = $service->getAllUsers(); - - // 隐藏密码 - foreach ($users as &$user) { - if (isset($user['password'])) { - $user['password'] = '******'; - } - } - - return json([ - 'code' => 1, - 'data' => $users, - 'msg' => '获取成功', - ]); - } - - /** - * 添加账号 - */ - public function add() - { - // 检查是否为管理员 - if (!Session::get('is_admin', false)) { - return json([ - 'code' => 0, - 'msg' => '无权限访问', - ]); - } - - $username = $this->request->param('username', ''); - $password = $this->request->param('password', ''); - - $service = new UserService(); - $result = $service->addUser($username, $password); - - return json($result); - } - - /** - * 删除账号 - */ - public function delete() - { - // 检查是否为管理员 - if (!Session::get('is_admin', false)) { - return json([ - 'code' => 0, - 'msg' => '无权限访问', - ]); - } - - $username = $this->request->param('username', ''); - - if (empty($username)) { - return json([ - 'code' => 0, - 'msg' => '用户名不能为空', - ]); - } - - $service = new UserService(); - $result = $service->deleteUser($username); - - return json($result); - } -} diff --git a/app/middleware/Admin.php b/app/middleware/Admin.php new file mode 100644 index 0000000..55dbc2d --- /dev/null +++ b/app/middleware/Admin.php @@ -0,0 +1,54 @@ +isAjax()) { + return json([ + 'code' => 0, + 'msg' => '请先登录', + ]); + } + // 否则跳转到登录页 + return redirect('/login'); + } + + // 检查是否为管理员 + $isAdmin = Session::get('is_admin', false); + + if (!$isAdmin) { + // 如果是AJAX请求,返回JSON + if ($request->isAjax()) { + return json([ + 'code' => 0, + 'msg' => '无权限访问,需要管理员权限', + ]); + } + // 否则跳转到爬虫页面 + return redirect('/crawler'); + } + + return $next($request); + } +} diff --git a/app/model/Config.php b/app/model/Config.php new file mode 100644 index 0000000..4923a7e --- /dev/null +++ b/app/model/Config.php @@ -0,0 +1,25 @@ +execute($sql); + + // 初始化BASE_URL配置(如果不存在) + try { + $defaultBaseUrl = 'http://gzrsks.oumakspt.com:62'; + $exist = Config::where('config_key', 'BASE_URL')->find(); + if (!$exist) { + $config = new Config(); + $config->config_key = 'BASE_URL'; + $config->config_value = $defaultBaseUrl; + $config->created_at = date('Y-m-d H:i:s'); + $config->updated_at = date('Y-m-d H:i:s'); + $config->save(); + } + } catch (\Exception $e) { + // 忽略错误,可能在下次访问时创建 + } + } catch (\Exception $e) { + // 忽略错误 + } + } + + /** + * 获取配置值 + * @param string $key + * @param string $default + * @return string + */ + public function getConfig(string $key, string $default = ''): string + { + $this->initDatabase(); + + try { + $config = Config::where('config_key', $key)->find(); + if ($config) { + return $config->config_value ?? $default; + } + } catch (\Exception $e) { + // 忽略错误 + } + + return $default; + } + + /** + * 设置配置值 + * @param string $key + * @param string $value + * @return array ['code' => 1|0, 'msg' => string] + */ + public function setConfig(string $key, string $value): array + { + $this->initDatabase(); + + try { + $config = Config::where('config_key', $key)->find(); + + if ($config) { + // 更新现有配置 + $config->config_value = $value; + $config->updated_at = date('Y-m-d H:i:s'); + $config->save(); + } else { + // 创建新配置 + $config = new Config(); + $config->config_key = $key; + $config->config_value = $value; + $config->created_at = date('Y-m-d H:i:s'); + $config->updated_at = date('Y-m-d H:i:s'); + $config->save(); + } + + return ['code' => 1, 'msg' => '保存成功']; + } catch (\Exception $e) { + return ['code' => 0, 'msg' => '保存失败: ' . $e->getMessage()]; + } + } + + /** + * 获取BASE_URL + * @return string + */ + public function getBaseUrl(): string + { + return $this->getConfig('BASE_URL', 'http://gzrsks.oumakspt.com:62'); + } + + /** + * 设置BASE_URL + * @param string $url + * @return array + */ + public function setBaseUrl(string $url): array + { + if (empty($url)) { + return ['code' => 0, 'msg' => 'BASE_URL不能为空']; + } + + // 验证URL格式 + if (!filter_var($url, FILTER_VALIDATE_URL) && !preg_match('/^https?:\/\/[\w\.-]+(:\d+)?$/', $url)) { + return ['code' => 0, 'msg' => 'BASE_URL格式不正确']; + } + + return $this->setConfig('BASE_URL', $url); + } +} diff --git a/app/service/CrawlerService.php b/app/service/CrawlerService.php index c83aa88..681eaf5 100644 --- a/app/service/CrawlerService.php +++ b/app/service/CrawlerService.php @@ -9,23 +9,29 @@ namespace app\service; */ class CrawlerService { - /** - * 基础URL(域名和端口) - */ - private const BASE_URL = 'http://gzrsks.oumakspt.com:62'; - /** * 应用路径 */ private const APP_PATH = '/tyzpwb'; + /** + * 获取基础URL(域名和端口) + * @return string + */ + private function getBaseUrlHost(): string + { + // 从配置服务获取BASE_URL + $configService = new \app\service\ConfigService(); + return $configService->getBaseUrl(); + } + /** * 获取完整基础URL(包含应用路径) * @return string */ public function getBaseUrl(): string { - return self::BASE_URL . self::APP_PATH; + return $this->getBaseUrlHost() . self::APP_PATH; } /** @@ -88,7 +94,7 @@ class CrawlerService // Origin if ($isFirefox) { - $headers[] = 'Origin: ' . self::BASE_URL; + $headers[] = 'Origin: ' . $this->getBaseUrlHost(); } elseif ($origin !== null) { $headers[] = 'Origin: ' . $origin; } @@ -174,7 +180,7 @@ class CrawlerService $cookieString = $this->buildCookieString($cookies); $referer = $baseUrl . '/stuchooseexam/selectPosition.htm'; - $origin = self::BASE_URL; + $origin = $this->getBaseUrlHost(); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); diff --git a/app/service/UserService.php b/app/service/UserService.php index e89acf9..85b291e 100644 --- a/app/service/UserService.php +++ b/app/service/UserService.php @@ -3,17 +3,15 @@ declare (strict_types = 1); namespace app\service; +use app\model\User; +use think\facade\Db; + /** * 用户服务类 * 用于处理用户账号管理相关逻辑 */ class UserService { - /** - * 账号数据文件路径 - */ - private const USERS_FILE = 'users.json'; - /** * 管理员账号(固定) */ @@ -21,58 +19,65 @@ class UserService private const ADMIN_PASSWORD = '123456'; /** - * 初始化账号数据文件 + * 初始化数据库表 */ - private function initUsersFile(): void + public function initDatabase(): void { - $filePath = $this->getUsersFilePath(); - if (!file_exists($filePath)) { - $dir = dirname($filePath); - if (!is_dir($dir)) { - mkdir($dir, 0755, true); + $dbPath = dirname(dirname(__DIR__)) . '/runtime/database.db'; + $dbDir = dirname($dbPath); + + // 确保runtime目录存在 + if (!is_dir($dbDir)) { + mkdir($dbDir, 0755, true); + } + + // 连接SQLite数据库 + try { + $connection = Db::connect('sqlite'); + + // 创建用户表(如果不存在) + $sql = "CREATE TABLE IF NOT EXISTS users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username VARCHAR(50) NOT NULL UNIQUE, + password VARCHAR(255) NOT NULL, + created_at DATETIME NOT NULL + )"; + + $connection->execute($sql); + } catch (\Exception $e) { + // 如果连接失败,尝试创建数据库文件 + if (!file_exists($dbPath)) { + touch($dbPath); + chmod($dbPath, 0666); } - file_put_contents($filePath, json_encode([], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); } } - /** - * 获取账号数据文件路径 - * @return string - */ - private function getUsersFilePath(): string - { - // 获取项目根目录 - $rootPath = dirname(dirname(__DIR__)); - $runtimePath = $rootPath . '/runtime'; - if (!is_dir($runtimePath)) { - mkdir($runtimePath, 0755, true); - } - return $runtimePath . '/' . self::USERS_FILE; - } - /** * 读取所有账号 * @return array */ public function getAllUsers(): array { - $this->initUsersFile(); - $filePath = $this->getUsersFilePath(); - $content = file_get_contents($filePath); - $users = json_decode($content, true); - return is_array($users) ? $users : []; - } - - /** - * 保存账号数据 - * @param array $users - * @return bool - */ - private function saveUsers(array $users): bool - { - $this->initUsersFile(); - $filePath = $this->getUsersFilePath(); - return file_put_contents($filePath, json_encode($users, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) !== false; + $this->initDatabase(); + + try { + $users = User::select()->toArray(); + // 确保返回关联数组格式 + $result = []; + foreach ($users as $user) { + $result[] = [ + 'id' => $user['id'] ?? null, + 'username' => $user['username'] ?? '', + 'password' => $user['password'] ?? '', + 'created_at' => $user['created_at'] ?? '', + ]; + } + return $result; + } catch (\Exception $e) { + // 如果表不存在,返回空数组 + return []; + } } /** @@ -92,16 +97,19 @@ class UserService } // 验证普通用户账号 - $users = $this->getAllUsers(); - foreach ($users as $user) { - if (isset($user['username']) && $user['username'] === $username) { - if (isset($user['password']) && $user['password'] === $password) { - return [ - 'username' => $username, - 'is_admin' => false, - ]; - } + $this->initDatabase(); + + try { + $user = User::where('username', $username)->find(); + + if ($user && $user->password === $password) { + return [ + 'username' => $username, + 'is_admin' => false, + ]; } + } catch (\Exception $e) { + // 忽略数据库错误 } return false; @@ -123,26 +131,25 @@ class UserService return ['code' => 0, 'msg' => '不能添加管理员账号']; } - $users = $this->getAllUsers(); + $this->initDatabase(); - // 检查用户名是否已存在 - foreach ($users as $user) { - if (isset($user['username']) && $user['username'] === $username) { + try { + // 检查用户名是否已存在 + $existUser = User::where('username', $username)->find(); + if ($existUser) { return ['code' => 0, 'msg' => '用户名已存在']; } - } - - // 添加新用户 - $users[] = [ - 'username' => $username, - 'password' => $password, - 'created_at' => date('Y-m-d H:i:s'), - ]; - - if ($this->saveUsers($users)) { + + // 添加新用户 + $user = new User(); + $user->username = $username; + $user->password = $password; + $user->created_at = date('Y-m-d H:i:s'); + $user->save(); + return ['code' => 1, 'msg' => '添加成功']; - } else { - return ['code' => 0, 'msg' => '保存失败']; + } catch (\Exception $e) { + return ['code' => 0, 'msg' => '保存失败: ' . $e->getMessage()]; } } @@ -157,23 +164,20 @@ class UserService return ['code' => 0, 'msg' => '不能删除管理员账号']; } - $users = $this->getAllUsers(); - $newUsers = []; + $this->initDatabase(); - foreach ($users as $user) { - if (isset($user['username']) && $user['username'] !== $username) { - $newUsers[] = $user; + try { + $user = User::where('username', $username)->find(); + + if (!$user) { + return ['code' => 0, 'msg' => '用户不存在']; } - } - - if (count($newUsers) === count($users)) { - return ['code' => 0, 'msg' => '用户不存在']; - } - - if ($this->saveUsers($newUsers)) { + + $user->delete(); + return ['code' => 1, 'msg' => '删除成功']; - } else { - return ['code' => 0, 'msg' => '保存失败']; + } catch (\Exception $e) { + return ['code' => 0, 'msg' => '删除失败: ' . $e->getMessage()]; } } diff --git a/config/database.php b/config/database.php index 9d3f0d0..0dd613a 100644 --- a/config/database.php +++ b/config/database.php @@ -58,6 +58,24 @@ return [ 'fields_cache' => false, ], + // SQLite配置 + 'sqlite' => [ + // 数据库类型 + 'type' => 'sqlite', + // 数据库路径 + 'database' => '../runtime/database.db', + // 数据库编码 + 'charset' => 'utf8', + // 表前缀 + 'prefix' => '', + // 是否严格检查字段是否存在 + 'fields_strict' => true, + // 监听SQL + 'trigger_sql' => env('APP_DEBUG', true), + // 开启字段缓存 + 'fields_cache' => false, + ], + // 更多的数据库配置信息 ], ]; diff --git a/route/app.php b/route/app.php index 2bcf56e..9eac206 100644 --- a/route/app.php +++ b/route/app.php @@ -29,8 +29,10 @@ Route::post('crawler/getPositionInfo', 'crawler/getPositionInfo'); Route::post('crawler/batchGetPositionInfo', 'crawler/batchGetPositionInfo'); Route::post('crawler/fetchAllPositions', 'crawler/fetchAllPositions'); -// 用户管理路由(需要登录且为管理员) -Route::get('user', 'user/index'); -Route::get('user/getUsers', 'user/getUsers'); -Route::post('user/add', 'user/add'); -Route::post('user/delete', 'user/delete'); \ No newline at end of file +// 管理员路由(需要登录且为管理员) +Route::get('admin', 'admin/index'); +Route::get('admin/getUsers', 'admin/getUsers'); +Route::post('admin/addUser', 'admin/addUser'); +Route::post('admin/deleteUser', 'admin/deleteUser'); +Route::get('admin/getBaseUrl', 'admin/getBaseUrl'); +Route::post('admin/setBaseUrl', 'admin/setBaseUrl'); \ No newline at end of file diff --git a/view/user/index.html b/view/admin/index.html similarity index 77% rename from view/user/index.html rename to view/admin/index.html index 391caec..ec526eb 100644 --- a/view/user/index.html +++ b/view/admin/index.html @@ -3,7 +3,7 @@
-