简化邮箱换绑流程,登录后仅验证新邮箱
This commit is contained in:
@@ -6,7 +6,7 @@
|
||||
|
||||
## 功能
|
||||
|
||||
- **邮箱换绑**:在账号设置中验证原邮箱和新邮箱后更换绑定地址;新邮箱须未被其他账号占用。账号及活动记录保留,当前会话保留、其他设备退出,原邮箱未使用验证码失效;后续使用新邮箱登录并接收提醒。
|
||||
- **邮箱换绑**:登录后在账号设置中验证新邮箱即可更换绑定地址;新邮箱须未被其他账号占用。账号及活动记录保留,当前会话保留、其他设备退出,原邮箱未使用验证码失效;后续使用新邮箱登录并接收提醒。
|
||||
- **值班提醒**:读取单双周值班 JSON,按 2026-11-06 单周周五为基准循环,北京时间前一天 18:00 汇总提醒,并在每个值班时段开始前一小时再次发送邮件;邮箱匹配、预览和部署说明见 [duty/README.md](duty/README.md)。
|
||||
- **账号体系**:注册时设置密码,通过邮箱+密码登录;也可选邮箱验证码登录,忘记密码后可凭邮箱验证码重设。注册需填写姓名、所属部门、邮箱和手机号,Bearer 会话默认 30 天有效,可改个人资料
|
||||
- **活动记录**:标题 / 分类(8 类)/ 时间 / 地点 / 描述 / 名额 / 公开或私密;发起人自动写入一条参加记录
|
||||
|
||||
Vendored
+2
-4
@@ -226,10 +226,8 @@
|
||||
<div class="card form-card">
|
||||
<details id="change-email-panel">
|
||||
<summary>更换绑定邮箱</summary>
|
||||
<p class="muted">验证原邮箱和新邮箱后换绑。换绑后请使用新邮箱登录,其他设备将退出登录。</p>
|
||||
<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>
|
||||
@@ -269,7 +267,7 @@
|
||||
|
||||
<div id="toast" class="toast hidden" role="status" aria-live="polite"></div>
|
||||
|
||||
<script src="/js/app.js?v=17"></script>
|
||||
<script src="/js/app.js?v=18"></script>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Vendored
+14
-21
@@ -938,33 +938,27 @@
|
||||
|
||||
// ------------------------------------------------------------- 设置
|
||||
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 () => {
|
||||
let emailChangePending = false;
|
||||
$("#change-email-new-code").addEventListener("click", async () => {
|
||||
const form = $("#change-email-form");
|
||||
if (kind === "new" && !form.email.reportValidity()) return;
|
||||
button.disabled = true;
|
||||
emailChangePending.add(kind);
|
||||
if (!form.email.reportValidity()) return;
|
||||
emailChangePending = true;
|
||||
updateEmailChangeButtons();
|
||||
$("#change-email-error").textContent = "";
|
||||
const email = kind === "old" ? state.me.email : form.email.value.trim();
|
||||
const 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);
|
||||
const data = await api("/auth/email/new-code", { method: "POST", body: { email } });
|
||||
$("#change-email-new-hint").textContent = data.dev_code ? `本机测试验证码:${data.dev_code}` : `验证码已发送至 ${email}`;
|
||||
emailChangeCooldowns.set(state.me.id, Date.now() + 60000);
|
||||
} catch (error) { $("#change-email-error").textContent = error.message; }
|
||||
finally { emailChangePending.delete(kind); updateEmailChangeButtons(); }
|
||||
finally { emailChangePending = false; 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);
|
||||
const left = Math.max(0, Math.ceil(((emailChangeCooldowns.get(state.me?.id) || 0) - Date.now()) / 1000));
|
||||
const button = $("#change-email-new-code");
|
||||
button.disabled = left > 0 || emailChangePending;
|
||||
button.textContent = left ? `${left} 秒后重发` : "获取验证码";
|
||||
}
|
||||
}
|
||||
setInterval(updateEmailChangeButtons, 1000);
|
||||
$("#change-email-form").addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
@@ -973,10 +967,9 @@
|
||||
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 } });
|
||||
const data = await api("/auth/email/change", { method: "POST", body: { email: form.email.value.trim(), 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 = "";
|
||||
|
||||
+2
-11
@@ -460,10 +460,9 @@ class NewEmailIn(BaseModel):
|
||||
|
||||
|
||||
class ChangeEmailIn(NewEmailIn):
|
||||
old_code: str
|
||||
new_code: str
|
||||
|
||||
@field_validator("old_code", "new_code", mode="before")
|
||||
@field_validator("new_code", mode="before")
|
||||
@classmethod
|
||||
def validate_codes(cls, value):
|
||||
return EmailCodeIn.check_code(value)
|
||||
@@ -1002,12 +1001,6 @@ async def _check_new_email(email: str, user: dict, db: AsyncSession):
|
||||
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)
|
||||
@@ -1039,11 +1032,9 @@ async def _check_change_code(db, email, code, purpose):
|
||||
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.id == new_id, email_verifications.c.used == 0,
|
||||
email_verifications.c.expires_at > now_ms(),
|
||||
).values(used=1))
|
||||
if consumed.rowcount != 1:
|
||||
|
||||
@@ -5,11 +5,9 @@ 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']}
|
||||
return {'email': email, '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')
|
||||
@@ -31,16 +29,15 @@ class ChangeEmailTests(ApiTestCase):
|
||||
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)
|
||||
self.assertEqual((await self.client.post('/api/auth/email/change', json={'email': 'x@example.test', '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):
|
||||
async def test_wrong_new_code_can_retry_with_correct_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'
|
||||
@@ -77,7 +74,7 @@ class ChangeEmailTests(ApiTestCase):
|
||||
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'
|
||||
bad = '000000' if payload['new_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, 'new_code': bad})).status_code, 400)
|
||||
self.assertEqual((await self.client.post('/api/auth/email/change', headers=auth(owner['token']), json=payload)).status_code, 429)
|
||||
|
||||
Reference in New Issue
Block a user