web: add complete password reset flow with deep link token handling
Some checks failed
Android CI / android (push) Failing after 3m59s
Android Release / release (push) Has started running
CI / test (push) Failing after 2m15s

This commit is contained in:
Codex
2026-03-09 16:09:17 +03:00
parent f708854bb2
commit 69c0b632df
4 changed files with 148 additions and 6 deletions

View File

@@ -9,6 +9,14 @@ export async function verifyEmailRequest(token: string): Promise<void> {
await http.post("/auth/verify-email", { token }); await http.post("/auth/verify-email", { token });
} }
export async function requestPasswordResetRequest(email: string): Promise<void> {
await http.post("/auth/request-password-reset", { email });
}
export async function resetPasswordRequest(token: string, password: string): Promise<void> {
await http.post("/auth/reset-password", { token, password });
}
export async function loginRequest(email: string, password: string, otpCode?: string, recoveryCode?: string): Promise<TokenPair> { export async function loginRequest(email: string, password: string, otpCode?: string, recoveryCode?: string): Promise<TokenPair> {
const { data } = await http.post<TokenPair>("/auth/login", { const { data } = await http.post<TokenPair>("/auth/login", {
email, email,

View File

@@ -12,6 +12,7 @@ import { applyAppearancePreferences, getAppPreferences } from "../utils/preferen
const PENDING_INVITE_TOKEN_KEY = "bm_pending_invite_token"; const PENDING_INVITE_TOKEN_KEY = "bm_pending_invite_token";
const AUTH_NOTICE_KEY = "bm_auth_notice"; const AUTH_NOTICE_KEY = "bm_auth_notice";
const PENDING_NOTIFICATION_NAV_KEY = "bm_pending_notification_nav"; const PENDING_NOTIFICATION_NAV_KEY = "bm_pending_notification_nav";
const PENDING_RESET_PASSWORD_TOKEN_KEY = "bm_pending_reset_password_token";
export function App() { export function App() {
const accessToken = useAuthStore((s) => s.accessToken); const accessToken = useAuthStore((s) => s.accessToken);
@@ -69,6 +70,15 @@ export function App() {
window.history.replaceState(null, "", "/"); window.history.replaceState(null, "", "/");
}, []); }, []);
useEffect(() => {
const resetToken = extractPasswordResetTokenFromLocation();
if (!resetToken) {
return;
}
window.localStorage.setItem(PENDING_RESET_PASSWORD_TOKEN_KEY, resetToken);
window.history.replaceState(null, "", "/");
}, []);
useEffect(() => { useEffect(() => {
const nav = extractNotificationNavigationFromLocation(); const nav = extractNotificationNavigationFromLocation();
if (!nav) { if (!nav) {
@@ -142,7 +152,13 @@ export function App() {
}, [accessToken, joiningInvite, loadChats, me, setActiveChatId, setFocusedMessage, showToast]); }, [accessToken, joiningInvite, loadChats, me, setActiveChatId, setFocusedMessage, showToast]);
if (!accessToken || !me) { if (!accessToken || !me) {
return <AuthPage />; const pendingResetToken = window.localStorage.getItem(PENDING_RESET_PASSWORD_TOKEN_KEY);
return (
<AuthPage
initialResetToken={pendingResetToken}
onResetTokenConsumed={() => window.localStorage.removeItem(PENDING_RESET_PASSWORD_TOKEN_KEY)}
/>
);
} }
return ( return (
<> <>
@@ -200,6 +216,17 @@ function extractNotificationNavigationFromLocation(): { chatId: number; messageI
return { chatId, messageId }; return { chatId, messageId };
} }
function extractPasswordResetTokenFromLocation(): string | null {
if (typeof window === "undefined") {
return null;
}
const url = new URL(window.location.href);
if (!/^\/reset-password\/?$/i.test(url.pathname)) {
return null;
}
return url.searchParams.get("token")?.trim() || null;
}
function inviteJoinErrorMessage(error: unknown): string { function inviteJoinErrorMessage(error: unknown): string {
const status = getHttpStatusCode(error); const status = getHttpStatusCode(error);
if (status === 404) { if (status === 404) {

View File

@@ -1,12 +1,17 @@
import axios from "axios"; import axios from "axios";
import { FormEvent, useEffect, useState } from "react"; import { FormEvent, useEffect, useState } from "react";
import { checkEmailStatus, registerRequest } from "../api/auth"; import { checkEmailStatus, registerRequest, requestPasswordResetRequest, resetPasswordRequest } from "../api/auth";
import { useAuthStore } from "../store/authStore"; import { useAuthStore } from "../store/authStore";
type Step = "email" | "password" | "register" | "otp"; type Step = "email" | "password" | "register" | "otp" | "forgot" | "reset";
const AUTH_NOTICE_KEY = "bm_auth_notice"; const AUTH_NOTICE_KEY = "bm_auth_notice";
export function AuthPanel() { interface AuthPanelProps {
initialResetToken?: string | null;
onResetTokenConsumed?: () => void;
}
export function AuthPanel({ initialResetToken = null, onResetTokenConsumed }: AuthPanelProps) {
const login = useAuthStore((s) => s.login); const login = useAuthStore((s) => s.login);
const loading = useAuthStore((s) => s.loading); const loading = useAuthStore((s) => s.loading);
const [step, setStep] = useState<Step>("email"); const [step, setStep] = useState<Step>("email");
@@ -16,6 +21,8 @@ export function AuthPanel() {
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
const [otpCode, setOtpCode] = useState(""); const [otpCode, setOtpCode] = useState("");
const [recoveryCode, setRecoveryCode] = useState(""); const [recoveryCode, setRecoveryCode] = useState("");
const [resetToken, setResetToken] = useState(initialResetToken || "");
const [newPassword, setNewPassword] = useState("");
const [useRecoveryCode, setUseRecoveryCode] = useState(false); const [useRecoveryCode, setUseRecoveryCode] = useState(false);
const [checkingEmail, setCheckingEmail] = useState(false); const [checkingEmail, setCheckingEmail] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
@@ -30,6 +37,17 @@ export function AuthPanel() {
window.localStorage.removeItem(AUTH_NOTICE_KEY); window.localStorage.removeItem(AUTH_NOTICE_KEY);
}, []); }, []);
useEffect(() => {
const prepared = initialResetToken?.trim() || "";
if (!prepared) {
return;
}
setResetToken(prepared);
setStep("reset");
setSuccess("Enter a new password to finish reset.");
onResetTokenConsumed?.();
}, [initialResetToken, onResetTokenConsumed]);
async function onSubmit(event: FormEvent) { async function onSubmit(event: FormEvent) {
event.preventDefault(); event.preventDefault();
setError(null); setError(null);
@@ -64,6 +82,35 @@ export function AuthPanel() {
return; return;
} }
if (step === "forgot") {
const normalizedEmail = email.trim().toLowerCase();
if (!normalizedEmail) {
setError("Enter email.");
return;
}
await requestPasswordResetRequest(normalizedEmail);
setSuccess("If account exists, reset email was sent.");
setStep("password");
return;
}
if (step === "reset") {
const preparedToken = resetToken.trim();
if (!preparedToken) {
setError("Reset token is required.");
return;
}
if (newPassword.trim().length < 8) {
setError("Password must be at least 8 characters.");
return;
}
await resetPasswordRequest(preparedToken, newPassword.trim());
setSuccess("Password reset successful. Sign in with new password.");
setStep("password");
setNewPassword("");
return;
}
await login( await login(
email, email,
password, password,
@@ -91,6 +138,7 @@ export function AuthPanel() {
setUseRecoveryCode(false); setUseRecoveryCode(false);
setName(""); setName("");
setUsername(""); setUsername("");
setNewPassword("");
setError(null); setError(null);
setSuccess(null); setSuccess(null);
} }
@@ -100,6 +148,10 @@ export function AuthPanel() {
? "Continue" ? "Continue"
: step === "register" : step === "register"
? "Create account" ? "Create account"
: step === "forgot"
? "Send reset email"
: step === "reset"
? "Reset password"
: step === "password" : step === "password"
? "Next" ? "Next"
: "Sign in"; : "Sign in";
@@ -150,6 +202,10 @@ export function AuthPanel() {
</> </>
) : null} ) : null}
{step === "forgot" ? (
<p className="text-xs text-slate-400">We'll send a password reset link if this account exists.</p>
) : null}
{step === "password" || step === "register" || step === "otp" ? ( {step === "password" || step === "register" || step === "otp" ? (
<input <input
className="w-full rounded bg-slate-800 px-3 py-2" className="w-full rounded bg-slate-800 px-3 py-2"
@@ -160,6 +216,24 @@ export function AuthPanel() {
/> />
) : null} ) : null}
{step === "reset" ? (
<>
<input
className="w-full rounded bg-slate-800 px-3 py-2"
placeholder="Reset token"
value={resetToken}
onChange={(e) => setResetToken(e.target.value)}
/>
<input
className="w-full rounded bg-slate-800 px-3 py-2"
placeholder="New password"
type="password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
/>
</>
) : null}
{step === "otp" ? ( {step === "otp" ? (
<> <>
<button <button
@@ -190,6 +264,34 @@ export function AuthPanel() {
<button className="w-full rounded bg-accent px-3 py-2 font-semibold text-black disabled:opacity-50" disabled={isBusy} type="submit"> <button className="w-full rounded bg-accent px-3 py-2 font-semibold text-black disabled:opacity-50" disabled={isBusy} type="submit">
{submitLabel} {submitLabel}
</button> </button>
{step === "password" ? (
<button
className="text-xs text-sky-300 hover:text-sky-200"
onClick={() => {
setError(null);
setSuccess(null);
setStep("forgot");
}}
type="button"
>
Forgot password?
</button>
) : null}
{(step === "email" || step === "forgot" || step === "password") ? (
<button
className="text-xs text-sky-300 hover:text-sky-200"
onClick={() => {
setError(null);
setSuccess(null);
setStep("reset");
}}
type="button"
>
I have reset token
</button>
) : null}
</form> </form>
{error ? <p className="mt-3 text-sm text-red-400">{error}</p> : null} {error ? <p className="mt-3 text-sm text-red-400">{error}</p> : null}
{success ? <p className="mt-3 text-sm text-emerald-400">{success}</p> : null} {success ? <p className="mt-3 text-sm text-emerald-400">{success}</p> : null}

View File

@@ -1,9 +1,14 @@
import { AuthPanel } from "../components/AuthPanel"; import { AuthPanel } from "../components/AuthPanel";
export function AuthPage() { interface AuthPageProps {
initialResetToken?: string | null;
onResetTokenConsumed?: () => void;
}
export function AuthPage({ initialResetToken = null, onResetTokenConsumed }: AuthPageProps) {
return ( return (
<main className="min-h-screen bg-gradient-to-b from-slate-900 via-slate-950 to-black p-4"> <main className="min-h-screen bg-gradient-to-b from-slate-900 via-slate-950 to-black p-4">
<AuthPanel /> <AuthPanel initialResetToken={initialResetToken} onResetTokenConsumed={onResetTokenConsumed} />
</main> </main>
); );
} }