This commit is contained in:
杨志
2026-01-21 08:39:32 +08:00
parent c36f73caa2
commit e964409bb7
10 changed files with 963 additions and 8 deletions

74
app/controller/Auth.php Normal file
View File

@@ -0,0 +1,74 @@
<?php
declare (strict_types = 1);
namespace app\controller;
use app\BaseController;
use app\service\UserService;
use think\facade\Session;
use think\facade\View;
/**
* 认证控制器
*/
class Auth extends BaseController
{
/**
* 显示登录页面
*/
public function login()
{
// 如果已登录,跳转到爬虫页面
if (Session::has('username')) {
return redirect('/crawler');
}
return View::fetch();
}
/**
* 处理登录
*/
public function doLogin()
{
$username = $this->request->param('username', '');
$password = $this->request->param('password', '');
if (empty($username) || empty($password)) {
return json([
'code' => 0,
'msg' => '请输入用户名和密码',
]);
}
$service = new UserService();
$user = $service->verifyLogin($username, $password);
if ($user === false) {
return json([
'code' => 0,
'msg' => '用户名或密码错误',
]);
}
// 保存登录信息到Session
Session::set('username', $user['username']);
Session::set('is_admin', $user['is_admin']);
return json([
'code' => 1,
'msg' => '登录成功',
'data' => [
'is_admin' => $user['is_admin'],
],
]);
}
/**
* 退出登录
*/
public function logout()
{
Session::clear();
return redirect('/login');
}
}

View File

@@ -4,6 +4,7 @@ declare (strict_types = 1);
namespace app\controller;
use app\BaseController;
use app\middleware\Auth;
use app\service\CrawlerService;
use think\facade\View;
@@ -12,6 +13,7 @@ use think\facade\View;
*/
class Crawler extends BaseController
{
protected $middleware = [Auth::class];
/**
* 显示爬虫工具首页
*/

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

@@ -0,0 +1,114 @@
<?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);
}
}

View File

@@ -6,5 +6,5 @@ return [
// 多语言加载
// \think\middleware\LoadLangPack::class,
// Session初始化
// \think\middleware\SessionInit::class
\think\middleware\SessionInit::class,
];

37
app/middleware/Auth.php Normal file
View File

@@ -0,0 +1,37 @@
<?php
declare (strict_types = 1);
namespace app\middleware;
/**
* 登录验证中间件
*/
class Auth
{
/**
* 处理请求
*
* @param \think\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, \Closure $next)
{
// 检查是否已登录
$username = session('username');
if (empty($username)) {
// 如果是AJAX请求返回JSON
if ($request->isAjax()) {
return json([
'code' => 0,
'msg' => '请先登录',
]);
}
// 否则跳转到登录页
return redirect('/login');
}
return $next($request);
}
}

189
app/service/UserService.php Normal file
View File

@@ -0,0 +1,189 @@
<?php
declare (strict_types = 1);
namespace app\service;
/**
* 用户服务类
* 用于处理用户账号管理相关逻辑
*/
class UserService
{
/**
* 账号数据文件路径
*/
private const USERS_FILE = 'users.json';
/**
* 管理员账号(固定)
*/
private const ADMIN_USERNAME = 'admin';
private const ADMIN_PASSWORD = '123456';
/**
* 初始化账号数据文件
*/
private function initUsersFile(): 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));
}
}
/**
* 获取账号数据文件路径
* @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;
}
/**
* 验证登录(包括管理员和普通用户)
* @param string $username
* @param string $password
* @return array|false 返回用户信息或false
*/
public function verifyLogin(string $username, string $password)
{
// 验证管理员账号
if ($username === self::ADMIN_USERNAME && $password === self::ADMIN_PASSWORD) {
return [
'username' => $username,
'is_admin' => true,
];
}
// 验证普通用户账号
$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,
];
}
}
}
return false;
}
/**
* 添加账号
* @param string $username
* @param string $password
* @return array ['code' => 1|0, 'msg' => string]
*/
public function addUser(string $username, string $password): array
{
if (empty($username) || empty($password)) {
return ['code' => 0, 'msg' => '用户名和密码不能为空'];
}
if ($username === self::ADMIN_USERNAME) {
return ['code' => 0, 'msg' => '不能添加管理员账号'];
}
$users = $this->getAllUsers();
// 检查用户名是否已存在
foreach ($users as $user) {
if (isset($user['username']) && $user['username'] === $username) {
return ['code' => 0, 'msg' => '用户名已存在'];
}
}
// 添加新用户
$users[] = [
'username' => $username,
'password' => $password,
'created_at' => date('Y-m-d H:i:s'),
];
if ($this->saveUsers($users)) {
return ['code' => 1, 'msg' => '添加成功'];
} else {
return ['code' => 0, 'msg' => '保存失败'];
}
}
/**
* 删除账号
* @param string $username
* @return array ['code' => 1|0, 'msg' => string]
*/
public function deleteUser(string $username): array
{
if ($username === self::ADMIN_USERNAME) {
return ['code' => 0, 'msg' => '不能删除管理员账号'];
}
$users = $this->getAllUsers();
$newUsers = [];
foreach ($users as $user) {
if (isset($user['username']) && $user['username'] !== $username) {
$newUsers[] = $user;
}
}
if (count($newUsers) === count($users)) {
return ['code' => 0, 'msg' => '用户不存在'];
}
if ($this->saveUsers($newUsers)) {
return ['code' => 1, 'msg' => '删除成功'];
} else {
return ['code' => 0, 'msg' => '保存失败'];
}
}
/**
* 检查是否为管理员
* @param string $username
* @return bool
*/
public function isAdmin(string $username): bool
{
return $username === self::ADMIN_USERNAME;
}
}

View File

@@ -16,10 +16,21 @@ Route::get('think', function () {
Route::get('hello/:name', 'index/hello');
// 爬虫工具路由
// 认证路由(不需要登录)
Route::get('login', 'auth/login');
Route::post('auth/doLogin', 'auth/doLogin');
Route::get('auth/logout', 'auth/logout');
// 爬虫工具路由(需要登录)
Route::get('crawler', 'crawler/index');
Route::post('crawler/getDsdmOptions', 'crawler/getDsdmOptions');
Route::post('crawler/getZwdmList', 'crawler/getZwdmList');
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');

View File

@@ -237,7 +237,13 @@
</head>
<body>
<div class="container">
<h1>职位信息爬虫工具</h1>
<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>
<!-- 第一步:填写基础信息 -->
<div class="form-section">
@@ -323,6 +329,9 @@
</div>
<script>
// API基础路径配置
const API_BASE_URL = ''; // 空字符串表示使用相对路径如需跨域可修改为完整URL'http://your-domain.com'
// 复用同一个aa确保selectPosition与getPositionTree的Referer一致
let lastAa = '';
let lastResults = [];
@@ -348,7 +357,7 @@
showMessage('dsdm-message', '正在获取地区选项...', 'info');
fetch('/crawler/getDsdmOptions', {
fetch(API_BASE_URL + '/crawler/getDsdmOptions', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
@@ -403,7 +412,7 @@
showMessage('zwdm-message', '正在获取职位代码列表...', 'info');
fetch('/crawler/getZwdmList', {
fetch(API_BASE_URL + '/crawler/getZwdmList', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
@@ -495,7 +504,7 @@
showMessage('result-message', `正在获取 ${zwdmList.length} 个职位的信息,请稍候...`, 'info');
fetch('/crawler/batchGetPositionInfo', {
fetch(API_BASE_URL + '/crawler/batchGetPositionInfo', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
@@ -637,7 +646,7 @@
// 逐条获取职位详情
for (let i = 0; i < codes.length; i++) {
const code = codes[i];
const infoResp = await fetch('/crawler/getPositionInfo', {
const infoResp = await fetch(API_BASE_URL + '/crawler/getPositionInfo', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `zwdm=${encodeURIComponent(code)}&examid=${encodeURIComponent(examid)}&cookies=${encodeURIComponent(JSON.stringify(cookieData))}`

181
view/login.html Normal file
View File

@@ -0,0 +1,181 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录 - 职位信息爬虫工具</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
.login-container {
background: #fff;
border-radius: 10px;
box-shadow: 0 10px 40px rgba(0,0,0,0.2);
padding: 40px;
width: 100%;
max-width: 400px;
}
h1 {
color: #333;
margin-bottom: 30px;
text-align: center;
font-size: 24px;
}
.form-group {
margin-bottom: 20px;
}
.form-group label {
display: block;
margin-bottom: 8px;
color: #333;
font-weight: 500;
}
.form-group input {
width: 100%;
padding: 12px;
border: 1px solid #ddd;
border-radius: 6px;
font-size: 14px;
transition: border-color 0.3s;
}
.form-group input:focus {
outline: none;
border-color: #667eea;
}
.btn {
width: 100%;
padding: 12px;
background: #667eea;
color: #fff;
border: none;
border-radius: 6px;
cursor: pointer;
font-size: 16px;
font-weight: 500;
transition: background 0.3s;
}
.btn:hover {
background: #5568d3;
}
.btn:disabled {
background: #ccc;
cursor: not-allowed;
}
.message {
padding: 12px;
border-radius: 6px;
margin-bottom: 20px;
text-align: center;
}
.message.success {
background: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.message.error {
background: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
.message.info {
background: #d1ecf1;
color: #0c5460;
border: 1px solid #bee5eb;
}
</style>
</head>
<body>
<div class="login-container">
<h1>职位信息爬虫工具</h1>
<div id="message"></div>
<form id="loginForm">
<div class="form-group">
<label for="username">用户名:</label>
<input type="text" id="username" name="username" required autofocus>
</div>
<div class="form-group">
<label for="password">密码:</label>
<input type="password" id="password" name="password" required>
</div>
<button type="submit" class="btn" id="loginBtn">登录</button>
</form>
</div>
<script>
const API_BASE_URL = '';
document.getElementById('loginForm').addEventListener('submit', function(e) {
e.preventDefault();
const username = document.getElementById('username').value.trim();
const password = document.getElementById('password').value.trim();
const loginBtn = document.getElementById('loginBtn');
if (!username || !password) {
showMessage('请输入用户名和密码', 'error');
return;
}
loginBtn.disabled = true;
loginBtn.textContent = '登录中...';
fetch(API_BASE_URL + '/auth/doLogin', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`
})
.then(response => response.json())
.then(data => {
if (data.code === 1) {
showMessage('登录成功,正在跳转...', 'success');
setTimeout(() => {
window.location.href = '/crawler';
}, 500);
} else {
showMessage(data.msg || '登录失败', 'error');
loginBtn.disabled = false;
loginBtn.textContent = '登录';
}
})
.catch(error => {
showMessage('请求失败: ' + error.message, 'error');
loginBtn.disabled = false;
loginBtn.textContent = '登录';
});
});
function showMessage(message, type) {
const messageDiv = document.getElementById('message');
messageDiv.innerHTML = `<div class="message ${type}">${message}</div>`;
}
</script>
</body>
</html>

338
view/user/index.html Normal file
View File

@@ -0,0 +1,338 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>账号管理 - 职位信息爬虫工具</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background: #f5f5f5;
padding: 20px;
}
.container {
max-width: 1000px;
margin: 0 auto;
background: #fff;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
padding: 30px;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30px;
padding-bottom: 20px;
border-bottom: 2px solid #4CAF50;
}
h1 {
color: #333;
font-size: 24px;
}
.nav-links {
display: flex;
gap: 15px;
}
.nav-links a {
color: #2196F3;
text-decoration: none;
padding: 8px 15px;
border-radius: 4px;
transition: background 0.3s;
}
.nav-links a:hover {
background: #e3f2fd;
}
.form-section {
margin-bottom: 30px;
padding: 20px;
background: #f9f9f9;
border-radius: 6px;
border: 1px solid #e0e0e0;
}
.form-section h2 {
font-size: 18px;
color: #555;
margin-bottom: 15px;
}
.form-group {
margin-bottom: 15px;
}
.form-group label {
display: block;
margin-bottom: 5px;
color: #333;
font-weight: 500;
}
.form-group input {
width: 100%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 14px;
}
.btn {
padding: 10px 20px;
background: #4CAF50;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
transition: background 0.3s;
}
.btn:hover {
background: #45a049;
}
.btn-danger {
background: #f44336;
}
.btn-danger:hover {
background: #da190b;
}
.message {
padding: 12px;
border-radius: 4px;
margin-bottom: 15px;
}
.message.success {
background: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.message.error {
background: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
table {
width: 100%;
border-collapse: collapse;
background: #fff;
}
table th,
table td {
padding: 12px;
text-align: left;
border: 1px solid #ddd;
}
table th {
background: #4CAF50;
color: #fff;
font-weight: 600;
}
table tr:nth-child(even) {
background: #f9f9f9;
}
table tr:hover {
background: #f0f0f0;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>账号管理</h1>
<div class="nav-links">
<a href="/crawler">爬虫工具</a>
<a href="/auth/logout">退出登录</a>
</div>
</div>
<!-- 添加账号 -->
<div class="form-section">
<h2>添加账号</h2>
<div id="add-message"></div>
<div class="form-group">
<label for="new-username">用户名:</label>
<input type="text" id="new-username" placeholder="请输入用户名">
</div>
<div class="form-group">
<label for="new-password">密码:</label>
<input type="password" id="new-password" placeholder="请输入密码">
</div>
<button class="btn" onclick="addUser()">添加账号</button>
</div>
<!-- 账号列表 -->
<div class="form-section">
<h2>账号列表</h2>
<div id="list-message"></div>
<table id="users-table">
<thead>
<tr>
<th>用户名</th>
<th>创建时间</th>
<th>操作</th>
</tr>
</thead>
<tbody id="users-tbody">
<tr>
<td colspan="3" style="text-align: center;">加载中...</td>
</tr>
</tbody>
</table>
</div>
</div>
<script>
const API_BASE_URL = '';
// 页面加载时获取账号列表
window.onload = function() {
loadUsers();
};
// 加载账号列表
function loadUsers() {
fetch(API_BASE_URL + '/user/getUsers', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
})
.then(response => response.json())
.then(data => {
if (data.code === 1) {
displayUsers(data.data);
} else {
showMessage('list-message', data.msg || '获取失败', 'error');
}
})
.catch(error => {
showMessage('list-message', '请求失败: ' + error.message, 'error');
});
}
// 显示账号列表
function displayUsers(users) {
const tbody = document.getElementById('users-tbody');
tbody.innerHTML = '';
// 添加管理员账号(只显示,不能删除)
const adminRow = document.createElement('tr');
adminRow.innerHTML = `
<td>admin</td>
<td>-</td>
<td><span style="color: #999;">系统管理员</span></td>
`;
tbody.appendChild(adminRow);
// 添加普通用户
if (users.length === 0) {
const row = document.createElement('tr');
row.innerHTML = '<td colspan="3" style="text-align: center;">暂无账号</td>';
tbody.appendChild(row);
} else {
users.forEach(user => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${user.username || ''}</td>
<td>${user.created_at || '-'}</td>
<td>
<button class="btn btn-danger" onclick="deleteUser('${user.username}')">删除</button>
</td>
`;
tbody.appendChild(row);
});
}
}
// 添加账号
function addUser() {
const username = document.getElementById('new-username').value.trim();
const password = document.getElementById('new-password').value.trim();
if (!username || !password) {
showMessage('add-message', '请输入用户名和密码', 'error');
return;
}
fetch(API_BASE_URL + '/user/add', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`
})
.then(response => response.json())
.then(data => {
if (data.code === 1) {
showMessage('add-message', data.msg || '添加成功', 'success');
document.getElementById('new-username').value = '';
document.getElementById('new-password').value = '';
loadUsers();
} else {
showMessage('add-message', data.msg || '添加失败', 'error');
}
})
.catch(error => {
showMessage('add-message', '请求失败: ' + error.message, 'error');
});
}
// 删除账号
function deleteUser(username) {
if (!confirm('确定要删除账号 "' + username + '" 吗?')) {
return;
}
fetch(API_BASE_URL + '/user/delete', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `username=${encodeURIComponent(username)}`
})
.then(response => response.json())
.then(data => {
if (data.code === 1) {
showMessage('list-message', data.msg || '删除成功', 'success');
loadUsers();
} else {
showMessage('list-message', data.msg || '删除失败', 'error');
}
})
.catch(error => {
showMessage('list-message', '请求失败: ' + error.message, 'error');
});
}
// 显示消息
function showMessage(containerId, message, type) {
const container = document.getElementById(containerId);
container.innerHTML = `<div class="message ${type}">${message}</div>`;
}
</script>
</body>
</html>