This commit is contained in:
杨志
2026-01-21 08:53:45 +08:00
parent f9c34127c7
commit a962e06a18
14 changed files with 574 additions and 222 deletions

114
app/controller/Admin.php Normal file
View File

@@ -0,0 +1,114 @@
<?php
declare (strict_types = 1);
namespace app\controller;
use app\BaseController;
use app\middleware\Admin;
use app\service\ConfigService;
use app\service\UserService;
use think\facade\View;
/**
* 管理员控制器
*/
class Admin extends BaseController
{
protected $middleware = [Admin::class];
/**
* 显示管理首页
*/
public function index()
{
return View::fetch();
}
/**
* 获取所有账号列表
*/
public function getUsers()
{
$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' => '获取成功',
]);
}
/**
* 添加账号
*/
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);
}
}

View File

@@ -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();
}

View File

@@ -1,114 +0,0 @@
<?php
declare (strict_types = 1);
namespace app\controller;
use app\BaseController;
use app\middleware\Auth;
use app\service\UserService;
use think\facade\Session;
use think\facade\View;
/**
* 用户管理控制器
*/
class User extends BaseController
{
protected $middleware = [Auth::class];
/**
* 显示账号管理页面
*/
public function index()
{
// 检查是否为管理员
if (!Session::get('is_admin', false)) {
return json([
'code' => 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);
}
}

54
app/middleware/Admin.php Normal file
View File

@@ -0,0 +1,54 @@
<?php
declare (strict_types = 1);
namespace app\middleware;
use think\facade\Session;
/**
* 管理员权限验证中间件
*/
class Admin
{
/**
* 处理请求
*
* @param \think\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, \Closure $next)
{
// 检查是否已登录
$username = Session::get('username');
if (empty($username)) {
// 如果是AJAX请求返回JSON
if ($request->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);
}
}

25
app/model/Config.php Normal file
View File

@@ -0,0 +1,25 @@
<?php
declare (strict_types = 1);
namespace app\model;
use think\Model;
/**
* 配置模型
*/
class Config extends Model
{
// 设置数据库连接
protected $connection = 'sqlite';
// 设置表名
protected $name = 'configs';
// 自动写入时间戳
protected $autoWriteTimestamp = true;
// 定义时间戳字段名
protected $createTime = 'created_at';
protected $updateTime = 'updated_at';
}

28
app/model/User.php Normal file
View File

@@ -0,0 +1,28 @@
<?php
declare (strict_types = 1);
namespace app\model;
use think\Model;
/**
* 用户模型
*/
class User extends Model
{
// 设置数据库连接
protected $connection = 'sqlite';
// 设置表名
protected $name = 'users';
// 自动写入时间戳
protected $autoWriteTimestamp = true;
// 定义时间戳字段名
protected $createTime = 'created_at';
protected $updateTime = false;
// 隐藏字段
protected $hidden = ['password'];
}

View File

@@ -0,0 +1,143 @@
<?php
declare (strict_types = 1);
namespace app\service;
use app\model\Config;
use think\facade\Db;
/**
* 配置服务类
*/
class ConfigService
{
/**
* 初始化数据库表
*/
private function initDatabase(): void
{
$dbPath = dirname(dirname(__DIR__)) . '/runtime/database.db';
$dbDir = dirname($dbPath);
if (!is_dir($dbDir)) {
mkdir($dbDir, 0755, true);
}
try {
$connection = Db::connect('sqlite');
// 创建配置表(如果不存在)
$sql = "CREATE TABLE IF NOT EXISTS configs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
config_key VARCHAR(100) NOT NULL UNIQUE,
config_value TEXT NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL
)";
$connection->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);
}
}

View File

@@ -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);

View File

@@ -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,33 +19,38 @@ 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);
}
file_put_contents($filePath, json_encode([], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}
}
$dbPath = dirname(dirname(__DIR__)) . '/runtime/database.db';
$dbDir = dirname($dbPath);
/**
* 获取账号数据文件路径
* @return string
*/
private function getUsersFilePath(): string
{
// 获取项目根目录
$rootPath = dirname(dirname(__DIR__));
$runtimePath = $rootPath . '/runtime';
if (!is_dir($runtimePath)) {
mkdir($runtimePath, 0755, true);
// 确保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);
}
}
return $runtimePath . '/' . self::USERS_FILE;
}
/**
@@ -56,23 +59,25 @@ class UserService
*/
public function getAllUsers(): array
{
$this->initUsersFile();
$filePath = $this->getUsersFilePath();
$content = file_get_contents($filePath);
$users = json_decode($content, true);
return is_array($users) ? $users : [];
}
$this->initDatabase();
/**
* 保存账号数据
* @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;
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'),
];
// 添加新用户
$user = new User();
$user->username = $username;
$user->password = $password;
$user->created_at = date('Y-m-d H:i:s');
$user->save();
if ($this->saveUsers($users)) {
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' => '用户不存在'];
}
$user->delete();
if ($this->saveUsers($newUsers)) {
return ['code' => 1, 'msg' => '删除成功'];
} else {
return ['code' => 0, 'msg' => '保存失败'];
} catch (\Exception $e) {
return ['code' => 0, 'msg' => '删除失败: ' . $e->getMessage()];
}
}

View File

@@ -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,
],
// 更多的数据库配置信息
],
];

View File

@@ -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');
// 管理路由(需要登录且为管理员)
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');

View File

@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>账号管理 - 职位信息爬虫工具</title>
<title>系统管理 - 职位信息爬虫工具</title>
<style>
* {
margin: 0;
@@ -18,7 +18,7 @@
}
.container {
max-width: 1000px;
max-width: 1200px;
margin: 0 auto;
background: #fff;
border-radius: 8px;
@@ -162,13 +162,25 @@
<body>
<div class="container">
<div class="header">
<h1>账号管理</h1>
<h1>系统管理</h1>
<div class="nav-links">
<a href="/crawler">爬虫工具</a>
<a href="/auth/logout">退出登录</a>
</div>
</div>
<!-- BASE_URL配置 -->
<div class="form-section">
<h2>BASE_URL配置</h2>
<div id="baseurl-message"></div>
<div class="form-group">
<label for="base-url">BASE_URL域名和端口</label>
<input type="text" id="base-url" placeholder="例如http://gzrsks.oumakspt.com:62">
<small style="color: #666; margin-top: 5px; display: block;">这是爬虫目标网站的基础URL不含路径</small>
</div>
<button class="btn" onclick="saveBaseUrl()">保存配置</button>
</div>
<!-- 添加账号 -->
<div class="form-section">
<h2>添加账号</h2>
@@ -208,14 +220,65 @@
<script>
const API_BASE_URL = '';
// 页面加载时获取账号列表
// 页面加载时获取配置和账号列表
window.onload = function() {
loadBaseUrl();
loadUsers();
};
// 加载BASE_URL配置
function loadBaseUrl() {
fetch(API_BASE_URL + '/admin/getBaseUrl', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
})
.then(response => response.json())
.then(data => {
if (data.code === 1) {
document.getElementById('base-url').value = data.data.base_url || '';
} else {
showMessage('baseurl-message', data.msg || '获取失败', 'error');
}
})
.catch(error => {
showMessage('baseurl-message', '请求失败: ' + error.message, 'error');
});
}
// 保存BASE_URL配置
function saveBaseUrl() {
const baseUrl = document.getElementById('base-url').value.trim();
if (!baseUrl) {
showMessage('baseurl-message', 'BASE_URL不能为空', 'error');
return;
}
fetch(API_BASE_URL + '/admin/setBaseUrl', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `base_url=${encodeURIComponent(baseUrl)}`
})
.then(response => response.json())
.then(data => {
if (data.code === 1) {
showMessage('baseurl-message', data.msg || '保存成功', 'success');
} else {
showMessage('baseurl-message', data.msg || '保存失败', 'error');
}
})
.catch(error => {
showMessage('baseurl-message', '请求失败: ' + error.message, 'error');
});
}
// 加载账号列表
function loadUsers() {
fetch(API_BASE_URL + '/user/getUsers', {
fetch(API_BASE_URL + '/admin/getUsers', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
@@ -278,7 +341,7 @@
return;
}
fetch(API_BASE_URL + '/user/add', {
fetch(API_BASE_URL + '/admin/addUser', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
@@ -307,7 +370,7 @@
return;
}
fetch(API_BASE_URL + '/user/delete', {
fetch(API_BASE_URL + '/admin/deleteUser', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',

View File

@@ -157,7 +157,12 @@
if (data.code === 1) {
showMessage('登录成功,正在跳转...', 'success');
setTimeout(() => {
window.location.href = '/crawler';
// 根据账号类型跳转到不同页面
if (data.data && data.data.is_admin) {
window.location.href = '/admin';
} else {
window.location.href = '/crawler';
}
}, 500);
} else {
showMessage(data.msg || '登录失败', 'error');

View File

@@ -240,7 +240,6 @@
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h1 style="margin: 0;">职位信息爬虫工具</h1>
<div style="display: flex; gap: 15px;">
<a href="/user" style="color: #2196F3; text-decoration: none; padding: 8px 15px; border-radius: 4px; background: #e3f2fd;">账号管理</a>
<a href="/auth/logout" style="color: #f44336; text-decoration: none; padding: 8px 15px; border-radius: 4px; background: #ffebee;">退出登录</a>
</div>
</div>