feat(frontend): rebuild auth around mobile-first flow
Some checks failed
Frontend CI/CD / build (push) Has been cancelled
Frontend CI/CD / deploy (push) Has been cancelled

This commit is contained in:
2026-05-21 10:28:03 +03:30
parent 66bb2fa107
commit f2b4cfce1a
17 changed files with 2703 additions and 752 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,471 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { AlertTriangle, ArrowLeft, CheckCircle2, Loader2 } from "lucide-react";
import SearchableCombobox from "@/components/SearchableCombobox";
import OtpCodeField from "@/components/OtpCodeField";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useAuth } from "@/contexts/AuthContext";
import { useToast } from "@/hooks/use-toast";
import { api } from "@/lib/api";
import { Link, useNavigate, useSearchParams } from "@/lib/router";
import type { GoogleFlowResponseSchema } from "@/lib/types";
import { resolveErrorMessage } from "@/lib/utils";
type CallbackStep = "loading" | "collect_profile" | "claim_required" | "error";
const normalizeDigits = (value: string) =>
value
.replace(/[\u06F0-\u06F9]/g, (digit) => String(digit.charCodeAt(0) - 0x06f0))
.replace(/[\u0660-\u0669]/g, (digit) => String(digit.charCodeAt(0) - 0x0660));
const sanitizeMobile = (value: string) => normalizeDigits(value).replace(/[^\d]/g, "");
const sanitizeUsername = (value: string) => value.replace(/[^A-Za-z0-9._-]/g, "");
export default function GoogleAuthCallback() {
const navigate = useNavigate();
const { toast } = useToast();
const { setSessionTokens } = useAuth();
const [searchParams] = useSearchParams();
const flow = searchParams.get("flow") || "";
const [step, setStep] = useState<CallbackStep>("loading");
const [loading, setLoading] = useState(false);
const [otpCooldown, setOtpCooldown] = useState(0);
const [googleFlow, setGoogleFlow] = useState<GoogleFlowResponseSchema | null>(null);
const [profileForm, setProfileForm] = useState({
mobile: "",
username: "",
first_name: "",
last_name: "",
student_id: "",
year_of_study: "",
major: null as string | null,
university: null as string | null,
});
const [claimCode, setClaimCode] = useState("");
const { data: majors = [] } = useQuery({
queryKey: ["majors"],
queryFn: () => api.getMajors(),
staleTime: 7 * 24 * 60 * 60 * 1000,
enabled: step === "collect_profile",
});
const { data: universities = [] } = useQuery({
queryKey: ["universities"],
queryFn: () => api.getUniversities(),
staleTime: 7 * 24 * 60 * 60 * 1000,
enabled: step === "collect_profile",
});
const majorItems = useMemo(
() => majors.map((major) => ({ value: String(major.code), label: major.label })),
[majors],
);
const universityItems = useMemo(
() => universities.map((university) => ({ value: String(university.code), label: university.label })),
[universities],
);
useEffect(() => {
if (otpCooldown <= 0) {
return;
}
const timer = window.setTimeout(() => setOtpCooldown((current) => current - 1), 1000);
return () => window.clearTimeout(timer);
}, [otpCooldown]);
const handleAuthenticatedFlow = useCallback(async (payload: GoogleFlowResponseSchema) => {
if (!payload.access_token || !payload.refresh_token) {
throw new Error("توکن‌های ورود گوگل دریافت نشد.");
}
await setSessionTokens(payload.access_token, payload.refresh_token);
toast({
title: "ورود با گوگل کامل شد",
description: "حساب شما با موفقیت بازیابی یا متصل شد.",
variant: "success",
});
navigate("/profile", { replace: true });
}, [navigate, setSessionTokens, toast]);
const applyFlow = useCallback(async (payload: GoogleFlowResponseSchema) => {
setGoogleFlow(payload);
if (payload.status === "authenticated") {
await handleAuthenticatedFlow(payload);
return;
}
if (payload.status === "claim_required") {
setProfileForm((current) => ({
...current,
mobile: payload.mobile || current.mobile,
}));
setStep("claim_required");
return;
}
if (payload.status === "collect_profile") {
setProfileForm((current) => ({
...current,
mobile: payload.mobile || current.mobile,
first_name: payload.first_name || current.first_name,
last_name: payload.last_name || current.last_name,
}));
setStep("collect_profile");
return;
}
setStep("error");
}, [handleAuthenticatedFlow]);
useEffect(() => {
if (!flow) {
setStep("error");
return;
}
let cancelled = false;
const loadFlow = async () => {
setLoading(true);
try {
const payload = await api.getGoogleFlow(flow);
if (!cancelled) {
await applyFlow(payload);
}
} catch (error: unknown) {
if (!cancelled) {
toast({
title: "اتصال گوگل کامل نشد",
description: resolveErrorMessage(error, "لینک گوگل نامعتبر یا منقضی شده است."),
variant: "destructive",
});
setStep("error");
}
} finally {
if (!cancelled) {
setLoading(false);
}
}
};
void loadFlow();
return () => {
cancelled = true;
};
}, [applyFlow, flow, toast]);
const handleCompleteProfile = async (event: React.FormEvent) => {
event.preventDefault();
try {
setLoading(true);
const payload = await api.completeGoogleSignup({
flow,
mobile: sanitizeMobile(profileForm.mobile),
username: googleFlow?.resolution === "new_account" ? profileForm.username : undefined,
student_id: profileForm.student_id || undefined,
year_of_study: profileForm.year_of_study ? Number(profileForm.year_of_study) : undefined,
major: profileForm.major || undefined,
university: profileForm.university || undefined,
first_name: profileForm.first_name || undefined,
last_name: profileForm.last_name || undefined,
});
if (payload.status === "claim_required") {
setOtpCooldown(120);
}
await applyFlow(payload);
} catch (error: unknown) {
toast({
title: "تکمیل ورود با گوگل ناموفق بود",
description: resolveErrorMessage(error, "اطلاعات تکمیلی قابل پذیرش نیست."),
variant: "destructive",
});
} finally {
setLoading(false);
}
};
const handleResendClaimOtp = async () => {
try {
setLoading(true);
await api.resendGoogleClaimOtp(flow);
setOtpCooldown(120);
toast({
title: "کد پیامکی دوباره ارسال شد",
description: "کد تازه را وارد کنید تا فرایند اتصال حساب کامل شود.",
variant: "success",
});
} catch (error: unknown) {
toast({
title: "ارسال مجدد ناموفق بود",
description: resolveErrorMessage(error, "امکان ارسال دوباره کد وجود ندارد."),
variant: "destructive",
});
} finally {
setLoading(false);
}
};
const handleVerifyClaim = async (event: React.FormEvent) => {
event.preventDefault();
try {
setLoading(true);
const payload = await api.verifyGoogleClaim(flow, normalizeDigits(claimCode));
await applyFlow(payload);
} catch (error: unknown) {
toast({
title: "تأیید حساب ناموفق بود",
description: resolveErrorMessage(error, "کد پیامکی معتبر نیست."),
variant: "destructive",
});
} finally {
setLoading(false);
}
};
const title =
step === "claim_required"
? "تأیید شماره موبایل"
: step === "collect_profile"
? "تکمیل اطلاعات حساب"
: step === "error"
? "ورود با گوگل متوقف شد"
: "در حال بازیابی حساب";
const description =
step === "claim_required"
? "برای اتصال نهایی حساب، مالکیت شماره موبایل را با کد پیامکی تأیید کنید."
: step === "collect_profile"
? googleFlow?.resolution === "existing_email_claim"
? "ایمیل گوگل شما با یک حساب قدیمی تطابق دارد. موبایل همان حساب را تأیید کنید تا بازیابی کامل شود."
: "این اولین ورود شما با گوگل است. اطلاعات تکمیلی را ثبت کنید تا حساب شما ساخته شود."
: step === "error"
? "لینک این فرایند منقضی شده یا از سمت گوگل کامل نشده است."
: "چند لحظه صبر کنید تا وضعیت حساب گوگل شما بررسی شود.";
return (
<div className="min-h-screen bg-background px-4 py-10" dir="rtl">
<div className="mx-auto max-w-3xl">
<Card className="border-border/70 bg-background/90 shadow-xl">
<CardHeader className="text-right">
<CardTitle>{title}</CardTitle>
<CardDescription className="leading-7">{description}</CardDescription>
</CardHeader>
<CardContent className="space-y-5">
{step === "loading" ? (
<div className="flex items-center justify-center gap-3 rounded-[1.5rem] border border-border/70 bg-muted/20 px-4 py-10 text-muted-foreground">
<Loader2 className="h-5 w-5 animate-spin" />
در حال دریافت وضعیت حساب گوگل...
</div>
) : null}
{step === "collect_profile" ? (
<form className="space-y-5" onSubmit={handleCompleteProfile}>
{googleFlow?.email ? (
<div className="rounded-[1.5rem] border border-primary/15 bg-primary/5 p-4 text-right text-sm text-muted-foreground">
<p className="font-medium text-foreground">ایمیل متصل به گوگل</p>
<p className="mt-2">{googleFlow.email}</p>
{googleFlow.mobile_hint ? (
<p className="mt-3 text-xs">
راهنما: حساب قدیمی با موبایل {googleFlow.mobile_hint} شناخته شده است.
</p>
) : null}
</div>
) : null}
<div className="grid gap-4 md:grid-cols-2">
<div>
<Label className="mb-2 block text-right">نام</Label>
<Input
value={profileForm.first_name}
onChange={(event) => setProfileForm((current) => ({ ...current, first_name: event.target.value }))}
className="h-12 rounded-2xl"
/>
</div>
<div>
<Label className="mb-2 block text-right">نام خانوادگی</Label>
<Input
value={profileForm.last_name}
onChange={(event) => setProfileForm((current) => ({ ...current, last_name: event.target.value }))}
className="h-12 rounded-2xl"
/>
</div>
</div>
<div className="grid gap-4 md:grid-cols-2">
<div>
<Label className="mb-2 block text-right">شماره موبایل</Label>
<Input
dir="ltr"
inputMode="numeric"
value={profileForm.mobile}
onChange={(event) => setProfileForm((current) => ({ ...current, mobile: sanitizeMobile(event.target.value) }))}
className="h-12 rounded-2xl"
placeholder="09xxxxxxxxx"
/>
</div>
{googleFlow?.resolution === "new_account" ? (
<div>
<Label className="mb-2 block text-right">نام کاربری</Label>
<Input
dir="ltr"
value={profileForm.username}
onChange={(event) => setProfileForm((current) => ({ ...current, username: sanitizeUsername(event.target.value) }))}
className="h-12 rounded-2xl"
placeholder="latin.username"
/>
</div>
) : null}
</div>
{googleFlow?.resolution === "new_account" ? (
<>
<div className="grid gap-4 md:grid-cols-2">
<div>
<Label className="mb-2 block text-right">دانشگاه</Label>
<SearchableCombobox
items={universityItems}
value={profileForm.university}
onChange={(value) => setProfileForm((current) => ({ ...current, university: value }))}
placeholder="انتخاب دانشگاه"
searchPlaceholder="نام دانشگاه را بنویسید..."
emptyText="دانشگاهی پیدا نشد"
dir="rtl"
/>
</div>
<div>
<Label className="mb-2 block text-right">رشته تحصیلی</Label>
<SearchableCombobox
items={majorItems}
value={profileForm.major}
onChange={(value) => setProfileForm((current) => ({ ...current, major: value }))}
placeholder="انتخاب رشته"
searchPlaceholder="نام رشته را بنویسید..."
emptyText="رشته‌ای پیدا نشد"
dir="rtl"
/>
</div>
</div>
<div className="grid gap-4 md:grid-cols-2">
<div>
<Label className="mb-2 block text-right">شماره دانشجویی (اختیاری)</Label>
<Input
dir="ltr"
inputMode="numeric"
value={profileForm.student_id}
onChange={(event) => setProfileForm((current) => ({ ...current, student_id: sanitizeMobile(event.target.value) }))}
className="h-12 rounded-2xl"
/>
</div>
<div>
<Label className="mb-2 block text-right">سال ورودی (اختیاری)</Label>
<Input
dir="ltr"
inputMode="numeric"
value={profileForm.year_of_study}
onChange={(event) => setProfileForm((current) => ({ ...current, year_of_study: sanitizeMobile(event.target.value) }))}
className="h-12 rounded-2xl"
/>
</div>
</div>
</>
) : (
<div className="rounded-[1.5rem] border border-amber-400/30 bg-amber-500/10 p-4 text-right text-sm leading-7 text-amber-900 dark:text-amber-100">
این مسیر برای بازیابی حساب قدیمی است. پس از ثبت موبایل، یک کد پیامکی ارسال میشود تا مالکیت حساب تأیید شود.
</div>
)}
<Button type="submit" className="h-12 w-full rounded-2xl" disabled={loading}>
{loading ? (
<>
<Loader2 className="ml-2 h-4 w-4 animate-spin" />
در حال ادامه...
</>
) : (
"ادامه و دریافت کد تأیید"
)}
</Button>
</form>
) : null}
{step === "claim_required" ? (
<form className="space-y-5" onSubmit={handleVerifyClaim}>
<div className="rounded-[1.5rem] border border-primary/15 bg-primary/5 p-4 text-right text-sm leading-7 text-muted-foreground">
<p className="font-medium text-foreground">کد به این شماره ارسال شده است</p>
<p className="mt-2">{googleFlow?.mobile_hint || googleFlow?.mobile || profileForm.mobile}</p>
{googleFlow?.resolution === "new_account" ? (
<p className="mt-3 text-xs">
بعد از تأیید این کد، حساب جدید شما ساخته میشود و مستقیماً وارد سایت میشوید.
</p>
) : (
<p className="mt-3 text-xs">
بعد از تأیید این کد، حساب قدیمی شما به گوگل متصل میشود و بازیابی کامل خواهد شد.
</p>
)}
</div>
<div>
<Label className="mb-3 block text-right">کد پیامکی</Label>
<OtpCodeField value={claimCode} onChange={(value) => setClaimCode(normalizeDigits(value))} disabled={loading} />
</div>
<div className="flex flex-col gap-3 sm:flex-row-reverse">
<Button type="submit" className="h-12 flex-1 rounded-2xl" disabled={loading || claimCode.length !== 5}>
{loading ? (
<>
<Loader2 className="ml-2 h-4 w-4 animate-spin" />
در حال تأیید...
</>
) : (
<>
<CheckCircle2 className="ml-2 h-4 w-4" />
تأیید و ورود
</>
)}
</Button>
<Button
type="button"
variant="outline"
className="h-12 rounded-2xl"
onClick={() => void handleResendClaimOtp()}
disabled={loading || otpCooldown > 0}
>
{otpCooldown > 0 ? `ارسال مجدد تا ${otpCooldown} ثانیه` : "ارسال دوباره کد"}
</Button>
</div>
</form>
) : null}
{step === "error" ? (
<div className="space-y-5">
<div className="rounded-[1.5rem] border border-amber-400/30 bg-amber-500/10 p-4 text-right text-sm leading-7 text-amber-900 dark:text-amber-100">
<div className="flex items-start justify-between gap-3">
<AlertTriangle className="mt-0.5 h-5 w-5 shrink-0" />
<div>
<p className="font-semibold">فرایند گوگل کامل نشد</p>
<p className="mt-2">
دوباره از صفحه ورود شروع کنید. اگر مشکل ادامه داشت، از ورود با موبایل یا بازیابی با موبایل استفاده کنید.
</p>
</div>
</div>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<Button type="button" className="h-12 rounded-2xl" onClick={() => void api.startGoogleLogin()}>
شروع دوباره با گوگل
</Button>
<Button asChild variant="outline" className="h-12 rounded-2xl">
<Link to="/auth">
<ArrowLeft className="ml-2 h-4 w-4" />
بازگشت به ورود
</Link>
</Button>
</div>
</div>
) : null}
</CardContent>
</Card>
</div>
</div>
);
}

View File

@@ -643,8 +643,8 @@ export default function Profile() {
<div className="flex flex-col items-start justify-between gap-8 lg:flex-row-reverse">
<div className="flex flex-1 flex-col items-start gap-5 text-right lg:items-end">
<div className="flex flex-wrap items-center gap-2 lg:justify-end">
<Badge variant={me?.is_email_verified ? "default" : "secondary"}>
{me?.is_email_verified ? "ایمیل تأیید شده" : "در انتظار تأیید ایمیل"}
<Badge variant={me?.is_mobile_verified ? "default" : "secondary"}>
{me?.is_mobile_verified ? وبایل تأیید شده" : "نیازمند تأیید موبایل"}
</Badge>
{isAdminUser ? <Badge variant="outline">دسترسی مدیریتی</Badge> : null}
<Badge variant="secondary">
@@ -786,6 +786,7 @@ export default function Profile() {
<CardTitle className="text-base">وضعیت حساب</CardTitle>
</CardHeader>
<CardContent className="space-y-1">
<InfoRow label="موبایل" value={me?.mobile || "—"} />
<InfoRow label="ایمیل" value={me?.email || "—"} />
<InfoRow label="نام کاربری" value={me?.username || "—"} />
<InfoRow
@@ -793,18 +794,22 @@ export default function Profile() {
value={me?.date_joined ? formatJalali(me.date_joined, false) : "—"}
/>
<InfoRow
label="تأیید ایمیل"
label="تأیید موبایل"
value={
<span className="inline-flex items-center gap-2">
{me?.is_email_verified ? (
{me?.is_mobile_verified ? (
<BadgeCheck className="h-4 w-4 text-emerald-600" />
) : (
<Clock3 className="h-4 w-4 text-amber-600" />
)}
{me?.is_email_verified ? "تأیید شده" : "در انتظار"}
{me?.is_mobile_verified ? "تأیید شده" : "در انتظار"}
</span>
}
/>
<InfoRow
label="اتصال گوگل"
value={me?.has_google_link ? "متصل" : "متصل نیست"}
/>
<InfoRow
label="سطح دسترسی"
value={isAdminUser ? "مدیریتی" : "کاربر عادی"}
@@ -829,7 +834,7 @@ export default function Profile() {
<Button variant="secondary" className="justify-between rounded-2xl py-6" asChild>
<Link to="/reset-password">
<span>درخواست تغییر رمز عبور</span>
<span>بازیابی یا تغییر رمز با موبایل</span>
<Mail className="h-4 w-4" />
</Link>
</Button>

View File

@@ -1,77 +1,77 @@
"use client";
import { useState } from 'react';
import { useParams, useNavigate } from '@/lib/router';
import { useToast } from '@/hooks/use-toast';
import { api } from '@/lib/api';
import { resolveErrorMessage } from '@/lib/utils';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { useQuery } from "@tanstack/react-query";
import { AlertTriangle, ArrowLeft, Loader2, ShieldAlert } from "lucide-react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { api } from "@/lib/api";
import { Link, useParams } from "@/lib/router";
import { resolveErrorMessage } from "@/lib/utils";
export default function ResetPasswordConfirm() {
const { token } = useParams<{ token: string }>();
const navigate = useNavigate();
const { toast } = useToast();
const [password, setPassword] = useState('');
const [confirm, setConfirm] = useState('');
const [loading, setLoading] = useState(false);
const { data, isLoading, isError, error } = useQuery({
queryKey: ["legacy-reset-guidance", token],
queryFn: () => api.getLegacyResetTokenMessage(token || ""),
retry: false,
});
const onSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!token) {
toast({ title: 'توکن نامعتبر است', variant: 'destructive' });
return;
}
if (password.length < 8) {
toast({ title: 'رمز عبور کوتاه است', description: 'حداقل ۸ کاراکتر', variant: 'destructive' });
return;
}
if (password !== confirm) {
toast({ title: 'عدم تطابق', description: 'تکرار رمز با رمز جدید یکسان نیست', variant: 'destructive' });
return;
}
try {
setLoading(true);
await api.resetPasswordConfirm(token, password);
toast({ title: 'رمز عبور با موفقیت تغییر کرد', variant: 'success' });
navigate('/auth');
} catch (error: unknown) {
toast({
title: 'خطا',
description: resolveErrorMessage(error, 'مشکلی رخ داد'),
variant: 'destructive',
});
} finally {
setLoading(false);
}
};
const message = isError
? resolveErrorMessage(error, "این مسیر دیگر برای بازیابی رمز عبور فعال نیست.")
: data?.message ||
"لینک بازیابی ایمیلی غیرفعال شده است. برای ادامه از بازیابی با موبایل یا ورود با گوگل استفاده کنید.";
return (
<div className="min-h-screen bg-background flex items-center justify-center p-4">
<Card className="w-full max-w-md" dir="rtl">
<CardHeader>
<CardTitle>تعیین رمز جدید</CardTitle>
<CardDescription>رمز عبور جدید را وارد کنید</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={onSubmit} className="space-y-4">
<div>
<Label htmlFor="password">رمز عبور جدید</Label>
<Input id="password" type="password" required value={password} onChange={(e) => setPassword(e.target.value)} />
<div className="min-h-screen bg-background px-4 py-10" dir="rtl">
<div className="mx-auto max-w-2xl">
<Card className="border-border/70 bg-background/90 shadow-xl">
<CardHeader className="text-right">
<div className="mb-4 inline-flex rounded-2xl border border-amber-400/30 bg-amber-500/10 p-3 text-amber-700 dark:text-amber-100">
<ShieldAlert className="h-5 w-5" />
</div>
<div>
<Label htmlFor="confirm">تکرار رمز</Label>
<Input id="confirm" type="password" required value={confirm} onChange={(e) => setConfirm(e.target.value)} />
<CardTitle>لینک بازیابی قدیمی غیرفعال شده است</CardTitle>
<CardDescription className="leading-7">
مسیرهای مبتنی بر ایمیل دیگر برای بازیابی حساب استفاده نمیشوند.
</CardDescription>
</CardHeader>
<CardContent className="space-y-5 text-right">
<div className="rounded-[1.5rem] border border-border/70 bg-muted/25 p-4 text-sm leading-7 text-muted-foreground">
{isLoading ? (
<span className="flex items-center justify-end gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
در حال دریافت راهنمای بازیابی...
</span>
) : (
message
)}
</div>
<Button type="submit" className="w-full" disabled={loading}>
{loading ? 'در حال ثبت...' : 'ثبت رمز جدید'}
</Button>
</form>
</CardContent>
</Card>
<div className="rounded-[1.5rem] border border-amber-400/30 bg-amber-500/10 p-4 text-sm leading-7 text-amber-900 dark:text-amber-100">
<div className="flex items-start justify-between gap-3">
<AlertTriangle className="mt-0.5 h-5 w-5 shrink-0" />
<div>
<p className="font-semibold">راه جایگزین</p>
<p className="mt-2">
از صفحه بازیابی با موبایل استفاده کنید. اگر موبایل ثبتشده را هم در دسترس ندارید، ورود با گوگل و همان ایمیل قبلی بهترین مسیر بازیابی است.
</p>
</div>
</div>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<Button asChild className="h-12 rounded-2xl">
<Link to="/reset-password">بازیابی با موبایل</Link>
</Button>
<Button asChild variant="outline" className="h-12 rounded-2xl">
<Link to="/auth">
<ArrowLeft className="ml-2 h-4 w-4" />
بازگشت به ورود
</Link>
</Button>
</div>
</CardContent>
</Card>
</div>
</div>
);
}

View File

@@ -1,35 +1,103 @@
"use client";
import { useState } from 'react';
import { useToast } from '@/hooks/use-toast';
import { api } from '@/lib/api';
import { resolveErrorMessage } from '@/lib/utils';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { useEffect, useState } from "react";
import { AlertTriangle, Loader2, ShieldCheck } from "lucide-react";
import OtpCodeField from "@/components/OtpCodeField";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useToast } from "@/hooks/use-toast";
import { api } from "@/lib/api";
import { Link } from "@/lib/router";
import { resolveErrorMessage } from "@/lib/utils";
const normalizeDigits = (value: string) =>
value
.replace(/[\u06F0-\u06F9]/g, (digit) => String(digit.charCodeAt(0) - 0x06f0))
.replace(/[\u0660-\u0669]/g, (digit) => String(digit.charCodeAt(0) - 0x0660));
const sanitizeMobile = (value: string) => normalizeDigits(value).replace(/[^\d]/g, "");
export default function ResetPasswordRequest() {
const { toast } = useToast();
const [email, setEmail] = useState('');
const [mobile, setMobile] = useState("");
const [code, setCode] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [loading, setLoading] = useState(false);
const [cooldown, setCooldown] = useState(0);
const onSubmit = async (e: React.FormEvent) => {
e.preventDefault();
useEffect(() => {
if (cooldown <= 0) {
return;
}
const timer = window.setTimeout(() => setCooldown((current) => current - 1), 1000);
return () => window.clearTimeout(timer);
}, [cooldown]);
const handleSendOtp = async () => {
try {
setLoading(true);
await api.requestPasswordReset(email);
const response = await api.sendOtp({
mobile: sanitizeMobile(mobile),
mode: "reset_password",
});
setCooldown(Math.min(response.expires_in_seconds, 120));
toast({
title: 'اگر ایمیلی ثبت شده باشد، لینک بازیابی ارسال شد',
description: 'ایمیل خود را بررسی کنید.',
variant: 'success'
title: "کد بازیابی ارسال شد",
description: response.message,
variant: "success",
});
} catch (error: unknown) {
// بک‌اند 200 می‌دهد حتی اگر ایمیل نباشد؛ اما اگر اروری بیاید، نشان بده
toast({
title: 'خطا',
description: resolveErrorMessage(error, 'مشکلی رخ داد'),
variant: 'destructive',
title: "ارسال کد انجام نشد",
description: resolveErrorMessage(error, "امکان ارسال پیامک بازیابی وجود ندارد."),
variant: "destructive",
});
} finally {
setLoading(false);
}
};
const handleResetPassword = async (event: React.FormEvent) => {
event.preventDefault();
if (newPassword.length < 8) {
toast({
title: "رمز عبور کوتاه است",
description: "رمز جدید باید حداقل ۸ کاراکتر داشته باشد.",
variant: "destructive",
});
return;
}
if (newPassword !== confirmPassword) {
toast({
title: "عدم تطابق رمزها",
description: "تکرار رمز عبور با رمز جدید یکسان نیست.",
variant: "destructive",
});
return;
}
try {
setLoading(true);
await api.resetPassword({
mobile: sanitizeMobile(mobile),
code: normalizeDigits(code),
new_password: newPassword,
});
toast({
title: "رمز عبور تغییر کرد",
description: "اکنون می‌توانید با رمز جدید وارد شوید.",
variant: "success",
});
setCode("");
setNewPassword("");
setConfirmPassword("");
} catch (error: unknown) {
toast({
title: "بازیابی ناموفق بود",
description: resolveErrorMessage(error, "کد تأیید یا رمز جدید قابل پذیرش نیست."),
variant: "destructive",
});
} finally {
setLoading(false);
@@ -37,24 +105,131 @@ export default function ResetPasswordRequest() {
};
return (
<div className="min-h-screen bg-background flex items-center justify-center p-4">
<Card className="w-full max-w-md" dir="rtl">
<CardHeader>
<CardTitle>بازیابی رمز عبور</CardTitle>
<CardDescription>ایمیلتان را وارد کنید تا لینک بازیابی برای شما ارسال شود</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={onSubmit} className="space-y-4">
<div>
<Label htmlFor="email">ایمیل</Label>
<Input id="email" type="email" required value={email} onChange={(e) => setEmail(e.target.value)} />
<div className="min-h-screen bg-background px-4 py-10" dir="rtl">
<div className="mx-auto flex w-full max-w-4xl flex-col gap-6 lg:flex-row">
<Card className="border-border/70 bg-background/85 shadow-xl backdrop-blur-xl lg:w-[22rem]">
<CardHeader className="text-right">
<CardTitle>بازیابی حساب بدون ایمیل</CardTitle>
<CardDescription className="leading-7">
بازیابی رمز عبور اکنون با موبایل و کد پیامکی انجام میشود. اگر به موبایل ثبتشده هم دسترسی ندارید، از همان حساب گوگلی که قبلاً با ایمیلتان استفاده میکردید کمک بگیرید.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4 text-right">
<div className="rounded-[1.5rem] border border-amber-400/30 bg-amber-500/10 p-4 text-sm leading-7 text-amber-900 dark:text-amber-100">
<div className="flex items-start justify-between gap-3">
<AlertTriangle className="mt-0.5 h-5 w-5 shrink-0" />
<div>
<p className="font-semibold">اگر رمز را فراموش کردهاید</p>
<p className="mt-2">
میتوانید از مسیر ورود با گوگل ادامه دهید؛ به شرطی که حساب گوگل شما با ایمیل قدیمیتان یکسان باشد.
</p>
</div>
</div>
</div>
<Button type="submit" className="w-full" disabled={loading}>
{loading ? 'در حال ارسال...' : 'ارسال لینک بازیابی'}
<Button
type="button"
variant="outline"
className="h-12 w-full rounded-2xl"
onClick={() => void api.startGoogleLogin()}
>
ادامه با حساب گوگل
</Button>
</form>
</CardContent>
</Card>
<div className="rounded-[1.5rem] border border-border/70 bg-muted/20 p-4 text-sm leading-7 text-muted-foreground">
<p className="font-medium text-foreground">گامهای بازیابی</p>
<ol className="mt-2 space-y-2">
<li>۱. موبایل ثبتشده را وارد کنید.</li>
<li>۲. کد پیامکی را دریافت و ثبت کنید.</li>
<li>۳. رمز عبور جدید را تعیین کنید.</li>
</ol>
</div>
</CardContent>
</Card>
<Card className="flex-1 border-border/70 bg-background/90 shadow-xl backdrop-blur-xl">
<CardHeader className="text-right">
<CardTitle>تغییر رمز عبور با کد پیامکی</CardTitle>
<CardDescription>
این فرم جایگزین کامل بازیابی ایمیلی است.
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleResetPassword} className="space-y-5">
<div>
<Label htmlFor="mobile" className="mb-2 block text-right">شماره موبایل</Label>
<Input
id="mobile"
type="tel"
dir="ltr"
inputMode="numeric"
value={mobile}
onChange={(event) => setMobile(sanitizeMobile(event.target.value))}
placeholder="09xxxxxxxxx"
className="h-12 rounded-2xl"
/>
</div>
<div>
<Label className="mb-3 block text-right">کد بازیابی</Label>
<OtpCodeField value={code} onChange={(value) => setCode(normalizeDigits(value))} disabled={loading} />
</div>
<div className="grid gap-4 md:grid-cols-2">
<div>
<Label htmlFor="new-password" className="mb-2 block text-right">رمز عبور جدید</Label>
<Input
id="new-password"
type="password"
value={newPassword}
onChange={(event) => setNewPassword(event.target.value)}
className="h-12 rounded-2xl"
/>
</div>
<div>
<Label htmlFor="confirm-password" className="mb-2 block text-right">تکرار رمز عبور</Label>
<Input
id="confirm-password"
type="password"
value={confirmPassword}
onChange={(event) => setConfirmPassword(event.target.value)}
className="h-12 rounded-2xl"
/>
</div>
</div>
<div className="flex flex-col gap-3 sm:flex-row-reverse">
<Button type="submit" className="h-12 flex-1 rounded-2xl" disabled={loading || code.length !== 5}>
{loading ? (
<>
<Loader2 className="ml-2 h-4 w-4 animate-spin" />
در حال ثبت...
</>
) : (
<>
<ShieldCheck className="ml-2 h-4 w-4" />
ثبت رمز جدید
</>
)}
</Button>
<Button
type="button"
variant="outline"
className="h-12 rounded-2xl"
onClick={() => void handleSendOtp()}
disabled={loading || cooldown > 0}
>
{cooldown > 0 ? `ارسال مجدد تا ${cooldown} ثانیه` : "ارسال کد بازیابی"}
</Button>
</div>
<div className="text-right text-sm text-muted-foreground">
<Link to="/auth" className="underline underline-offset-4">
بازگشت به صفحه ورود
</Link>
</div>
</form>
</CardContent>
</Card>
</div>
</div>
);
}

View File

@@ -1,122 +1,77 @@
"use client";
import { useEffect } from "react";
import { useParams, Link } from "@/lib/router";
import { useQuery } from "@tanstack/react-query";
import { api } from "@/lib/api";
import {
Card,
CardHeader,
CardTitle,
CardContent,
CardFooter,
} from "@/components/ui/card";
import { Alert, AlertTitle, AlertDescription } from "@/components/ui/alert";
import { AlertTriangle, ArrowLeft, Loader2, MailWarning } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Loader2, CheckCircle2, Info, XCircle } from "lucide-react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { api } from "@/lib/api";
import { Link, useParams } from "@/lib/router";
import { resolveErrorMessage } from "@/lib/utils";
type State =
| { kind: "loading" }
| { kind: "success"; message: string }
| { kind: "already"; message: string }
| { kind: "error"; message: string };
export default function VerifyEmail() {
const { token } = useParams<{ token: string }>();
const query = useQuery({
queryKey: ["verify-email", token],
queryFn: async (): Promise<State> => {
if (!token) throw new Error("توکن تأیید یافت نشد.");
try {
const res = await api.verifyEmail(token);
return { kind: "success", message: "ایمیل شما با موفقیت تأیید شد." };
} catch (error: unknown) {
const msg: string = resolveErrorMessage(error, "").toLowerCase();
if (msg.includes("already verified")) {
return { kind: "already", message: "ایمیل شما قبلاً تأیید شده است." };
}
if (msg.includes("invalid verification token")) {
return { kind: "error", message: "توکن تأیید نامعتبر است." };
}
return {
kind: "error",
message: "متأسفانه خطایی رخ داد. لطفاً دوباره تلاش کنید.",
};
}
},
const { data, isLoading, isError, error } = useQuery({
queryKey: ["legacy-email-guidance", token],
queryFn: () => api.getLegacyVerifyEmailMessage(token || ""),
retry: false,
});
useEffect(() => {
document.title = "تأیید ایمیل";
}, []);
const renderBody = () => {
if (query.isLoading || query.data?.kind === "loading") {
return (
<div className="flex items-center gap-3 text-muted-foreground">
<Loader2 className="h-5 w-5 animate-spin" />
<span>در حال تأیید ایمیل...</span>
</div>
);
}
if (query.isError || query.data?.kind === "error") {
const message =
(query.data && "message" in query.data && query.data.message) ||
"خطای ناشناخته رخ داد";
return (
<Alert variant="destructive" dir="rtl" className="text-right">
<XCircle className="h-5 w-5" />
<AlertTitle>خطا</AlertTitle>
<AlertDescription>{message}</AlertDescription>
</Alert>
);
}
if (query.data?.kind === "already") {
return (
<Alert dir="rtl" className="text-right">
<Info className="h-5 w-5" />
<AlertTitle>توجه</AlertTitle>
<AlertDescription>{query.data.message}</AlertDescription>
</Alert>
);
}
// success
return (
<Alert dir="rtl" className="text-right">
<CheckCircle2 className="h-5 w-5" />
<AlertTitle>تبریک!</AlertTitle>
<AlertDescription>ایمیل شما با موفقیت تأیید شد.</AlertDescription>
</Alert>
);
};
const message = isError
? resolveErrorMessage(error, "تأیید ایمیل دیگر برای ورود و بازیابی حساب استفاده نمی‌شود.")
: data?.message ||
"تأیید ایمیل غیرفعال شده است. برای ادامه باید موبایل خود را تأیید کنید یا با همان حساب گوگل مرتبط وارد شوید.";
return (
<div className="min-h-[70vh] flex items-center justify-center bg-background p-4">
<Card className="w-full max-w-lg" dir="rtl">
<CardHeader className="text-right">
<CardTitle>تأیید ایمیل</CardTitle>
</CardHeader>
<CardContent className="space-y-6">{renderBody()}</CardContent>
<CardFooter className="flex items-center justify-between gap-3">
<Button asChild variant="secondary" className="min-w-32">
<Link to="/">رفتن به صفحهٔ اصلی</Link>
</Button>
<div className="flex items-center gap-2">
<Button asChild className="min-w-32">
<Link to="/auth">ورود به حساب</Link>
</Button>
<Button asChild variant="outline" className="min-w-32">
<Link to="/profile">پروفایل</Link>
</Button>
</div>
</CardFooter>
</Card>
<div className="min-h-screen bg-background px-4 py-10" dir="rtl">
<div className="mx-auto max-w-2xl">
<Card className="border-border/70 bg-background/90 shadow-xl">
<CardHeader className="text-right">
<div className="mb-4 inline-flex rounded-2xl border border-amber-400/30 bg-amber-500/10 p-3 text-amber-700 dark:text-amber-100">
<MailWarning className="h-5 w-5" />
</div>
<CardTitle>تأیید ایمیل کنار گذاشته شده است</CardTitle>
<CardDescription className="leading-7">
دسترسی کاربران به ایمیل محدود شده و مسیر تأیید حساب به موبایل و گوگل منتقل شده است.
</CardDescription>
</CardHeader>
<CardContent className="space-y-5 text-right">
<div className="rounded-[1.5rem] border border-border/70 bg-muted/25 p-4 text-sm leading-7 text-muted-foreground">
{isLoading ? (
<span className="flex items-center justify-end gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
در حال دریافت پیام راهنما...
</span>
) : (
message
)}
</div>
<div className="rounded-[1.5rem] border border-amber-400/30 bg-amber-500/10 p-4 text-sm leading-7 text-amber-900 dark:text-amber-100">
<div className="flex items-start justify-between gap-3">
<AlertTriangle className="mt-0.5 h-5 w-5 shrink-0" />
<div>
<p className="font-semibold">برای کاربران قدیمی</p>
<p className="mt-2">
اگر حساب شما قبلاً با ایمیل ساخته شده است، از صفحه ورود گزینه گوگل را بزنید تا در صورت تطابق ایمیل، حسابتان به موبایل متصل شود.
</p>
</div>
</div>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<Button asChild className="h-12 rounded-2xl">
<Link to="/auth">ورود و اتصال حساب</Link>
</Button>
<Button asChild variant="outline" className="h-12 rounded-2xl">
<Link to="/reset-password">
<ArrowLeft className="ml-2 h-4 w-4" />
بازیابی با موبایل
</Link>
</Button>
</div>
</CardContent>
</Card>
</div>
</div>
);
}