From 635930db507b3027a4594f98151aab6fd3ee172d Mon Sep 17 00:00:00 2001 From: bboysoul Date: Mon, 7 Sep 2026 17:35:09 +0800 Subject: [PATCH] feat: add password change settings --- backend/main.py | 19 ++++++++++++++++ backend/schemas.py | 11 ++++++++++ frontend/src/MvpPanel.vue | 33 ++++++++++++++++++++++++++++ frontend/src/style.css | 2 +- frontend/src/style.test.ts | 10 +++++++++ tests/test_app.py | 44 ++++++++++++++++++++++++++++++++++++++ 6 files changed, 118 insertions(+), 1 deletion(-) diff --git a/backend/main.py b/backend/main.py index e29704d..236008a 100644 --- a/backend/main.py +++ b/backend/main.py @@ -32,6 +32,7 @@ from .mvp import router as mvp_router from .schemas import ( BatchResult, BatchTaskUpdate, + ChangePasswordRequest, FolderCreate, FolderOut, InitializeRequest, @@ -172,6 +173,24 @@ async def me(user: User = Depends(current_user)): return user +@app.post("/api/v1/auth/change-password", status_code=204) +async def change_password( + payload: ChangePasswordRequest, + token: str = Depends(session_token), + user: User = Depends(current_user), + db: AsyncSession = Depends(get_db), +): + if not verify_password(user.password_hash, payload.current_password): + raise HTTPException(status_code=400, detail="当前密码不正确") + user.password_hash = hash_password(payload.new_password) + current_hash = hash_token(token) + await db.execute( + delete(Session).where(Session.user_id == user.id, Session.token_hash != current_hash) + ) + await db.commit() + return Response(status_code=204) + + @app.get("/api/v1/bootstrap") async def bootstrap_data(user: User = Depends(current_user), db: AsyncSession = Depends(get_db)): folders = list((await db.scalars( diff --git a/backend/schemas.py b/backend/schemas.py index 75b40a3..a749f09 100644 --- a/backend/schemas.py +++ b/backend/schemas.py @@ -14,6 +14,17 @@ class LoginRequest(BaseModel): password: str +class ChangePasswordRequest(BaseModel): + current_password: str = Field(min_length=1, max_length=256) + new_password: str = Field(min_length=12, max_length=256) + + @model_validator(mode="after") + def reject_same_password(self): + if self.current_password == self.new_password: + raise ValueError("新密码不能与当前密码相同") + return self + + class UserOut(BaseModel): model_config = ConfigDict(from_attributes=True) id: UUID diff --git a/frontend/src/MvpPanel.vue b/frontend/src/MvpPanel.vue index 7479359..a70234a 100644 --- a/frontend/src/MvpPanel.vue +++ b/frontend/src/MvpPanel.vue @@ -24,6 +24,11 @@ const habitNameInput = ref(null) const importFile = ref(null) const importPreview = ref(null) const restoreFile = ref(null) +const currentPassword = ref('') +const newPassword = ref('') +const confirmPassword = ref('') +const passwordBusy = ref(false) +const passwordError = ref('') const todayKey = ref(dateKey(new Date())) const habitSwipeStart = ref<{ id: string; x: number; y: number } | null>(null) const habitPointerStart = ref<{ id: string; x: number; y: number } | null>(null) @@ -286,6 +291,33 @@ async function restore() { emit('changed'); emit('notice', '数据已恢复') }) } +async function changePassword() { + passwordError.value = '' + if (newPassword.value !== confirmPassword.value) { + passwordError.value = '两次输入的新密码不一致' + return + } + if (newPassword.value.length < 12) { + passwordError.value = '新密码至少需要 12 位' + return + } + passwordBusy.value = true + try { + await request('/auth/change-password', { + method: 'POST', + body: JSON.stringify({ current_password: currentPassword.value, new_password: newPassword.value }), + }) + currentPassword.value = '' + newPassword.value = '' + confirmPassword.value = '' + emit('notice', '密码已修改,其他设备已退出登录') + await loadSettings() + } catch (e) { + passwordError.value = e instanceof Error ? e.message : '修改密码失败' + } finally { + passwordBusy.value = false + } +} onMounted(() => { if (props.view === 'habits' || props.view === 'today-habits') { refreshHabitDay() @@ -357,6 +389,7 @@ onBeforeUnmount(() => {

数据导出与恢复

下载完整 JSON 备份,或从备份恢复。

导入

先预览变化,确认后才写入。

{{ JSON.stringify(importPreview, null, 2) }}
+

修改密码

修改后当前设备保持登录,其他设备会自动退出。

登录会话

{{ s.current ? '当前设备' : '其他设备' }}{{ s.user_agent || '未知设备' }} · {{ s.last_seen_at || s.created_at }}

没有可显示的会话。

最近活动

{{ row.action || row.event || '变更' }}{{ row.created_at || row.timestamp }}
diff --git a/frontend/src/style.css b/frontend/src/style.css index 6d6dde8..457a3c9 100644 --- a/frontend/src/style.css +++ b/frontend/src/style.css @@ -25,7 +25,7 @@ main{min-width:0;padding:27px 34px 50px;overflow:auto;background:linear-gradient .numeric-action{display:flex;gap:6px;align-items:center}.numeric-action input{width:74px;border:1px solid var(--line);border-radius:8px;padding:7px;background:#fff}.numeric-action .soft-button{min-height:44px;padding:9px 12px} .habit-row>.icon.ghost{width:44px;height:44px;flex:0 0 44px}.habit-check{margin-left:-4px}.habit-row.done .habit-check .task-check-mark{background:#71856b;border-color:#71856b;color:#fff}.habit-toolbar{display:flex;align-items:center;gap:12px;justify-content:flex-end;color:var(--muted);font-size:12px}.habit-toolbar label{display:inline-flex;align-items:center;gap:6px}.habit-toolbar input{margin:0}.habit-toolbar-today{justify-content:flex-start;margin:0 0 2px 2px} .empty-panel{text-align:center;color:var(--muted);display:grid;place-items:center;gap:10px}.today-empty-panel{min-height:130px}.empty-action{margin-top:4px;color:#655d52}.empty-action svg{width:15px;height:15px} -.settings-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.tool-card{display:flex;flex-direction:column;align-items:flex-start;gap:10px}.tool-card>svg{color:var(--accent);width:25px;height:25px}.tool-card p{margin:0;color:var(--muted);font-size:13px}.tool-card.wide{grid-column:1/-1}.file-button input{display:none}.tool-card pre{width:100%;max-height:180px;overflow:auto;background:#f8f3e8;padding:10px;border-radius:8px;font-size:10px}.session-row,.audit-row{width:100%;display:flex;justify-content:space-between;align-items:center;border-top:1px solid var(--line);padding:9px 0}.session-row span{display:grid}.session-row small,.audit-row small{color:var(--muted);font-size:11px}.inline-error{padding:9px;border-radius:8px;color:var(--danger);background:#fff0ed}.settings.active{background:var(--accent-soft);color:#b7421e;font-weight:700} +.settings-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.tool-card{display:flex;flex-direction:column;align-items:flex-start;gap:10px}.tool-card>svg{color:var(--accent);width:25px;height:25px}.tool-card p{margin:0;color:var(--muted);font-size:13px}.tool-card.wide{grid-column:1/-1}.password-form{width:100%;display:grid;gap:10px}.password-form label{display:grid;gap:6px;color:#675f54;font-size:12px;font-weight:650}.password-form input{width:100%;border:1px solid var(--line);background:#fff;border-radius:10px;padding:11px 12px;outline:none}.password-form input:focus{border-color:var(--accent);box-shadow:0 0 0 3px rgba(241,90,41,.1)}.password-form button{justify-self:start}.file-button input{display:none}.tool-card pre{width:100%;max-height:180px;overflow:auto;background:#f8f3e8;padding:10px;border-radius:8px;font-size:10px}.session-row,.audit-row{width:100%;display:flex;justify-content:space-between;align-items:center;border-top:1px solid var(--line);padding:9px 0}.session-row span{display:grid}.session-row small,.audit-row small{color:var(--muted);font-size:11px}.inline-error{padding:9px;border-radius:8px;color:var(--danger);background:#fff0ed}.settings.active{background:var(--accent-soft);color:#b7421e;font-weight:700} @media(max-width:800px){.settings-grid{grid-template-columns:1fr}.tool-card.wide{grid-column:auto}.habit-row{padding:5px 4px 5px 8px}.habit-main{padding:10px 2px}.numeric-action input{width:62px}} .unified-fab{display:grid;place-items:center;position:fixed;z-index:60;right:20px;bottom:22px;width:56px;height:56px;border:0;border-radius:50%;background:var(--accent);color:#fff;box-shadow:0 8px 20px rgba(241,90,41,.28);transition:transform .16s ease,box-shadow .16s ease;touch-action:none;user-select:none}.unified-fab svg{width:25px;height:25px}.unified-fab:hover{transform:translateY(-2px);box-shadow:0 10px 24px rgba(241,90,41,.32)}.unified-fab:active{transform:scale(.96)}.unified-fab.dragging{transform:scale(1.06);box-shadow:0 12px 28px rgba(241,90,41,.36)}.task-compose-mask{position:fixed;z-index:70;inset:0;background:rgba(45,38,31,.34);display:flex;align-items:flex-end;padding:0}.task-compose-sheet{width:100%;max-height:min(88dvh,720px);overflow:auto;background:#fffdf8;border-radius:24px 24px 0 0;padding:18px 18px calc(20px + env(safe-area-inset-bottom));box-shadow:0 -16px 42px rgba(56,40,24,.2);display:grid;gap:14px;transform-origin:var(--fab-origin-x,calc(100% - 44px)) var(--fab-origin-y,100%)}.task-compose-sheet header{display:flex;align-items:center;justify-content:space-between}.task-compose-sheet header small{color:var(--accent);font-size:10px;font-weight:800;letter-spacing:.12em}.task-compose-sheet h2{margin:2px 0 0;font-size:22px}.task-compose-sheet label{display:grid;gap:6px;color:#675f54;font-size:12px;font-weight:650}.task-compose-sheet input,.task-compose-sheet select,.task-compose-sheet textarea{width:100%;border:1px solid var(--line);background:#fff;border-radius:11px;padding:12px;outline:none;resize:vertical}.task-compose-sheet input:focus,.task-compose-sheet select:focus,.task-compose-sheet textarea:focus{border-color:var(--accent);box-shadow:0 0 0 3px rgba(241,90,41,.1)}.task-compose-row{display:grid;grid-template-columns:minmax(0,1fr) 105px;gap:10px}.task-compose-sheet footer{display:flex;justify-content:flex-end;gap:9px;padding-top:4px}.task-compose-sheet button:disabled{opacity:.45}.task-compose-enter-active,.task-compose-leave-active{transition:background .22s ease}.task-compose-enter-active .task-compose-sheet,.task-compose-leave-active .task-compose-sheet{transition:transform .28s cubic-bezier(.2,.9,.25,1.08),opacity .2s ease}.task-compose-enter-from,.task-compose-leave-to{background:rgba(45,38,31,0)}.task-compose-enter-from .task-compose-sheet,.task-compose-leave-to .task-compose-sheet{transform:translateY(36px) scale(.86);opacity:0} .countdown-compose-enter-active,.countdown-compose-leave-active{transition:background .24s ease}.countdown-compose-enter-active .countdown-modal,.countdown-compose-leave-active .countdown-modal{transition:transform .34s cubic-bezier(.18,.9,.28,1.16),opacity .22s ease,filter .22s ease;transform-origin:var(--fab-origin-x,calc(100% - 43px)) var(--fab-origin-y,calc(100% - 104px))}.countdown-compose-enter-from,.countdown-compose-leave-to{background:rgba(45,38,31,0)}.countdown-compose-enter-from .countdown-modal,.countdown-compose-leave-to .countdown-modal{transform:translate(20px,28px) scale(.18) rotate(8deg);opacity:0;filter:blur(5px)}@media(max-width:930px){.unified-fab{bottom:calc(82px + env(safe-area-inset-bottom))}}@media(prefers-reduced-motion:reduce){*,*:before,*:after{scroll-behavior:auto!important;animation-duration:.01ms!important;transition-duration:.01ms!important}} diff --git a/frontend/src/style.test.ts b/frontend/src/style.test.ts index 71df882..1bd220a 100644 --- a/frontend/src/style.test.ts +++ b/frontend/src/style.test.ts @@ -117,6 +117,16 @@ describe('task and habit row decoration', () => { expect(mvpPanel).not.toContain("view === 'today-habits' && busy\" class=\"empty-panel\">加载中…") }) + it('shows a password form with confirmation and calls the protected endpoint', () => { + expect(mvpPanel).toContain('class="password-form"') + expect(mvpPanel).toContain('aria-label="当前密码"') + expect(mvpPanel).toContain('aria-label="新密码"') + expect(mvpPanel).toContain('aria-label="确认新密码"') + expect(mvpPanel).toContain("request('/auth/change-password'") + expect(mvpPanel).toContain('两次输入的新密码不一致') + expect(css).toContain('.password-form{width:100%;display:grid;gap:10px}') + }) + it('keeps habit cards borderless so the rounded left edge has no visual gap', () => { expect(css).toMatch(/\.habit-row\{border:0;/) expect(css).not.toMatch(/\.habit-row\{[^}]*border-top:/) diff --git a/tests/test_app.py b/tests/test_app.py index bb29585..e3cc399 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -130,6 +130,50 @@ def test_logout_revokes_current_session(client): assert client.get("/api/v1/me").status_code == 401 +def test_change_password_checks_current_password_and_revokes_other_sessions(client): + old_password = "correct horse battery staple" + new_password = "new correct horse battery staple" + client.post("/api/v1/setup/initialize", json={"username": "owner", "password": old_password}) + other = type(client)(client.app) + try: + assert other.post("/api/v1/auth/login", json={"username": "owner", "password": old_password}).status_code == 200 + wrong = client.post( + "/api/v1/auth/change-password", + json={"current_password": "wrong password", "new_password": new_password}, + ) + assert wrong.status_code == 400 + assert wrong.json()["detail"] == "当前密码不正确" + + changed = client.post( + "/api/v1/auth/change-password", + json={"current_password": old_password, "new_password": new_password}, + ) + assert changed.status_code == 204 + assert client.get("/api/v1/me").status_code == 200 + assert other.get("/api/v1/me").status_code == 401 + assert other.post("/api/v1/auth/login", json={"username": "owner", "password": old_password}).status_code == 401 + assert other.post("/api/v1/auth/login", json={"username": "owner", "password": new_password}).status_code == 200 + finally: + other.close() + + +def test_change_password_validates_new_password(client): + client.post( + "/api/v1/setup/initialize", + json={"username": "owner", "password": "correct horse battery staple"}, + ) + too_short = client.post( + "/api/v1/auth/change-password", + json={"current_password": "correct horse battery staple", "new_password": "short"}, + ) + assert too_short.status_code == 422 + same = client.post( + "/api/v1/auth/change-password", + json={"current_password": "correct horse battery staple", "new_password": "correct horse battery staple"}, + ) + assert same.status_code == 422 + + def initialized_client(client): client.post( "/api/v1/setup/initialize",