feat: add JWT authentication and AGENTS.md
This commit is contained in:
81
AGENTS.md
Normal file
81
AGENTS.md
Normal file
@@ -0,0 +1,81 @@
|
||||
# AGENTS.md
|
||||
|
||||
## Project overview
|
||||
- Full-stack todo app: **Vue 3 + Element Plus** (WebUI/) + **FastAPI + SQLAlchemy** (api/)
|
||||
- **Python 3.10+, Node 18+**; SQLite database
|
||||
- Single `master` branch, no CI/CD
|
||||
|
||||
## Quick commands
|
||||
|
||||
```powershell
|
||||
# Install Python deps (required before first run)
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Full-stack one-shot (builds frontend, then starts backend on :23994)
|
||||
python main.py
|
||||
|
||||
# Frontend dev only (hot-reload on :5173, proxies /api → :23994)
|
||||
cd WebUI; npm run dev
|
||||
|
||||
# Backend only
|
||||
cd api; uvicorn app.main:app --host 0.0.0.0 --port 23994
|
||||
|
||||
# Type-check frontend (noEmit; uses project references tsconfig)
|
||||
cd WebUI; npm run typecheck
|
||||
|
||||
# Run the one hand-written test (backend must be running on :23994)
|
||||
python tests/test_accounts.py
|
||||
```
|
||||
|
||||
**Build order matters:** `python main.py` automatically compiles WebUI (`npm install` + `npm run build`), copies `WebUI/dist/` → `api/webui/`, then starts uvicorn. It checks timestamps to skip rebuilds when frontend is unchanged.
|
||||
|
||||
**Import path:** `main.py` injects `api/` into `sys.path` (no `os.chdir`). Backend imports resolve relative to `api/` — e.g. `from app.config import ...`, not `from api.app.config import ...`.
|
||||
|
||||
**Port conflict:** `main.py` will auto-kill any process already listening on port 23994 before starting. If you have another instance running, it will be terminated without warning.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Backend (`api/app/`)
|
||||
- **Config is hardcoded** in `api/app/config.py` — no `.env`, no `os.getenv()`. Port `23994`, CORS origins `["http://localhost:5173", "http://localhost:23994"]`. Note: `pydantic-settings` is in `requirements.txt` but unused.
|
||||
- **SQLite path** is computed relative to `api/` via `__file__` — safe regardless of cwd. `connect_args={"check_same_thread": False}` for FastAPI async compatibility.
|
||||
- **`database.py:init_db()`** auto-creates tables on startup (`create_all`) and auto-adds missing columns via `ALTER TABLE ADD COLUMN` (no Alembic). Columns that are non-nullable with no default are skipped.
|
||||
- **UserSettings is a singleton**: always id=1, auto-created on first `GET`.
|
||||
- **Account balance changes** auto-create `AccountHistory` records in `update_balance()`.
|
||||
- **Habit checkins for the same day** accumulate count (not new rows), enforced by a `(habit_id, checkin_date)` unique constraint.
|
||||
- **Anniversaries / DebtInstallments** have computed fields (`next_date`, `days_until`, `year_count` / `remaining_periods`) calculated at request time, not stored in DB.
|
||||
- **`task_tags` M2M table** is defined in `models/tag.py` (not `models/task.py`).
|
||||
- **Update schemas** use `clearable_fields` + `exclude_unset=True` to distinguish "field not sent" from "field sent as null".
|
||||
- **JWT authentication** — mandatory for all `/api/*` routes except `/api/auth/*` and `/health`. Default password: `elysia`. Login via `POST /api/auth/login`. Token key in localStorage: `elysia_auth_token`. Frontend axios interceptor auto-attaches `Authorization: Bearer <token>`.
|
||||
|
||||
### Frontend (`WebUI/`)
|
||||
- Vue Router uses `createWebHistory()` (HTML5 history mode) — **requires the backend SPA fallback** (`/{full_path:path}` → `index.html`).
|
||||
- Vite dev proxy forwards `/api` → `http://localhost:23994`.
|
||||
- `@` alias maps to `src/`.
|
||||
- Global styles in SCSS (`src/styles/`).
|
||||
- 8 Pinia stores; Element Plus icons registered globally in `main.ts`.
|
||||
- Element Plus uses Chinese locale (`zh-cn`).
|
||||
|
||||
### Route registration order matters
|
||||
The `/health` endpoint must be registered **before** the `/{full_path:path}` SPA fallback catch-all, otherwise `/health` requests return `index.html`. This is enforced in `api/app/main.py:114` — do not reorder these registrations.
|
||||
|
||||
### Docker
|
||||
- `Dockerfile` copies pre-built `api/webui/` — you must build frontend before `docker build`.
|
||||
- Docker CMD is an inline `python -c` one-liner that injects `api/` into `sys.path` and starts uvicorn. No separate entrypoint script.
|
||||
- `docker-compose.yml` mounts `api/data/` and `api/logs/` for persistence; `api/webui/` is read-only.
|
||||
|
||||
## Testing quirks
|
||||
- Only one test file: `tests/test_accounts.py` — **hand-written, no framework** (not pytest). It counts pass/fail manually and uses `requests` directly against `localhost:23994`.
|
||||
- Backend must be running before executing tests.
|
||||
- **The test permanently mutates the database** — Section 15 deliberately leaves test data in place for UI display. Run it on a disposable database copy or reset manually if you need a clean state.
|
||||
- **The test sends no auth headers** and will fail with 401 if JWT auth is enforced. You must first `POST /api/auth/login` with `{"password": "elysia"}` to get a token, then include `Authorization: Bearer <token>` in requests, or temporarily comment out the auth middleware for testing.
|
||||
- No test coverage for tasks, habits, anniversaries, or tags.
|
||||
|
||||
## What's missing (agents should not assume)
|
||||
- No linter, formatter, pre-commit hooks, or CI/CD
|
||||
- No `.env` or environment variable loading
|
||||
- No database migrations framework (Alembic)
|
||||
|
||||
## Additional notes
|
||||
- Swagger UI at `/docs` when backend is running — the live, auto-generated API reference.
|
||||
- `python-multipart` in `requirements.txt` is required for FastAPI to parse form data (not optional).
|
||||
- `sass` is a runtime `dependency` (not `devDependency`) in `package.json` — unusual, but intentional.
|
||||
1580
API_DOCS.md
1580
API_DOCS.md
File diff suppressed because it is too large
Load Diff
@@ -121,7 +121,7 @@ npm run dev
|
||||
|
||||
## API 概览
|
||||
|
||||
所有接口均以 `/api` 为前缀,详细的请求/响应格式参见 [API_DOCS.md](./API_DOCS.md) 或访问 `/docs` 查看 Swagger 文档。
|
||||
所有接口均以 `/api` 为前缀,启动后端后访问 `/docs` 查看 Swagger 文档。
|
||||
|
||||
| 模块 | 前缀 | 说明 |
|
||||
|------|------|------|
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useCategoryStore } from '@/stores/useCategoryStore'
|
||||
import { useTagStore } from '@/stores/useTagStore'
|
||||
import { useUIStore } from '@/stores/useUIStore'
|
||||
import { useUserSettingsStore } from '@/stores/useUserSettingsStore'
|
||||
import { useAuthStore } from '@/stores/useAuthStore'
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
import AppHeader from '@/components/AppHeader.vue'
|
||||
import TaskDialog from '@/components/TaskDialog.vue'
|
||||
@@ -18,6 +19,7 @@ const categoryStore = useCategoryStore()
|
||||
const tagStore = useTagStore()
|
||||
const uiStore = useUIStore()
|
||||
const userSettingsStore = useUserSettingsStore()
|
||||
const authStore = useAuthStore()
|
||||
|
||||
// 路由变化时同步 currentView
|
||||
watch(() => route.meta.view, (view) => {
|
||||
@@ -33,6 +35,8 @@ watch(() => userSettingsStore.siteName, (name) => {
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
if (!authStore.isLoggedIn) return
|
||||
|
||||
await userSettingsStore.fetchAndSync()
|
||||
|
||||
// 根据用户设置初始化默认排序
|
||||
@@ -63,41 +67,46 @@ onMounted(async () => {
|
||||
<template>
|
||||
<el-config-provider :locale="zhCn">
|
||||
<div class="app-container">
|
||||
<div class="decoration-star" style="top: 20%; right: 8%; animation-delay: 0.5s;"></div>
|
||||
<div class="decoration-star" style="top: 60%; left: 3%; animation-delay: 1s;"></div>
|
||||
<div class="decoration-star" style="top: 80%; right: 5%; animation-delay: 1.5s;"></div>
|
||||
<template v-if="route.name !== 'login'">
|
||||
<div class="decoration-star" style="top: 20%; right: 8%; animation-delay: 0.5s;"></div>
|
||||
<div class="decoration-star" style="top: 60%; left: 3%; animation-delay: 1s;"></div>
|
||||
<div class="decoration-star" style="top: 80%; right: 5%; animation-delay: 1.5s;"></div>
|
||||
|
||||
<AppHeader />
|
||||
<AppHeader />
|
||||
|
||||
<div class="app-main">
|
||||
<main
|
||||
class="main-content"
|
||||
:class="{
|
||||
'full-width': uiStore.currentView !== 'list'
|
||||
}"
|
||||
>
|
||||
<router-view v-slot="{ Component }">
|
||||
<Transition name="view-fade" mode="out-in">
|
||||
<component :is="Component" />
|
||||
</Transition>
|
||||
</router-view>
|
||||
</main>
|
||||
</div>
|
||||
<div class="app-main">
|
||||
<main
|
||||
class="main-content"
|
||||
:class="{
|
||||
'full-width': uiStore.currentView !== 'list'
|
||||
}"
|
||||
>
|
||||
<router-view v-slot="{ Component }">
|
||||
<Transition name="view-fade" mode="out-in">
|
||||
<component :is="Component" />
|
||||
</Transition>
|
||||
</router-view>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<div v-if="uiStore.currentView !== 'settings' && uiStore.currentView !== 'profile' && uiStore.currentView !== 'habits' && uiStore.currentView !== 'anniversaries' && uiStore.currentView !== 'assets'" class="fab-container">
|
||||
<el-button
|
||||
type="primary"
|
||||
circle
|
||||
size="large"
|
||||
class="add-btn btn-glow"
|
||||
@click="uiStore.openTaskDialog()"
|
||||
>
|
||||
<el-icon :size="24"><Plus /></el-icon>
|
||||
</el-button>
|
||||
</div>
|
||||
<div v-if="uiStore.currentView !== 'settings' && uiStore.currentView !== 'profile' && uiStore.currentView !== 'habits' && uiStore.currentView !== 'anniversaries' && uiStore.currentView !== 'assets'" class="fab-container">
|
||||
<el-button
|
||||
type="primary"
|
||||
circle
|
||||
size="large"
|
||||
class="add-btn btn-glow"
|
||||
@click="uiStore.openTaskDialog()"
|
||||
>
|
||||
<el-icon :size="24"><Plus /></el-icon>
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
<TaskDialog />
|
||||
<CategoryDialog />
|
||||
<TaskDialog />
|
||||
<CategoryDialog />
|
||||
</template>
|
||||
<router-view v-else v-slot="{ Component }">
|
||||
<component :is="Component" />
|
||||
</router-view>
|
||||
</div>
|
||||
</el-config-provider>
|
||||
</template>
|
||||
|
||||
19
WebUI/src/api/auth.ts
Normal file
19
WebUI/src/api/auth.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { post } from './request'
|
||||
|
||||
export interface LoginResponse {
|
||||
access_token: string
|
||||
token_type: string
|
||||
}
|
||||
|
||||
export interface ChangePasswordData {
|
||||
old_password: string
|
||||
new_password: string
|
||||
}
|
||||
|
||||
export function login(password: string): Promise<LoginResponse> {
|
||||
return post<LoginResponse>('/auth/login', { password })
|
||||
}
|
||||
|
||||
export function changePassword(data: ChangePasswordData): Promise<{ message: string }> {
|
||||
return post<{ message: string }>('/auth/change-password', data)
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios'
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
const TOKEN_KEY = 'elysia_auth_token'
|
||||
|
||||
const instance: AxiosInstance = axios.create({
|
||||
baseURL: '/api',
|
||||
timeout: 10000,
|
||||
@@ -9,6 +11,14 @@ const instance: AxiosInstance = axios.create({
|
||||
}
|
||||
})
|
||||
|
||||
instance.interceptors.request.use((config) => {
|
||||
const token = localStorage.getItem(TOKEN_KEY)
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
return config
|
||||
})
|
||||
|
||||
instance.interceptors.response.use(
|
||||
(response: AxiosResponse) => {
|
||||
return response
|
||||
@@ -28,7 +38,9 @@ instance.interceptors.response.use(
|
||||
break
|
||||
case 401:
|
||||
message = '登录状态已失效~'
|
||||
break
|
||||
localStorage.removeItem(TOKEN_KEY)
|
||||
window.location.href = '/login'
|
||||
return Promise.reject(error)
|
||||
case 403:
|
||||
message = '没有权限访问呢~'
|
||||
break
|
||||
|
||||
@@ -3,9 +3,11 @@ import { computed } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import { useUIStore } from '@/stores/useUIStore'
|
||||
import { useUserSettingsStore } from '@/stores/useUserSettingsStore'
|
||||
import { useAuthStore } from '@/stores/useAuthStore'
|
||||
|
||||
const uiStore = useUIStore()
|
||||
const userSettingsStore = useUserSettingsStore()
|
||||
const authStore = useAuthStore()
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
|
||||
@@ -21,6 +23,11 @@ function setView(view: string) {
|
||||
}
|
||||
|
||||
function handleCommand(command: string) {
|
||||
if (command === 'logout') {
|
||||
authStore.logout()
|
||||
router.push('/login')
|
||||
return
|
||||
}
|
||||
router.push(`/${command}`)
|
||||
}
|
||||
|
||||
@@ -125,6 +132,10 @@ const currentRouteName = computed(() => route.name as string)
|
||||
<el-icon><Setting /></el-icon>
|
||||
<span>偏好设置</span>
|
||||
</el-dropdown-item>
|
||||
<el-dropdown-item command="logout" divided>
|
||||
<el-icon><SwitchButton /></el-icon>
|
||||
<span>退出登录</span>
|
||||
</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
|
||||
@@ -3,6 +3,12 @@ import type { RouteRecordRaw } from 'vue-router'
|
||||
import { useUserSettingsStore } from '@/stores/useUserSettingsStore'
|
||||
|
||||
const routes: RouteRecordRaw[] = [
|
||||
{
|
||||
path: '/login',
|
||||
name: 'login',
|
||||
component: () => import('@/views/LoginView.vue'),
|
||||
meta: { title: '登录', noAuth: true }
|
||||
},
|
||||
{
|
||||
path: '/',
|
||||
redirect: '/tasks'
|
||||
@@ -68,11 +74,20 @@ const router = createRouter({
|
||||
}
|
||||
})
|
||||
|
||||
router.beforeEach((to) => {
|
||||
const TOKEN_KEY = 'elysia_auth_token'
|
||||
|
||||
router.beforeEach((to, from) => {
|
||||
const page = (to.meta.title as string) || ''
|
||||
const userStore = useUserSettingsStore()
|
||||
const siteName = userStore.siteName || '爱莉希雅待办'
|
||||
document.title = page ? `${page} - ${siteName}` : siteName
|
||||
|
||||
if (to.meta.noAuth) return
|
||||
|
||||
const token = localStorage.getItem(TOKEN_KEY)
|
||||
if (!token) {
|
||||
return { path: '/login', query: { redirect: to.fullPath } }
|
||||
}
|
||||
})
|
||||
|
||||
export default router
|
||||
|
||||
49
WebUI/src/stores/useAuthStore.ts
Normal file
49
WebUI/src/stores/useAuthStore.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import { login as apiLogin } from '@/api/auth'
|
||||
|
||||
const TOKEN_KEY = 'elysia_auth_token'
|
||||
|
||||
function getStoredToken(): string {
|
||||
return localStorage.getItem(TOKEN_KEY) || ''
|
||||
}
|
||||
|
||||
function setStoredToken(token: string) {
|
||||
localStorage.setItem(TOKEN_KEY, token)
|
||||
}
|
||||
|
||||
function clearStoredToken() {
|
||||
localStorage.removeItem(TOKEN_KEY)
|
||||
}
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
const token = ref<string>(getStoredToken())
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
|
||||
const isLoggedIn = computed(() => !!token.value)
|
||||
|
||||
async function login(password: string): Promise<boolean> {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const res = await apiLogin(password)
|
||||
token.value = res.access_token
|
||||
setStoredToken(res.access_token)
|
||||
return true
|
||||
} catch (e: any) {
|
||||
error.value = e?.response?.data?.detail || '登录失败'
|
||||
return false
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function logout() {
|
||||
token.value = ''
|
||||
error.value = ''
|
||||
clearStoredToken()
|
||||
}
|
||||
|
||||
return { token, loading, error, isLoggedIn, login, logout }
|
||||
})
|
||||
157
WebUI/src/views/LoginView.vue
Normal file
157
WebUI/src/views/LoginView.vue
Normal file
@@ -0,0 +1,157 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, shallowRef } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import { Lock } from '@element-plus/icons-vue'
|
||||
import { useAuthStore } from '@/stores/useAuthStore'
|
||||
import { useUserSettingsStore } from '@/stores/useUserSettingsStore'
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
const authStore = useAuthStore()
|
||||
const userSettingsStore = useUserSettingsStore()
|
||||
|
||||
const password = ref('')
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
|
||||
const redirect = (route.query.redirect as string) || '/'
|
||||
|
||||
async function handleLogin() {
|
||||
if (!password.value) return
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const ok = await authStore.login(password.value)
|
||||
if (ok) {
|
||||
await userSettingsStore.fetchAndSync()
|
||||
router.replace(redirect)
|
||||
} else {
|
||||
error.value = authStore.error || '密码错误'
|
||||
}
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="login-wrapper">
|
||||
<div class="decoration-star" style="top: 10%; right: 15%; animation-delay: 0s;"></div>
|
||||
<div class="decoration-star" style="top: 70%; left: 10%; animation-delay: 1s;"></div>
|
||||
<div class="decoration-star" style="top: 30%; left: 20%; animation-delay: 2s;"></div>
|
||||
|
||||
<div class="login-card">
|
||||
<div class="login-header">
|
||||
<div class="logo-icon">✿</div>
|
||||
<h1 class="site-name">{{ userSettingsStore.siteName }}</h1>
|
||||
<p class="subtitle">需要密码才能进入哦~</p>
|
||||
</div>
|
||||
|
||||
<el-form @submit.prevent="handleLogin" class="login-form">
|
||||
<el-input
|
||||
v-model="password"
|
||||
type="password"
|
||||
placeholder="请输入密码"
|
||||
size="large"
|
||||
show-password
|
||||
:prefix-icon="Lock"
|
||||
@keyup.enter="handleLogin"
|
||||
/>
|
||||
<p v-if="error" class="error-msg">{{ error }}</p>
|
||||
<el-button
|
||||
type="primary"
|
||||
size="large"
|
||||
:loading="loading"
|
||||
class="login-btn"
|
||||
@click="handleLogin"
|
||||
>
|
||||
进入
|
||||
</el-button>
|
||||
</el-form>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.login-wrapper {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: linear-gradient(135deg, #fce4ec 0%, #f8bbd0 30%, #f48fb1 60%, #fce4ec 100%);
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.login-card {
|
||||
background: rgba(255, 255, 255, 0.85);
|
||||
backdrop-filter: blur(16px);
|
||||
border-radius: 24px;
|
||||
padding: 48px 40px;
|
||||
width: 400px;
|
||||
max-width: 90vw;
|
||||
box-shadow: 0 8px 32px rgba(255, 183, 197, 0.3);
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.login-header {
|
||||
text-align: center;
|
||||
margin-bottom: 32px;
|
||||
|
||||
.logo-icon {
|
||||
font-size: 48px;
|
||||
color: var(--primary);
|
||||
animation: twinkle 2s ease-in-out infinite;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.site-name {
|
||||
font-size: 24px;
|
||||
font-weight: 700;
|
||||
background: linear-gradient(135deg, var(--primary) 0%, var(--accent) 100%);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
font-size: 14px;
|
||||
color: var(--text-secondary);
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.login-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.error-msg {
|
||||
color: #f56c6c;
|
||||
font-size: 13px;
|
||||
margin: 0;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.login-btn {
|
||||
width: 100%;
|
||||
height: 44px;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
background: linear-gradient(135deg, var(--primary) 0%, var(--accent) 100%);
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
|
||||
&:hover {
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 4px 16px rgba(255, 183, 197, 0.5);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes twinkle {
|
||||
0%, 100% { opacity: 1; transform: scale(1); }
|
||||
50% { opacity: 0.7; transform: scale(1.05); }
|
||||
}
|
||||
</style>
|
||||
@@ -27,3 +27,7 @@ DEFAULT_PAGE_SIZE = 20
|
||||
# 服务配置
|
||||
HOST = "0.0.0.0"
|
||||
PORT = 23994
|
||||
|
||||
# JWT 认证配置
|
||||
JWT_SECRET = "elysia-todo-secret-key-change-in-production"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES = 1440 # 24小时
|
||||
|
||||
@@ -10,6 +10,7 @@ from app.config import CORS_ORIGINS, WEBUI_PATH, HOST, PORT
|
||||
from app.database import init_db
|
||||
from app.routers import api_router
|
||||
from app.utils.logger import logger
|
||||
from app.utils.auth import decode_access_token
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
@@ -89,6 +90,28 @@ async def log_requests(request: Request, call_next):
|
||||
return response
|
||||
|
||||
|
||||
# 认证中间件(保护所有 /api/* 路由,除了 /api/auth/* 和 /health)
|
||||
@app.middleware("http")
|
||||
async def auth_middleware(request: Request, call_next):
|
||||
path = request.url.path
|
||||
|
||||
# 不拦截:健康检查、静态文件、auth 路由
|
||||
if path == "/health" or not path.startswith("/api/") or path.startswith("/api/auth/"):
|
||||
return await call_next(request)
|
||||
|
||||
auth_header = request.headers.get("Authorization", "")
|
||||
token = auth_header.replace("Bearer ", "")
|
||||
if not token:
|
||||
return JSONResponse(status_code=401, content={"detail": "未登录"})
|
||||
|
||||
try:
|
||||
decode_access_token(token)
|
||||
except Exception:
|
||||
return JSONResponse(status_code=401, content={"detail": "登录已过期,请重新登录"})
|
||||
|
||||
return await call_next(request)
|
||||
|
||||
|
||||
# 全局异常处理器
|
||||
@app.exception_handler(Exception)
|
||||
async def global_exception_handler(request: Request, exc: Exception):
|
||||
|
||||
@@ -31,6 +31,9 @@ class UserSettings(Base):
|
||||
default_sort_by = Column(String(20), default="created_at")
|
||||
default_sort_order = Column(String(10), default="desc")
|
||||
|
||||
# 认证
|
||||
password_hash = Column(String(255), default="")
|
||||
|
||||
# 时间戳
|
||||
created_at = Column(DateTime, default=utcnow)
|
||||
updated_at = Column(DateTime, default=utcnow, onupdate=utcnow)
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
from fastapi import APIRouter
|
||||
from app.routers import tasks, categories, tags, user_settings, habits, anniversaries, accounts
|
||||
from app.routers import tasks, categories, tags, user_settings, habits, anniversaries, accounts, auth
|
||||
|
||||
# 创建主路由
|
||||
api_router = APIRouter()
|
||||
|
||||
# 注册子路由
|
||||
api_router.include_router(auth.router)
|
||||
api_router.include_router(tasks.router)
|
||||
api_router.include_router(categories.router)
|
||||
api_router.include_router(tags.router)
|
||||
|
||||
51
api/app/routers/auth.py
Normal file
51
api/app/routers/auth.py
Normal file
@@ -0,0 +1,51 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.database import get_db
|
||||
from app.models.user_settings import UserSettings
|
||||
from app.schemas.auth import LoginRequest, TokenResponse, ChangePasswordRequest
|
||||
from app.utils.auth import (
|
||||
hash_password, verify_password, create_access_token,
|
||||
get_current_user, set_default_password
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/auth", tags=["认证"])
|
||||
|
||||
|
||||
@router.post("/login", response_model=TokenResponse)
|
||||
def login(data: LoginRequest, db: Session = Depends(get_db)):
|
||||
settings = db.query(UserSettings).filter(UserSettings.id == 1).first()
|
||||
if not settings:
|
||||
settings = UserSettings(id=1)
|
||||
db.add(settings)
|
||||
db.commit()
|
||||
db.refresh(settings)
|
||||
|
||||
set_default_password(db, settings)
|
||||
|
||||
if not verify_password(data.password, settings.password_hash):
|
||||
raise HTTPException(status_code=401, detail="密码错误")
|
||||
|
||||
token = create_access_token({"sub": str(settings.id)})
|
||||
return TokenResponse(access_token=token)
|
||||
|
||||
|
||||
@router.post("/change-password")
|
||||
def change_password(
|
||||
data: ChangePasswordRequest,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
get_current_user(request)
|
||||
|
||||
settings = db.query(UserSettings).filter(UserSettings.id == 1).first()
|
||||
if not settings:
|
||||
raise HTTPException(status_code=500, detail="用户设置不存在")
|
||||
|
||||
if not verify_password(data.old_password, settings.password_hash):
|
||||
raise HTTPException(status_code=400, detail="原密码错误")
|
||||
|
||||
settings.password_hash = hash_password(data.new_password)
|
||||
db.commit()
|
||||
|
||||
return {"message": "密码修改成功"}
|
||||
15
api/app/schemas/auth.py
Normal file
15
api/app/schemas/auth.py
Normal file
@@ -0,0 +1,15 @@
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
password: str = Field(..., min_length=1, max_length=100)
|
||||
|
||||
|
||||
class TokenResponse(BaseModel):
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
|
||||
|
||||
class ChangePasswordRequest(BaseModel):
|
||||
old_password: str = Field(..., min_length=1, max_length=100)
|
||||
new_password: str = Field(..., min_length=1, max_length=100)
|
||||
51
api/app/utils/auth.py
Normal file
51
api/app/utils/auth.py
Normal file
@@ -0,0 +1,51 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
from jose import JWTError, jwt
|
||||
from passlib.context import CryptContext
|
||||
from fastapi import Request, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.config import JWT_SECRET, ACCESS_TOKEN_EXPIRE_MINUTES
|
||||
from app.database import get_db
|
||||
from app.models.user_settings import UserSettings
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
ALGORITHM = "HS256"
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return pwd_context.hash(password)
|
||||
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
return pwd_context.verify(plain_password, hashed_password)
|
||||
|
||||
|
||||
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
|
||||
to_encode = data.copy()
|
||||
expire = datetime.now(timezone.utc) + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
|
||||
to_encode.update({"exp": expire})
|
||||
return jwt.encode(to_encode, JWT_SECRET, algorithm=ALGORITHM)
|
||||
|
||||
|
||||
def decode_access_token(token: str) -> dict:
|
||||
return jwt.decode(token, JWT_SECRET, algorithms=[ALGORITHM])
|
||||
|
||||
|
||||
def get_current_user(request: Request) -> dict:
|
||||
auth_header = request.headers.get("Authorization", "")
|
||||
token = auth_header.replace("Bearer ", "")
|
||||
if not token:
|
||||
raise HTTPException(status_code=401, detail="未登录")
|
||||
try:
|
||||
payload = decode_access_token(token)
|
||||
return payload
|
||||
except JWTError:
|
||||
raise HTTPException(status_code=401, detail="登录已过期,请重新登录")
|
||||
|
||||
|
||||
def set_default_password(db: Session, settings: UserSettings):
|
||||
if not settings.password_hash:
|
||||
settings.password_hash = hash_password("elysia")
|
||||
db.commit()
|
||||
@@ -1,16 +1,16 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>webui</title>
|
||||
<script type="module" crossorigin src="/assets/index-DP1ITMxF.js"></script>
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>webui</title>
|
||||
<script type="module" crossorigin src="/assets/index-BDYzX3N-.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/assets/vendor-CwFI-VDq.js">
|
||||
<link rel="modulepreload" crossorigin href="/assets/element-plus-CAICPA8-.js">
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-DE0sVD5v.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
<link rel="modulepreload" crossorigin href="/assets/element-plus-DsX44Q4d.js">
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-DOz3B-pr.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
||||
</body>
|
||||
|
||||
@@ -4,3 +4,6 @@ sqlalchemy==2.0.25
|
||||
pydantic==2.5.3
|
||||
pydantic-settings==2.1.0
|
||||
python-multipart==0.0.6
|
||||
python-jose[cryptography]==3.3.0
|
||||
passlib[bcrypt]==1.7.4
|
||||
bcrypt==4.2.1
|
||||
|
||||
Reference in New Issue
Block a user