新增邮箱换绑功能,验证新旧邮箱并注销其他设备会话

This commit is contained in:
2026-11-06 15:23:05 +08:00
parent 0a7a641430
commit e096294955
6 changed files with 252 additions and 5 deletions
+1
View File
@@ -6,6 +6,7 @@
## 功能 ## 功能
- **邮箱换绑**:在账号设置中验证原邮箱和新邮箱后更换绑定地址;新邮箱须未被其他账号占用。账号及活动记录保留,当前会话保留、其他设备退出,原邮箱未使用验证码失效;后续使用新邮箱登录并接收提醒。
- **值班提醒**:读取单双周值班 JSON,按 2026-11-06 单周周五为基准循环,北京时间前一天 18:00 汇总提醒,并在每个值班时段开始前一小时再次发送邮件;邮箱匹配、预览和部署说明见 [duty/README.md](duty/README.md)。 - **值班提醒**:读取单双周值班 JSON,按 2026-11-06 单周周五为基准循环,北京时间前一天 18:00 汇总提醒,并在每个值班时段开始前一小时再次发送邮件;邮箱匹配、预览和部署说明见 [duty/README.md](duty/README.md)。
- **账号体系**:注册时设置密码,通过邮箱+密码登录;也可选邮箱验证码登录,忘记密码后可凭邮箱验证码重设。注册需填写姓名、所属部门、邮箱和手机号,Bearer 会话默认 30 天有效,可改个人资料 - **账号体系**:注册时设置密码,通过邮箱+密码登录;也可选邮箱验证码登录,忘记密码后可凭邮箱验证码重设。注册需填写姓名、所属部门、邮箱和手机号,Bearer 会话默认 30 天有效,可改个人资料
- **活动记录**:标题 / 分类(8 类)/ 时间 / 地点 / 描述 / 名额 / 公开或私密;发起人自动写入一条参加记录 - **活动记录**:标题 / 分类(8 类)/ 时间 / 地点 / 描述 / 名额 / 公开或私密;发起人自动写入一条参加记录
+4
View File
@@ -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 > div { min-width: 0; overflow-wrap: anywhere; }
.duty-reminder-row .muted { display: block; margin-top: 5px; } .duty-reminder-row .muted { display: block; margin-top: 5px; }
.duty-reminder-row .btn { flex: none; min-height: 40px; } .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; }
+18 -2
View File
@@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WorkLog · 活动记录</title> <title>WorkLog · 活动记录</title>
<meta name="theme-color" content="#f5f7f5" /> <meta name="theme-color" content="#f5f7f5" />
<link rel="stylesheet" href="/assets/styles.css?v=10" /> <link rel="stylesheet" href="/assets/styles.css?v=11" />
</head> </head>
<body> <body>
<div id="app"> <div id="app">
@@ -223,6 +223,22 @@
<label>绑定邮箱<div class="muted" id="pf-email" style="margin-top:4px"></div></label> <label>绑定邮箱<div class="muted" id="pf-email" style="margin-top:4px"></div></label>
<button class="btn primary" id="pf-save">保存资料</button> <button class="btn primary" id="pf-save">保存资料</button>
</div> </div>
<div class="card form-card">
<details id="change-email-panel">
<summary>更换绑定邮箱</summary>
<p class="muted">验证原邮箱和新邮箱后换绑。换绑后请使用新邮箱登录,其他设备将退出登录。</p>
<form id="change-email-form">
<label>原邮箱验证码<div class="code-row"><input name="old_code" required pattern="[0-9]{6}" maxlength="6" inputmode="numeric" autocomplete="off" placeholder="原邮箱收到的 6 位验证码" /><button class="btn" type="button" id="change-email-old-code">获取验证码</button></div></label>
<p class="form-hint muted" id="change-email-old-hint" role="status"></p>
<label>新邮箱<input name="email" type="email" required maxlength="255" autocomplete="email" placeholder="输入新的邮箱地址" /></label>
<label>新邮箱验证码<div class="code-row"><input name="new_code" required pattern="[0-9]{6}" maxlength="6" inputmode="numeric" autocomplete="off" placeholder="新邮箱收到的 6 位验证码" /><button class="btn" type="button" id="change-email-new-code">获取验证码</button></div></label>
<p class="form-hint muted" id="change-email-new-hint" role="status"></p>
<div class="form-error" id="change-email-error" role="alert"></div>
<button class="btn primary block" type="submit">确认换绑</button>
</form>
</details>
<p id="change-email-result" class="muted" role="status"></p>
</div>
<div class="card form-card"> <div class="card form-card">
<h3>测试邮件连通性</h3> <h3>测试邮件连通性</h3>
<p class="muted">向当前账号绑定的邮箱发送测试邮件,同一邮箱每 2 分钟可测试一次。</p> <p class="muted">向当前账号绑定的邮箱发送测试邮件,同一邮箱每 2 分钟可测试一次。</p>
@@ -253,7 +269,7 @@
<div id="toast" class="toast hidden" role="status" aria-live="polite"></div> <div id="toast" class="toast hidden" role="status" aria-live="polite"></div>
<script src="/js/app.js?v=16"></script> <script src="/js/app.js?v=17"></script>
</div> </div>
</body> </body>
</html> </html>
+50
View File
@@ -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() { function fillProfile() {
$("#pf-name").value = state.me.display_name; $("#pf-name").value = state.me.display_name;
$("#pf-dept").value = state.me.department || ""; $("#pf-dept").value = state.me.department || "";
+96 -3
View File
@@ -450,6 +450,25 @@ class ProfileIn(BaseModel):
return value 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): class ActivityIn(BaseModel):
title: str = Field(min_length=1, max_length=120) title: str = Field(min_length=1, max_length=120)
start_at: int = Field(gt=0) start_at: int = Field(gt=0)
@@ -878,6 +897,11 @@ def _client_ip(request: Request) -> str:
@app.post("/api/auth/send-code") @app.post("/api/auth/send-code")
async def send_code(payload: SendCodeIn, request: Request, db: AsyncSession = Depends(get_db)) -> dict: 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: if DEV_MODE:
try: try:
local = ip_address(_client_ip(request)).is_loopback 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) code_hash = await asyncio.to_thread(hash_password, code)
stamp = now_ms() stamp = now_ms()
await db.execute(update(email_verifications).where( 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, email_verifications.c.used == 0,
).values(used=1)) ).values(used=1))
await db.execute( await db.execute(
insert(email_verifications).values( 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, 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: try:
await _send_email( await _send_email(
email, "WorkLog 验证码", email, "WorkLog 更换邮箱验证码" if scoped_purpose else "WorkLog 验证码",
f"你的验证码是 {code},{EMAIL_CODE_TTL_MIN} 分钟内有效。如果不是你本人的操作,请忽略本邮件。", f"你的验证码是 {code},{EMAIL_CODE_TTL_MIN} 分钟内有效。如果不是你本人的操作,请忽略本邮件。",
) )
except HTTPException: 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") @app.post("/api/auth/register")
async def register(payload: RegisterIn, request: Request, db: AsyncSession = Depends(get_db)) -> dict: async def register(payload: RegisterIn, request: Request, db: AsyncSession = Depends(get_db)) -> dict:
await _auth_limit(db, "verify-ip:" + _client_ip(request), 60) await _auth_limit(db, "verify-ip:" + _client_ip(request), 60)
+83
View File
@@ -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)