From e0962949557d3f790e2f8fbe004a2b59b5d86577 Mon Sep 17 00:00:00 2001 From: soehi <811446351@qq.com> Date: Fri, 6 Nov 2026 15:23:05 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E9=82=AE=E7=AE=B1=E6=8D=A2?= =?UTF-8?q?=E7=BB=91=E5=8A=9F=E8=83=BD=EF=BC=8C=E9=AA=8C=E8=AF=81=E6=96=B0?= =?UTF-8?q?=E6=97=A7=E9=82=AE=E7=AE=B1=E5=B9=B6=E6=B3=A8=E9=94=80=E5=85=B6?= =?UTF-8?q?=E4=BB=96=E8=AE=BE=E5=A4=87=E4=BC=9A=E8=AF=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + dist/assets/styles.css | 4 ++ dist/index.html | 20 +++++++- dist/js/app.js | 50 +++++++++++++++++++ server/main.py | 99 ++++++++++++++++++++++++++++++++++++-- tests/test_change_email.py | 83 ++++++++++++++++++++++++++++++++ 6 files changed, 252 insertions(+), 5 deletions(-) create mode 100644 tests/test_change_email.py diff --git a/README.md b/README.md index 9be01e7..81e4fe8 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ ## 功能 +- **邮箱换绑**:在账号设置中验证原邮箱和新邮箱后更换绑定地址;新邮箱须未被其他账号占用。账号及活动记录保留,当前会话保留、其他设备退出,原邮箱未使用验证码失效;后续使用新邮箱登录并接收提醒。 - **值班提醒**:读取单双周值班 JSON,按 2026-11-06 单周周五为基准循环,北京时间前一天 18:00 汇总提醒,并在每个值班时段开始前一小时再次发送邮件;邮箱匹配、预览和部署说明见 [duty/README.md](duty/README.md)。 - **账号体系**:注册时设置密码,通过邮箱+密码登录;也可选邮箱验证码登录,忘记密码后可凭邮箱验证码重设。注册需填写姓名、所属部门、邮箱和手机号,Bearer 会话默认 30 天有效,可改个人资料 - **活动记录**:标题 / 分类(8 类)/ 时间 / 地点 / 描述 / 名额 / 公开或私密;发起人自动写入一条参加记录 diff --git a/dist/assets/styles.css b/dist/assets/styles.css index 1fc6ae4..0997fe0 100644 --- a/dist/assets/styles.css +++ b/dist/assets/styles.css @@ -572,3 +572,7 @@ button:focus-visible, a:focus-visible, [tabindex]:focus-visible { outline: 3px s .duty-reminder-row > div { min-width: 0; overflow-wrap: anywhere; } .duty-reminder-row .muted { display: block; margin-top: 5px; } .duty-reminder-row .btn { flex: none; min-height: 40px; } +#change-email-panel summary { cursor: pointer; font-weight: 600; padding-block: 6px; } +#change-email-panel summary:focus-visible { outline: 3px solid #28664f80; outline-offset: 4px; } +#change-email-form .form-hint { margin: 8px 0 0; overflow-wrap: anywhere; } +#change-email-result:empty { display: none; } diff --git a/dist/index.html b/dist/index.html index 30fa158..5b45e75 100644 --- a/dist/index.html +++ b/dist/index.html @@ -5,7 +5,7 @@ WorkLog · 活动记录 - +
@@ -223,6 +223,22 @@
+
+
+ 更换绑定邮箱 +

验证原邮箱和新邮箱后换绑。换绑后请使用新邮箱登录,其他设备将退出登录。

+
+ +

+ + +

+ + +
+
+

+

测试邮件连通性

向当前账号绑定的邮箱发送测试邮件,同一邮箱每 2 分钟可测试一次。

@@ -253,7 +269,7 @@ - +
diff --git a/dist/js/app.js b/dist/js/app.js index e83660a..5249577 100644 --- a/dist/js/app.js +++ b/dist/js/app.js @@ -937,6 +937,56 @@ } // ------------------------------------------------------------- 设置 + const emailChangeCooldowns = new Map(); + const emailChangePending = new Set(); + for (const kind of ["old", "new"]) { + const button = $(`#change-email-${kind}-code`); + const hint = $(`#change-email-${kind}-hint`); + button.addEventListener("click", async () => { + const form = $("#change-email-form"); + if (kind === "new" && !form.email.reportValidity()) return; + button.disabled = true; + emailChangePending.add(kind); + $("#change-email-error").textContent = ""; + const email = kind === "old" ? state.me.email : form.email.value.trim(); + try { + const data = await api(`/auth/email/${kind}-code`, { method: "POST", ...(kind === "new" ? { body: { email } } : {}) }); + hint.textContent = data.dev_code ? `本机测试验证码:${data.dev_code}` : `验证码已发送至 ${email}`; + emailChangeCooldowns.set(`${state.me.id}:${kind}`, Date.now() + 60000); + } catch (error) { $("#change-email-error").textContent = error.message; } + finally { emailChangePending.delete(kind); updateEmailChangeButtons(); } + }); + } + function updateEmailChangeButtons() { + for (const kind of ["old", "new"]) { + const left = Math.max(0, Math.ceil(((emailChangeCooldowns.get(`${state.me?.id}:${kind}`) || 0) - Date.now()) / 1000)); + const button = $(`#change-email-${kind}-code`); + button.disabled = left > 0 || emailChangePending.has(kind); + button.textContent = left ? `${left} 秒后重发` : "获取验证码"; + } + } + setInterval(updateEmailChangeButtons, 1000); + $("#change-email-form").addEventListener("submit", async (event) => { + event.preventDefault(); + const form = event.target; + const button = form.querySelector('[type="submit"]'); + button.disabled = true; + $("#change-email-error").textContent = ""; + try { + const data = await api("/auth/email/change", { method: "POST", body: { email: form.email.value.trim(), old_code: form.old_code.value, new_code: form.new_code.value } }); + state.me = data.user; + form.reset(); + $("#change-email-old-hint").textContent = ""; + $("#change-email-new-hint").textContent = ""; + $("#change-email-panel").open = false; + $("#pf-test-email-status").textContent = ""; + fillProfile(); + $("#change-email-result").textContent = "邮箱已换绑,今后请使用新邮箱登录,提醒邮件也会发送到新邮箱。"; + toast("邮箱已换绑"); + } catch (error) { $("#change-email-error").textContent = error.message; } + finally { button.disabled = false; } + }); + function fillProfile() { $("#pf-name").value = state.me.display_name; $("#pf-dept").value = state.me.department || ""; diff --git a/server/main.py b/server/main.py index 8a6515e..76a3760 100644 --- a/server/main.py +++ b/server/main.py @@ -450,6 +450,25 @@ class ProfileIn(BaseModel): return value +class NewEmailIn(BaseModel): + email: str = Field(max_length=255) + + @field_validator("email") + @classmethod + def validate_email(cls, value: str) -> str: + return SendCodeIn.check_email(value) + + +class ChangeEmailIn(NewEmailIn): + old_code: str + new_code: str + + @field_validator("old_code", "new_code", mode="before") + @classmethod + def validate_codes(cls, value): + return EmailCodeIn.check_code(value) + + class ActivityIn(BaseModel): title: str = Field(min_length=1, max_length=120) start_at: int = Field(gt=0) @@ -878,6 +897,11 @@ def _client_ip(request: Request) -> str: @app.post("/api/auth/send-code") async def send_code(payload: SendCodeIn, request: Request, db: AsyncSession = Depends(get_db)) -> dict: + return await _issue_code(payload, request, db) + + +async def _issue_code(payload: SendCodeIn, request: Request, db: AsyncSession, scoped_purpose: str | None = None) -> dict: + purpose = scoped_purpose or payload.purpose if DEV_MODE: try: local = ip_address(_client_ip(request)).is_loopback @@ -903,12 +927,12 @@ async def send_code(payload: SendCodeIn, request: Request, db: AsyncSession = De code_hash = await asyncio.to_thread(hash_password, code) stamp = now_ms() await db.execute(update(email_verifications).where( - email_verifications.c.email == email, email_verifications.c.purpose == payload.purpose, + email_verifications.c.email == email, email_verifications.c.purpose == purpose, email_verifications.c.used == 0, ).values(used=1)) await db.execute( insert(email_verifications).values( - id=new_id(), email=email, code=code_hash, purpose=payload.purpose, + id=new_id(), email=email, code=code_hash, purpose=purpose, expires_at=stamp + EMAIL_CODE_TTL_MIN * 60_000, used=0, created_at=stamp, ) ) @@ -920,7 +944,7 @@ async def send_code(payload: SendCodeIn, request: Request, db: AsyncSession = De try: await _send_email( - email, "WorkLog 验证码", + email, "WorkLog 更换邮箱验证码" if scoped_purpose else "WorkLog 验证码", f"你的验证码是 {code},{EMAIL_CODE_TTL_MIN} 分钟内有效。如果不是你本人的操作,请忽略本邮件。", ) except HTTPException: @@ -967,6 +991,75 @@ async def _consume_email_code(db: AsyncSession, email: str, code: str, purpose: # ---------------------------------------------------------------- 账号 +def _email_change_purpose(user: dict, kind: str) -> str: + return f"ce-{kind}:" + token_digest(user["id"] + ":" + user["email"].lower())[:24] + + +async def _check_new_email(email: str, user: dict, db: AsyncSession): + if email == user["email"].lower(): + raise HTTPException(status_code=409, detail="新邮箱不能与当前邮箱相同") + if await _find_user_by_email(db, email) is not None: + raise HTTPException(status_code=409, detail="该邮箱已被其他账号使用") + + +@app.post("/api/auth/email/old-code") +async def send_old_email_code(request: Request, user: dict = Depends(current_user), db: AsyncSession = Depends(get_db)): + await _auth_limit(db, "change-email:" + user["id"], 10) + return await _issue_code(SendCodeIn(email=user["email"], purpose="bind"), request, db, _email_change_purpose(user, "old")) + + +@app.post("/api/auth/email/new-code") +async def send_new_email_code(payload: NewEmailIn, request: Request, user: dict = Depends(current_user), db: AsyncSession = Depends(get_db)): + await _auth_limit(db, "change-email:" + user["id"], 10) + await _check_new_email(payload.email, user, db) + return await _issue_code(SendCodeIn(email=payload.email, purpose="bind"), request, db, _email_change_purpose(user, "new")) + + +async def _check_change_code(db, email, code, purpose): + email = email.strip().lower() + row = (await db.execute(select(email_verifications).where( + email_verifications.c.email == email, email_verifications.c.purpose == purpose, + email_verifications.c.used == 0, + ).order_by(email_verifications.c.created_at.desc()).limit(1))).mappings().first() + if row is None or row["expires_at"] <= now_ms(): + raise HTTPException(status_code=400, detail="验证码无效或已过期,请重新获取") + attempt = await db.execute(update(email_verifications).where( + email_verifications.c.id == row["id"], email_verifications.c.used == 0, + email_verifications.c.attempts < 5, + ).values(attempts=email_verifications.c.attempts + 1)) + await db.commit() + if attempt.rowcount != 1: + raise HTTPException(status_code=429, detail="验证码尝试次数过多,请重新获取") + if not await asyncio.to_thread(verify_password, code, row["code"]): + raise HTTPException(status_code=400, detail="验证码不正确") + return row["id"] + + +@app.post("/api/auth/email/change") +async def change_email(payload: ChangeEmailIn, request: Request, user: dict = Depends(current_user), db: AsyncSession = Depends(get_db)): + await _auth_limit(db, "verify-ip:" + _client_ip(request), 60) + await _check_new_email(payload.email, user, db) + old_id = await _check_change_code(db, user["email"], payload.old_code, _email_change_purpose(user, "old")) + new_id = await _check_change_code(db, payload.email, payload.new_code, _email_change_purpose(user, "new")) + for code_id in (old_id, new_id): + consumed = await db.execute(update(email_verifications).where( + email_verifications.c.id == code_id, email_verifications.c.used == 0, + email_verifications.c.expires_at > now_ms(), + ).values(used=1)) + if consumed.rowcount != 1: + await db.rollback() + raise HTTPException(status_code=409, detail="验证码已失效,请重新获取") + changed = await db.execute(update(users).where(users.c.id == user["id"], users.c.email == user["email"]).values(email=payload.email)) + if changed.rowcount != 1: + await db.rollback() + raise HTTPException(status_code=409, detail="绑定邮箱已变化,请刷新页面") + current_token = request.headers.get("authorization", "")[7:].strip() + await db.execute(delete(sessions).where(sessions.c.user_id == user["id"], sessions.c.token != token_digest(current_token))) + await db.execute(update(email_verifications).where(func.lower(email_verifications.c.email) == user["email"].lower(), email_verifications.c.used == 0).values(used=1)) + await db.commit() + fresh = (await db.execute(select(users).where(users.c.id == user["id"]))).mappings().one() + return {"user": user_public(fresh, include_contact=True)} + @app.post("/api/auth/register") async def register(payload: RegisterIn, request: Request, db: AsyncSession = Depends(get_db)) -> dict: await _auth_limit(db, "verify-ip:" + _client_ip(request), 60) diff --git a/tests/test_change_email.py b/tests/test_change_email.py new file mode 100644 index 0000000..787f3a5 --- /dev/null +++ b/tests/test_change_email.py @@ -0,0 +1,83 @@ +from sqlalchemy import select, update +from test_api import ApiTestCase, TEST_PASSWORD, auth, get_code, register + + +class ChangeEmailTests(ApiTestCase): + async def codes(self, user, email): + headers = auth(user['token']) + old = await self.client.post('/api/auth/email/old-code', headers=headers) + new = await self.client.post('/api/auth/email/new-code', headers=headers, json={'email': email}) + self.assertEqual(old.status_code, 200, old.text) + self.assertEqual(new.status_code, 200, new.text) + return {'email': email, 'old_code': old.json()['dev_code'], 'new_code': new.json()['dev_code']} + + async def test_change_preserves_identity_and_current_session_but_revokes_other_devices(self): + user = await register(self.client, 'emailowner') + old_email = user['user']['email'] + login = await self.client.post('/api/auth/login', json={'email': old_email, 'password': TEST_PASSWORD}) + other_token = login.json()['token'] + await get_code(self.client, old_email, 'login') + payload = await self.codes(user, ' New.Address@Example.Test ') + response = await self.client.post('/api/auth/email/change', headers=auth(user['token']), json=payload) + self.assertEqual(response.status_code, 200, response.text) + self.assertEqual(response.json()['user']['email'], 'new.address@example.test') + self.assertEqual(response.json()['user']['id'], user['user']['id']) + self.assertEqual((await self.client.get('/api/auth/me', headers=auth(user['token']))).status_code, 200) + self.assertEqual((await self.client.get('/api/auth/me', headers=auth(other_token))).status_code, 401) + self.assertEqual((await self.client.post('/api/auth/login', json={'email': old_email, 'password': TEST_PASSWORD})).status_code, 401) + self.assertEqual((await self.client.post('/api/auth/login', json={'email': 'new.address@example.test', 'password': TEST_PASSWORD})).status_code, 200) + async with self.sessions() as db: + rows = (await db.execute(select(self.m.email_verifications).where(self.m.email_verifications.c.email == old_email, self.m.email_verifications.c.used == 0))).all() + self.assertFalse(rows) + + async def test_unauthenticated_same_email_and_occupied_email_rejected(self): + self.assertEqual((await self.client.post('/api/auth/email/old-code')).status_code, 401) + self.assertEqual((await self.client.post('/api/auth/email/new-code', json={'email': 'x@example.test'})).status_code, 401) + self.assertEqual((await self.client.post('/api/auth/email/change', json={'email': 'x@example.test', 'old_code': '123456', 'new_code': '123456'})).status_code, 401) + owner = await register(self.client, 'sameemail') + other = await register(self.client, 'occupiedemail') + for email in [owner['user']['email'].upper(), other['user']['email'].upper()]: + r = await self.client.post('/api/auth/email/new-code', headers=auth(owner['token']), json={'email': email}) + self.assertEqual(r.status_code, 409) + + async def test_wrong_new_code_does_not_consume_valid_old_code(self): + owner = await register(self.client, 'retryemail') + payload = await self.codes(owner, 'retry-new@example.test') + bad = '000000' if payload['new_code'] != '000000' else '111111' + r = await self.client.post('/api/auth/email/change', headers=auth(owner['token']), json={**payload, 'new_code': bad}) + self.assertEqual(r.status_code, 400) + r = await self.client.post('/api/auth/email/change', headers=auth(owner['token']), json=payload) + self.assertEqual(r.status_code, 200, r.text) + + async def test_change_codes_are_bound_to_account_and_cannot_use_generic_bind_codes(self): + owner = await register(self.client, 'scopeowner') + other = await register(self.client, 'scopeother') + payload = await self.codes(owner, 'shared-target@example.test') + other_payload = await self.codes(other, 'shared-target@example.test') + if payload['new_code'] == other_payload['new_code']: + other_payload['new_code'] = '000000' if payload['new_code'] != '000000' else '111111' + r = await self.client.post('/api/auth/email/change', headers=auth(owner['token']), json={**payload, 'new_code': other_payload['new_code']}) + self.assertEqual(r.status_code, 400) + generic = await get_code(self.client, 'shared-target@example.test', 'bind') + if generic == payload['new_code']: + generic = '000000' if payload['new_code'] != '000000' else '111111' + r = await self.client.post('/api/auth/email/change', headers=auth(owner['token']), json={**payload, 'new_code': generic}) + self.assertEqual(r.status_code, 400) + r = await self.client.post('/api/auth/email/change', headers=auth(owner['token']), json=payload) + self.assertEqual(r.status_code, 200, r.text) + + async def test_expired_code_is_rejected(self): + owner = await register(self.client, 'expiredemail') + payload = await self.codes(owner, 'expired-new@example.test') + async with self.sessions() as db: + await db.execute(update(self.m.email_verifications).where(self.m.email_verifications.c.email == payload['email']).values(expires_at=0)) + await db.commit() + self.assertEqual((await self.client.post('/api/auth/email/change', headers=auth(owner['token']), json=payload)).status_code, 400) + + async def test_code_attempt_limit_is_persistent(self): + owner = await register(self.client, 'attemptemail') + payload = await self.codes(owner, 'attempt-new@example.test') + bad = '000000' if payload['old_code'] != '000000' else '111111' + for _ in range(5): + self.assertEqual((await self.client.post('/api/auth/email/change', headers=auth(owner['token']), json={**payload, 'old_code': bad})).status_code, 400) + self.assertEqual((await self.client.post('/api/auth/email/change', headers=auth(owner['token']), json=payload)).status_code, 429)