feat: 登录页后端级别隔离,未登录时服务器不返回主页面源码

This commit is contained in:
2026-04-23 11:56:45 +08:00
parent 224de1bd69
commit a378943ec0
6 changed files with 240 additions and 209 deletions
+7 -2
View File
@@ -168,11 +168,16 @@ async def health_check():
# ==================== 页面路由 ==================== # ==================== 页面路由 ====================
@app.get("/", response_class=HTMLResponse) @app.get("/", response_class=HTMLResponse)
async def index(): async def index(request: Request):
"""返回主页""" """根据登录状态返回对应页面"""
token = request.cookies.get("token")
if token and verify_jwt_token(token):
index_file = STATIC_DIR / "index.html" index_file = STATIC_DIR / "index.html"
if index_file.exists(): if index_file.exists():
return HTMLResponse(content=index_file.read_text(encoding='utf-8')) return HTMLResponse(content=index_file.read_text(encoding='utf-8'))
login_file = STATIC_DIR / "login.html"
if login_file.exists():
return HTMLResponse(content=login_file.read_text(encoding='utf-8'))
return HTMLResponse(content="<h1>CapacityReport</h1><p>Static files not found.</p>") return HTMLResponse(content="<h1>CapacityReport</h1><p>Static files not found.</p>")
+9 -9
View File
@@ -2,15 +2,15 @@
## 最近更新记录 ## 最近更新记录
### 2026-04-23: 鉴权改为全屏登录页模式 + 退出登录 ### 2026-04-23: 登录页后端级别隔离 + 退出登录
- **问题**: 之前的鉴权方案只在 API 层拦截 401 后弹出登录弹窗,但主页面 HTML 内容已经完整渲染并暴露给用户(未登录也能看到界面),不符合安全预期。 - **问题**: 之前登录页和主页面在同一个 HTML 文件中,即使前端隐藏了主内容,用户仍能通过查看源码看到完整的主页面 HTML。
- **修复方案**: - **最终方案 — 后端级别隔离**:
- **登录页独立化**: 将登录从弹窗模式(`loginModal`)改为独立全屏登录页面(`#loginPage`),未登录时主内容区 `#appContainer` 设为 `display:none`,只显示登录页。 - **独立 `login.html`**: 创建 `static/login.html` 作为独立登录页面,自包含样式和逻辑,不引用主程序任何 JS/CSS。
- **Token 启动校验**: `DOMContentLoaded` 时先检查 `localStorage` 中的 token,无 token 直接显示登录页;有 token 则用 `/api/config` 接口验证有效性,401 则跳回登录页。 - **后端路由鉴权**: `app/main.py` 的 `/` 路由从 cookie 中读取 `token` 并验证,有效则返回 `index.html`,无效则返回 `login.html`。**未登录时服务器根本不会返回 `index.html` 的内容**。
- **退出登录功能**: 每个页面 header 右上角新增退出按钮(`⏻` 图标,`.logout-btn` 类),事件委托统一处理,清除 token 后显示登录页。 - **Cookie + localStorage 双存储**: 登录成功后 token 同时存入 cookie(供后端 `/` 路由判断)和 localStorage(供前端 API 请求 Bearer header)。
- **登录后免刷新**: 登录成功后如果应用模块未初始化则调用 `initApp()` 完成初始化,无需 `window.location.reload()`。 - **退出登录**: 每个页面 header 右上角有退出按钮(`⏻`),清除 cookie + localStorage 后跳转到 `/`(后端自动返回登录页)。
- **涉及文件**: `static/index.html`、`static/js/app.js`、`static/css/style.css` - **API 401 处理**: `showLoginModal()` 函数保留,内部清除 token 后 `window.location.href = '/'` 跳转到登录页。
- **注意事项**: `showLoginModal()` 函数保留作为兼容入口(API 返回 401 时调用),内部已重定向到 `showLoginPage()`。 - **涉及文件**: `static/login.html`(新增)、`app/main.py`、`static/index.html`、`static/js/app.js`、`static/css/style.css`
### 2026-04-22: 增加 JWT 鉴权和接口安全控制 ### 2026-04-22: 增加 JWT 鉴权和接口安全控制
- **问题背景**: 网管部门通报安全问题,扫描到项目存在暴露的 API 文档(/docs, /redoc, /openapi.json),并且 API 接口没有使用授权控制,要求快速增加鉴权。 - **问题背景**: 网管部门通报安全问题,扫描到项目存在暴露的 API 文档(/docs, /redoc, /openapi.json),并且 API 接口没有使用授权控制,要求快速增加鉴权。
-73
View File
@@ -123,79 +123,6 @@ body {
transition: background-color var(--td-transition), color var(--td-transition); transition: background-color var(--td-transition), color var(--td-transition);
} }
/* ==================== 登录页面 ==================== */
.login-page {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background: var(--td-bg-color-page);
z-index: 10001;
}
.login-container {
width: 380px;
padding: 48px 40px;
background: var(--td-bg-color-container);
border-radius: var(--td-radius-large);
box-shadow: var(--td-shadow-3);
text-align: center;
}
.login-logo {
font-size: 56px;
margin-bottom: 8px;
line-height: 1;
}
.login-title {
font-size: 22px;
font-weight: 700;
color: var(--td-text-color-primary);
margin-bottom: 4px;
letter-spacing: 0.5px;
}
.login-subtitle {
font-size: 14px;
color: var(--td-text-color-secondary);
margin-bottom: 32px;
}
.login-form {
text-align: left;
}
.login-form .form-group label {
display: block;
margin-bottom: 6px;
font-size: 13px;
font-weight: 500;
color: var(--td-text-color-primary);
}
.login-form .form-input {
width: 100%;
height: 40px;
padding: 0 12px;
border: 1px solid var(--td-border-color);
border-radius: var(--td-radius-default);
font-size: 14px;
color: var(--td-text-color-primary);
background: var(--td-bg-color-container);
transition: all var(--td-transition);
}
.login-form .form-input:focus {
outline: none;
border-color: var(--td-brand-color);
box-shadow: 0 0 0 2px var(--td-brand-color-focus);
}
/* ==================== 退出登录按钮 ==================== */ /* ==================== 退出登录按钮 ==================== */
.logout-btn { .logout-btn {
width: 32px; width: 32px;
+1 -21
View File
@@ -12,27 +12,7 @@
<script src="/static/lib/monaco/vs/loader.js"></script> <script src="/static/lib/monaco/vs/loader.js"></script>
</head> </head>
<body> <body>
<!-- 登录页面(未登录时显示) --> <div class="app" id="appContainer">
<div class="login-page" id="loginPage">
<div class="login-container">
<div class="login-logo">📊</div>
<h2 class="login-title">CapacityReport</h2>
<p class="login-subtitle">容量报表处理系统</p>
<div class="login-form">
<div class="form-group">
<label>账号</label>
<input type="text" id="loginUsername" class="form-input" value="root" readonly style="background-color: var(--td-bg-color-component); color: var(--td-text-color-secondary); cursor: not-allowed;">
</div>
<div class="form-group" style="margin-top: 16px;">
<label>密码</label>
<input type="password" id="loginPassword" class="form-input" placeholder="请输入密码" autofocus>
</div>
<button class="btn btn-primary btn-lg" id="loginBtn" style="width: 100%; margin-top: 24px;">登录</button>
</div>
</div>
</div>
<div class="app" id="appContainer" style="display: none;">
<!-- 侧边栏导航 --> <!-- 侧边栏导航 -->
<aside class="sidebar" id="sidebar"> <aside class="sidebar" id="sidebar">
<div class="logo"> <div class="logo">
+4 -100
View File
@@ -147,83 +147,16 @@ async function api(endpoint, options = {}) {
return response.json(); return response.json();
} }
function showLoginPage() {
const loginPage = $('#loginPage');
const appContainer = $('#appContainer');
if (loginPage) loginPage.style.display = 'flex';
if (appContainer) appContainer.style.display = 'none';
const loginInput = $('#loginPassword');
if (loginInput) {
loginInput.value = '';
loginInput.focus();
}
}
function hideLoginPage() {
const loginPage = $('#loginPage');
const appContainer = $('#appContainer');
if (loginPage) loginPage.style.display = 'none';
if (appContainer) appContainer.style.display = '';
}
function initLoginEvents() {
const loginBtn = $('#loginBtn');
const loginInput = $('#loginPassword');
if (!loginBtn || !loginInput) return;
loginInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') loginBtn.click();
});
loginBtn.addEventListener('click', async () => {
const usernameInput = $('#loginUsername');
const username = usernameInput ? usernameInput.value : 'root';
const password = loginInput.value;
if (!password) {
showToast('请输入密码', 'warning');
return;
}
try {
loginBtn.disabled = true;
loginBtn.textContent = '登录中...';
const res = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
if (!res.ok) {
const err = await res.json().catch(() => ({ detail: '登录失败' }));
throw new Error(err.detail || '账号或密码错误');
}
const data = await res.json();
if (data.success && data.token) {
localStorage.setItem('token', data.token);
hideLoginPage();
showToast('登录成功', 'success');
loginInput.value = '';
// 如果应用尚未初始化,执行初始化
if (!window.fileUploader) {
initApp();
}
}
} catch (err) {
showToast(err.message, 'error');
} finally {
loginBtn.disabled = false;
loginBtn.textContent = '登录';
}
});
}
function showLoginModal() { function showLoginModal() {
localStorage.removeItem('token'); localStorage.removeItem('token');
showLoginPage(); document.cookie = 'token=; path=/; max-age=0';
window.location.href = '/';
} }
function logout() { function logout() {
localStorage.removeItem('token'); localStorage.removeItem('token');
showLoginPage(); document.cookie = 'token=; path=/; max-age=0';
showToast('已退出登录', 'info'); window.location.href = '/';
} }
@@ -2275,36 +2208,7 @@ async function updateCacheSize() {
} }
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
// 初始化登录事件(始终注册,不依赖登录状态)
initLoginEvents();
// 检查 token 有效性
const token = localStorage.getItem('token');
if (!token) {
showLoginPage();
// 主题管理在登录页也需要
new ThemeManager();
return;
}
// 用一个轻量接口验证 token 是否仍然有效
fetch('/api/config', {
headers: { 'Authorization': `Bearer ${token}` }
}).then(res => {
if (res.status === 401) {
localStorage.removeItem('token');
showLoginPage();
new ThemeManager();
return;
}
// token 有效,初始化应用
hideLoginPage();
initApp(); initApp();
}).catch(() => {
// 网络错误时也尝试初始化(可能稍后恢复)
hideLoginPage();
initApp();
});
}); });
function initApp() { function initApp() {
+215
View File
@@ -0,0 +1,215 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录 - 容量报表处理程序</title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>📊</text></svg>">
<style>
:root {
--brand-color: #0052d9;
--brand-hover: #0034b5;
--text-primary: rgba(0, 0, 0, 0.9);
--text-secondary: rgba(0, 0, 0, 0.6);
--text-placeholder: rgba(0, 0, 0, 0.4);
--bg-page: #f3f3f3;
--bg-container: #ffffff;
--bg-component: #f3f3f3;
--border-color: #dcdcdc;
--shadow: 0 6px 30px 5px rgba(0,0,0,0.05), 0 16px 24px 2px rgba(0,0,0,0.04), 0 8px 10px -5px rgba(0,0,0,0.08);
--radius: 12px;
--transition: 0.2s cubic-bezier(0.38, 0, 0.24, 1);
--error-color: #e34d59;
--success-color: #00a870;
--warning-color: #ed7b2f;
--font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "PingFang SC", "Noto Sans SC", "Microsoft YaHei", sans-serif;
}
@media (prefers-color-scheme: dark) {
:root {
--brand-color: #4787f0;
--brand-hover: #618dff;
--text-primary: rgba(255, 255, 255, 0.9);
--text-secondary: rgba(255, 255, 255, 0.55);
--text-placeholder: rgba(255, 255, 255, 0.35);
--bg-page: #1b1b1b;
--bg-container: #242424;
--bg-component: #2c2c2c;
--border-color: #5e5e5e;
--shadow: 0 6px 30px 5px rgba(0,0,0,0.15), 0 16px 24px 2px rgba(0,0,0,0.12), 0 8px 10px -5px rgba(0,0,0,0.24);
}
}
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body { height: 100%; }
body {
font-family: var(--font-family);
background: var(--bg-page);
color: var(--text-primary);
display: flex;
align-items: center;
justify-content: center;
}
.login-container {
width: 380px;
padding: 48px 40px;
background: var(--bg-container);
border-radius: var(--radius);
box-shadow: var(--shadow);
text-align: center;
}
.login-logo { font-size: 56px; margin-bottom: 8px; line-height: 1; }
.login-title { font-size: 22px; font-weight: 700; color: var(--text-primary); margin-bottom: 4px; letter-spacing: 0.5px; }
.login-subtitle { font-size: 14px; color: var(--text-secondary); margin-bottom: 32px; }
.login-form { text-align: left; }
.form-group { margin-bottom: 0; }
.form-group label {
display: block;
margin-bottom: 6px;
font-size: 13px;
font-weight: 500;
color: var(--text-primary);
}
.form-input {
width: 100%;
height: 40px;
padding: 0 12px;
border: 1px solid var(--border-color);
border-radius: 6px;
font-size: 14px;
color: var(--text-primary);
background: var(--bg-container);
transition: all var(--transition);
outline: none;
}
.form-input:focus {
border-color: var(--brand-color);
box-shadow: 0 0 0 2px rgba(0, 82, 217, 0.2);
}
.form-input[readonly] {
background: var(--bg-component);
color: var(--text-secondary);
cursor: not-allowed;
}
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 100%;
height: 40px;
margin-top: 24px;
padding: 0 24px;
border-radius: 6px;
font-size: 14px;
font-weight: 500;
border: none;
cursor: pointer;
background: var(--brand-color);
color: #fff;
transition: all var(--transition);
}
.btn:hover { background: var(--brand-hover); }
.btn:disabled { opacity: 0.5; cursor: not-allowed; }
.toast {
position: fixed;
top: 24px;
left: 50%;
transform: translateX(-50%) translateY(-120%);
padding: 10px 20px;
border-radius: 6px;
font-size: 13px;
color: #fff;
opacity: 0;
transition: all 0.3s ease;
z-index: 9999;
white-space: nowrap;
}
.toast.show { transform: translateX(-50%) translateY(0); opacity: 1; }
.toast.error { background: var(--error-color); }
.toast.success { background: var(--success-color); }
.toast.warning { background: var(--warning-color); }
</style>
</head>
<body>
<div class="login-container">
<div class="login-logo">📊</div>
<h2 class="login-title">CapacityReport</h2>
<p class="login-subtitle">容量报表处理系统</p>
<form class="login-form" id="loginForm" autocomplete="on">
<div class="form-group">
<label for="username">账号</label>
<input type="text" id="username" name="username" class="form-input" value="root" readonly>
</div>
<div class="form-group" style="margin-top: 16px;">
<label for="password">密码</label>
<input type="password" id="password" name="password" class="form-input" placeholder="请输入密码" autofocus>
</div>
<button type="submit" class="btn" id="loginBtn">登录</button>
</form>
</div>
<div class="toast" id="toast"></div>
<script>
function showToast(msg, type) {
const t = document.getElementById('toast');
t.textContent = msg;
t.className = 'toast ' + (type || 'error');
t.classList.add('show');
setTimeout(() => { t.classList.remove('show'); }, 3000);
}
document.getElementById('loginForm').addEventListener('submit', async (e) => {
e.preventDefault();
const btn = document.getElementById('loginBtn');
const password = document.getElementById('password').value;
const username = document.getElementById('username').value;
if (!password) {
showToast('请输入密码', 'warning');
return;
}
btn.disabled = true;
btn.textContent = '登录中...';
try {
const res = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
if (!res.ok) {
const err = await res.json().catch(() => ({ detail: '登录失败' }));
throw new Error(err.detail || '账号或密码错误');
}
const data = await res.json();
if (data.success && data.token) {
localStorage.setItem('token', data.token);
// 设置 cookie 供后端 / 路由判断
document.cookie = `token=${data.token}; path=/; max-age=${86400 * 30}; SameSite=Lax`;
showToast('登录成功', 'success');
setTimeout(() => { window.location.href = '/'; }, 300);
}
} catch (err) {
showToast(err.message, 'error');
} finally {
btn.disabled = false;
btn.textContent = '登录';
}
});
</script>
</body>
</html>