feat: add recovery-code password reset to login

This commit is contained in:
lezi-fun committed 2026-08-13 15:13:30 +08:00
1 parent 36fc7cbeb8
commit 63db81e498
5 files changed
+162 -1

No files matched your search

+23
View File
@@ -755,6 +755,29 @@ svg {
color: var(--glass-text-light);
}
.auth-forgot-link {
display: block;
width: fit-content;
margin: 12px auto 0;
padding: 0;
border: 0;
background: none;
color: var(--primary);
font-size: 13px;
cursor: pointer;
}
.auth-forgot-link:hover {
text-decoration: underline;
}
.auth-reset-hint {
margin: -8px 0 16px;
color: var(--glass-text-secondary);
font-size: 13px;
line-height: 1.5;
}
.captcha-row {
display: flex;
align-items: center;
+69 -1
View File
@@ -17,6 +17,11 @@ export default function Modals({ modal, onClose, reportPostId }) {
// 登录表单
const [loginEmail, setLoginEmail] = useState('');
const [loginPassword, setLoginPassword] = useState('');
const [authMode, setAuthMode] = useState('login');
const [resetEmail, setResetEmail] = useState('');
const [resetRecoveryCode, setResetRecoveryCode] = useState('');
const [resetPassword, setResetPassword] = useState('');
const [resetPasswordConfirm, setResetPasswordConfirm] = useState('');
// 注册表单
const [regUsername, setRegUsername] = useState('');
@@ -33,6 +38,7 @@ export default function Modals({ modal, onClose, reportPostId }) {
if (modal === 'register') {
API.getCaptcha().then((c) => setRegCaptcha(c)).catch(() => {});
}
if (modal !== 'login') setAuthMode('login');
}, [modal]);
if (!modal) return null;
@@ -57,6 +63,34 @@ export default function Modals({ modal, onClose, reportPostId }) {
}
};
const handleResetPassword = async () => {
if (!resetEmail.trim() || !resetRecoveryCode.trim() || !resetPassword || !resetPasswordConfirm) {
toast(t('auth.resetFillAll'), 'warning');
return;
}
if (resetPassword.length < 6) {
toast(t('auth.passwordTooShort'), 'warning');
return;
}
if (resetPassword !== resetPasswordConfirm) {
toast(t('auth.passwordMismatch'), 'warning');
return;
}
try {
await API.resetPassword(resetEmail.trim(), resetRecoveryCode.trim(), resetPassword);
setAuthMode('login');
setLoginEmail(resetEmail.trim());
setLoginPassword('');
setResetEmail('');
setResetRecoveryCode('');
setResetPassword('');
setResetPasswordConfirm('');
toast(t('auth.resetSuccess'), 'success');
} catch (err) {
toast(t('auth.resetFailed', { msg: err.message }), 'error');
}
};
const handleRegister = async () => {
if (!regUsername.trim() || !regEmail.trim() || !regPassword) { toast('请填写完整信息', 'warning'); return; }
if (regPassword.length < 6) { toast('密码至少6位', 'warning'); return; }
@@ -95,7 +129,7 @@ export default function Modals({ modal, onClose, reportPostId }) {
return (
<>
{modal === 'login' && (
{modal === 'login' && authMode === 'login' && (
<div className="modal active" onClick={close}>
<div className="modal-content">
<span className="close" onClick={onClose}><Icon name="close" size={20} /></span>
@@ -104,6 +138,40 @@ export default function Modals({ modal, onClose, reportPostId }) {
<input type="password" placeholder={t('auth.password')} value={loginPassword} onChange={(e) => setLoginPassword(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter') handleLogin(); }} />
<button className="btn-primary" style={{ width: '100%' }} onClick={handleLogin}>{t('auth.login')}</button>
<button
type="button"
className="auth-forgot-link"
onClick={() => {
setResetEmail(loginEmail);
setAuthMode('forgot');
}}
>
{t('auth.forgotPassword')}
</button>
</div>
</div>
)}
{modal === 'login' && authMode === 'forgot' && (
<div className="modal active" onClick={close}>
<div className="modal-content">
<span className="close" onClick={onClose}><Icon name="close" size={20} /></span>
<h2 style={{ marginBottom: 16 }}>{t('auth.resetTitle')}</h2>
<p className="auth-reset-hint">{t('auth.resetHint')}</p>
<input type="email" placeholder={t('auth.email')} value={resetEmail} onChange={(e) => setResetEmail(e.target.value)} />
<input type="text" placeholder={t('auth.recoveryCode')} value={resetRecoveryCode} onChange={(e) => setResetRecoveryCode(e.target.value)} />
<input type="password" placeholder={t('auth.newPassword')} value={resetPassword} onChange={(e) => setResetPassword(e.target.value)} />
<input
type="password"
placeholder={t('auth.confirmPassword')}
value={resetPasswordConfirm}
onChange={(e) => setResetPasswordConfirm(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter') handleResetPassword(); }}
/>
<button className="btn-primary" style={{ width: '100%' }} onClick={handleResetPassword}>{t('auth.resetPassword')}</button>
<button type="button" className="auth-forgot-link" onClick={() => setAuthMode('login')}>
{t('auth.backToLogin')}
</button>
</div>
</div>
)}
+12
View File
@@ -73,6 +73,18 @@
"username": "Username",
"passwordHint": "Password (min 6 chars)",
"forgotPassword": "Forgot password?",
"resetTitle": "Reset password with a recovery code",
"resetHint": "Enter your email and a recovery code generated in Settings to set a new password.",
"recoveryCode": "Recovery code",
"newPassword": "New password (min 6 characters)",
"confirmPassword": "Confirm new password",
"resetPassword": "Reset password",
"backToLogin": "Back to login",
"resetFillAll": "Please fill in all fields",
"passwordTooShort": "New password must be at least 6 characters",
"passwordMismatch": "The passwords do not match",
"resetSuccess": "Password reset. Please log in with your new password.",
"resetFailed": "Password reset failed: {{msg}}",
"captchaError": "Wrong captcha, please try again",
"registerSuccess": "Registration successful",
"loginSuccess": "Logged in",
+12
View File
@@ -73,6 +73,18 @@
"username": "用户名",
"passwordHint": "密码(至少6位)",
"forgotPassword": "忘记密码?",
"resetTitle": "通过恢复码重置密码",
"resetHint": "输入邮箱和设置中生成的恢复码,即可设置新密码。",
"recoveryCode": "恢复码",
"newPassword": "新密码(至少6位)",
"confirmPassword": "确认新密码",
"resetPassword": "重置密码",
"backToLogin": "返回登录",
"resetFillAll": "请填写完整信息",
"passwordTooShort": "新密码至少6位",
"passwordMismatch": "两次输入的密码不一致",
"resetSuccess": "密码重置成功,请使用新密码登录",
"resetFailed": "密码重置失败:{{msg}}",
"captchaError": "验证码错误,请重新计算",
"registerSuccess": "注册成功",
"loginSuccess": "登录成功",
+46
View File
@@ -22,6 +22,7 @@ async function api(path, options = {}) {
let adminToken = null;
let adminId = null;
let userId = null;
let userToken = null;
let postId = null;
let postNumber = null;
let replyId = null;
@@ -67,6 +68,51 @@ test('注册普通用户', async () => {
userId = data.user.id;
});
test('普通用户登录', async () => {
const { status, data } = await api('/auth/login', {
method: 'POST',
body: JSON.stringify({ email: normalUser.email, password: normalUser.password }),
});
assert.equal(status, 200);
assert.ok(data.token);
userToken = data.token;
});
test('恢复码可重置密码且只能使用一次', async () => {
const generated = await api('/auth/recovery-codes/generate', {
method: 'POST',
headers: { Authorization: `Bearer ${userToken}` },
});
assert.equal(generated.status, 200);
assert.equal(generated.data.codes.length, 10);
const recoveryCode = generated.data.codes[0];
const newPassword = '654321';
const reset = await api('/auth/reset-password', {
method: 'POST',
body: JSON.stringify({ email: normalUser.email, recoveryCode, newPassword }),
});
assert.equal(reset.status, 200);
const oldLogin = await api('/auth/login', {
method: 'POST',
body: JSON.stringify({ email: normalUser.email, password: normalUser.password }),
});
assert.equal(oldLogin.status, 401);
const newLogin = await api('/auth/login', {
method: 'POST',
body: JSON.stringify({ email: normalUser.email, password: newPassword }),
});
assert.equal(newLogin.status, 200);
const reused = await api('/auth/reset-password', {
method: 'POST',
body: JSON.stringify({ email: normalUser.email, recoveryCode, newPassword: normalUser.password }),
});
assert.equal(reused.status, 400);
});
test('密码少于6位被拒绝', async () => {
const { status } = await api('/auth/register', {
method: 'POST',