feat(frontend): rebuild auth around mobile-first flow
This commit is contained in:
11
src/app/auth/google/callback/page.tsx
Normal file
11
src/app/auth/google/callback/page.tsx
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
|
import GoogleAuthCallback from "@/views/GoogleAuthCallback";
|
||||||
|
|
||||||
|
export const metadata: Metadata = {
|
||||||
|
title: "ادامه ورود با گوگل",
|
||||||
|
robots: { index: false, follow: false },
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function GoogleAuthCallbackPage() {
|
||||||
|
return <GoogleAuthCallback />;
|
||||||
|
}
|
||||||
@@ -27,7 +27,7 @@ export default function MobileBottomNav() {
|
|||||||
const pathname = usePathname() || "/";
|
const pathname = usePathname() || "/";
|
||||||
const { isAuthenticated } = useAuth();
|
const { isAuthenticated } = useAuth();
|
||||||
|
|
||||||
if (pathname.startsWith("/admin") || pathname === "/logout") {
|
if (pathname.startsWith("/admin") || pathname === "/logout" || pathname.startsWith("/auth/google")) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
222
src/components/MobileVerificationGate.tsx
Normal file
222
src/components/MobileVerificationGate.tsx
Normal file
@@ -0,0 +1,222 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { Loader2, LogOut, ShieldCheck, Smartphone } from "lucide-react";
|
||||||
|
import { useAuth } from "@/contexts/AuthContext";
|
||||||
|
import { useToast } from "@/hooks/use-toast";
|
||||||
|
import { api } from "@/lib/api";
|
||||||
|
import OtpCodeField from "@/components/OtpCodeField";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { resolveErrorMessage } from "@/lib/utils";
|
||||||
|
|
||||||
|
const toEnglishDigits = (value: string) =>
|
||||||
|
value
|
||||||
|
.replace(/[\u06F0-\u06F9]/g, (digit) => String(digit.charCodeAt(0) - 0x06f0))
|
||||||
|
.replace(/[\u0660-\u0669]/g, (digit) => String(digit.charCodeAt(0) - 0x0660))
|
||||||
|
.replace(/[^\d]/g, "");
|
||||||
|
|
||||||
|
export default function MobileVerificationGate() {
|
||||||
|
const { user, isAuthenticated, loading, refreshProfile, setUser, logout } = useAuth();
|
||||||
|
const { toast } = useToast();
|
||||||
|
const [mobile, setMobile] = useState("");
|
||||||
|
const [code, setCode] = useState("");
|
||||||
|
const [step, setStep] = useState<"collect" | "verify">("collect");
|
||||||
|
const [sending, setSending] = useState(false);
|
||||||
|
const [verifying, setVerifying] = useState(false);
|
||||||
|
const [cooldown, setCooldown] = useState(0);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (user?.mobile) {
|
||||||
|
setMobile(user.mobile);
|
||||||
|
setStep("verify");
|
||||||
|
}
|
||||||
|
}, [user?.mobile]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (cooldown <= 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const timer = window.setTimeout(() => setCooldown((current) => current - 1), 1000);
|
||||||
|
return () => window.clearTimeout(timer);
|
||||||
|
}, [cooldown]);
|
||||||
|
|
||||||
|
const handleSendOtp = async () => {
|
||||||
|
try {
|
||||||
|
setSending(true);
|
||||||
|
const normalizedMobile = toEnglishDigits(mobile);
|
||||||
|
const response = await api.sendMobileVerificationOtp({ mobile: normalizedMobile });
|
||||||
|
setMobile(normalizedMobile);
|
||||||
|
setStep("verify");
|
||||||
|
setCooldown(Math.min(response.expires_in_seconds, 120));
|
||||||
|
toast({
|
||||||
|
title: "کد تأیید ارسال شد",
|
||||||
|
description: response.message,
|
||||||
|
variant: "success",
|
||||||
|
});
|
||||||
|
} catch (error: unknown) {
|
||||||
|
toast({
|
||||||
|
title: "خطا در ارسال کد",
|
||||||
|
description: resolveErrorMessage(error, "ارسال کد تأیید انجام نشد."),
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setSending(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleVerify = async () => {
|
||||||
|
try {
|
||||||
|
setVerifying(true);
|
||||||
|
const profile = await api.verifyMobile({
|
||||||
|
mobile: toEnglishDigits(mobile),
|
||||||
|
code: toEnglishDigits(code),
|
||||||
|
});
|
||||||
|
setUser(profile);
|
||||||
|
await refreshProfile();
|
||||||
|
toast({
|
||||||
|
title: "شماره موبایل تأیید شد",
|
||||||
|
description: "از این پس میتوانید با موبایل و کد پیامکی وارد شوید.",
|
||||||
|
variant: "success",
|
||||||
|
});
|
||||||
|
} catch (error: unknown) {
|
||||||
|
toast({
|
||||||
|
title: "کد نامعتبر است",
|
||||||
|
description: resolveErrorMessage(error, "تأیید شماره موبایل انجام نشد."),
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setVerifying(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading || !isAuthenticated || !user?.requires_mobile_verification) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-[80] flex items-center justify-center bg-slate-950/70 px-4 backdrop-blur-md" dir="rtl">
|
||||||
|
<div className="w-full max-w-lg rounded-[2rem] border border-white/10 bg-background/95 p-6 shadow-[0_30px_80px_rgba(15,23,42,0.35)]">
|
||||||
|
<div className="mb-6 flex items-start justify-between gap-4">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
className="rounded-2xl"
|
||||||
|
onClick={logout}
|
||||||
|
>
|
||||||
|
<LogOut className="ml-2 h-4 w-4" />
|
||||||
|
خروج
|
||||||
|
</Button>
|
||||||
|
<div className="text-right">
|
||||||
|
<div className="mb-3 inline-flex rounded-2xl border border-primary/20 bg-primary/10 p-3 text-primary">
|
||||||
|
<ShieldCheck className="h-5 w-5" />
|
||||||
|
</div>
|
||||||
|
<h2 className="text-xl font-semibold">تکمیل امنیت حساب با موبایل</h2>
|
||||||
|
<p className="mt-2 text-sm leading-6 text-muted-foreground">
|
||||||
|
برای ادامه استفاده از سایت باید شماره موبایل خود را ثبت و با کد پیامکی تأیید کنید.
|
||||||
|
ورودهای بعدی و بازیابی حساب شما از همین مسیر انجام میشود.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="rounded-[1.5rem] border border-border/70 bg-muted/20 p-4">
|
||||||
|
<div className="mb-4 flex items-center justify-end gap-3">
|
||||||
|
<div className="text-right">
|
||||||
|
<p className="font-medium">{user.first_name || user.last_name ? `${user.first_name} ${user.last_name}`.trim() : user.username}</p>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{user.email ? `ایمیل متصل: ${user.email}` : "ایمیل برای این حساب اختیاری است."}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-2xl border border-border/70 bg-background/80 p-3">
|
||||||
|
<Smartphone className="h-5 w-5 text-primary" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="required-mobile" className="mb-2 block text-right">
|
||||||
|
شماره موبایل
|
||||||
|
</Label>
|
||||||
|
<Input
|
||||||
|
id="required-mobile"
|
||||||
|
type="tel"
|
||||||
|
dir="ltr"
|
||||||
|
inputMode="numeric"
|
||||||
|
value={mobile}
|
||||||
|
onChange={(event) => setMobile(toEnglishDigits(event.target.value))}
|
||||||
|
placeholder="09xxxxxxxxx"
|
||||||
|
className="h-12 rounded-2xl"
|
||||||
|
disabled={sending || verifying}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{step === "verify" ? (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div>
|
||||||
|
<Label className="mb-3 block text-right">کد تأیید پیامکی</Label>
|
||||||
|
<OtpCodeField
|
||||||
|
value={code}
|
||||||
|
onChange={(value) => setCode(toEnglishDigits(value))}
|
||||||
|
disabled={verifying}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-3 sm:flex-row-reverse">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
className="flex-1 rounded-2xl"
|
||||||
|
onClick={() => void handleVerify()}
|
||||||
|
disabled={verifying || code.length !== 5}
|
||||||
|
>
|
||||||
|
{verifying ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="ml-2 h-4 w-4 animate-spin" />
|
||||||
|
در حال تأیید...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
"تأیید و ادامه"
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
className="rounded-2xl"
|
||||||
|
onClick={() => void handleSendOtp()}
|
||||||
|
disabled={sending || cooldown > 0}
|
||||||
|
>
|
||||||
|
{sending ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="ml-2 h-4 w-4 animate-spin" />
|
||||||
|
ارسال...
|
||||||
|
</>
|
||||||
|
) : cooldown > 0 ? (
|
||||||
|
`ارسال مجدد تا ${cooldown} ثانیه`
|
||||||
|
) : (
|
||||||
|
"ارسال مجدد کد"
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
className="w-full rounded-2xl"
|
||||||
|
onClick={() => void handleSendOtp()}
|
||||||
|
disabled={sending || mobile.length !== 11}
|
||||||
|
>
|
||||||
|
{sending ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="ml-2 h-4 w-4 animate-spin" />
|
||||||
|
در حال ارسال کد...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
"ارسال کد تأیید"
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import { useMemo } from "react";
|
|||||||
import { Link, NavLink } from "@/lib/router";
|
import { Link, NavLink } from "@/lib/router";
|
||||||
import { useAuth } from "@/contexts/AuthContext";
|
import { useAuth } from "@/contexts/AuthContext";
|
||||||
import ModeToggle from "@/components/ModeToggle";
|
import ModeToggle from "@/components/ModeToggle";
|
||||||
|
import NotificationsBell from "@/components/NotificationsBell";
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
@@ -70,6 +71,7 @@ export default function Navbar() {
|
|||||||
<NavItem to="/blog">بلاگ</NavItem>
|
<NavItem to="/blog">بلاگ</NavItem>
|
||||||
<NavItem to="/events">رویدادها</NavItem>
|
<NavItem to="/events">رویدادها</NavItem>
|
||||||
<ModeToggle />
|
<ModeToggle />
|
||||||
|
{isAuthenticated ? <NotificationsBell /> : null}
|
||||||
|
|
||||||
{isAuthenticated ? (
|
{isAuthenticated ? (
|
||||||
<Link
|
<Link
|
||||||
@@ -106,6 +108,7 @@ export default function Navbar() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-2 md:hidden">
|
<div className="flex items-center gap-2 md:hidden">
|
||||||
|
{isAuthenticated ? <NotificationsBell /> : null}
|
||||||
<ModeToggle />
|
<ModeToggle />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
177
src/components/NotificationsBell.tsx
Normal file
177
src/components/NotificationsBell.tsx
Normal file
@@ -0,0 +1,177 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Bell, CheckCheck, Loader2, Trash2 } from "lucide-react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||||
|
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||||
|
import { useNotifications } from "@/contexts/NotificationsContext";
|
||||||
|
import type { NotificationSchema } from "@/lib/types";
|
||||||
|
import { cn, formatJalali } from "@/lib/utils";
|
||||||
|
|
||||||
|
const connectionLabels = {
|
||||||
|
idle: "خاموش",
|
||||||
|
connecting: "در حال اتصال",
|
||||||
|
connected: "متصل",
|
||||||
|
disconnected: "قطع شده",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
function NotificationItem({
|
||||||
|
notification,
|
||||||
|
onOpen,
|
||||||
|
onDelete,
|
||||||
|
}: {
|
||||||
|
notification: NotificationSchema;
|
||||||
|
onOpen: (notification: NotificationSchema) => Promise<unknown>;
|
||||||
|
onDelete: (notification: NotificationSchema) => Promise<unknown>;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"rounded-2xl border border-border/70 bg-background/75 p-3 text-right transition hover:border-primary/30 hover:bg-muted/35",
|
||||||
|
!notification.is_seen && "border-primary/30 bg-primary/5",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className="flex items-start justify-between gap-3">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="icon"
|
||||||
|
variant="ghost"
|
||||||
|
className="h-8 w-8 shrink-0 rounded-full text-muted-foreground hover:text-destructive"
|
||||||
|
onClick={() => void onDelete(notification)}
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => void onOpen(notification)}
|
||||||
|
className="min-w-0 flex-1 space-y-1 text-right"
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-end gap-2">
|
||||||
|
{!notification.is_seen ? (
|
||||||
|
<span className="h-2.5 w-2.5 rounded-full bg-primary" />
|
||||||
|
) : null}
|
||||||
|
<p className="truncate font-semibold">{notification.title}</p>
|
||||||
|
</div>
|
||||||
|
<p className="line-clamp-2 text-sm text-muted-foreground">
|
||||||
|
{notification.message}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-muted-foreground/80">
|
||||||
|
{formatJalali(notification.created_at, false)}
|
||||||
|
</p>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function NotificationsBell() {
|
||||||
|
const {
|
||||||
|
notifications,
|
||||||
|
unreadCount,
|
||||||
|
totalCount,
|
||||||
|
hasMore,
|
||||||
|
isLoading,
|
||||||
|
isLoadingMore,
|
||||||
|
connectionStatus,
|
||||||
|
loadMore,
|
||||||
|
markAllAsSeen,
|
||||||
|
deleteNotification,
|
||||||
|
openNotification,
|
||||||
|
} = useNotifications();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Popover>
|
||||||
|
<PopoverTrigger asChild>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="icon"
|
||||||
|
className="relative h-10 w-10 rounded-full border-border/70 bg-background/85"
|
||||||
|
aria-label="اعلانها"
|
||||||
|
>
|
||||||
|
<Bell className="h-4 w-4" />
|
||||||
|
{unreadCount > 0 ? (
|
||||||
|
<span className="absolute -left-1 -top-1 flex min-w-5 items-center justify-center rounded-full bg-primary px-1.5 py-0.5 text-[10px] font-semibold text-primary-foreground">
|
||||||
|
{unreadCount > 9 ? "9+" : unreadCount}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</Button>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent className="w-[min(92vw,26rem)] rounded-[1.5rem] border border-border/70 bg-background/95 p-0 shadow-xl backdrop-blur-xl" align="end" sideOffset={12}>
|
||||||
|
<div className="border-b border-border/70 px-4 py-4 text-right">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Badge variant={connectionStatus === "connected" ? "default" : "secondary"}>
|
||||||
|
{connectionLabels[connectionStatus]}
|
||||||
|
</Badge>
|
||||||
|
{unreadCount > 0 ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="rounded-full"
|
||||||
|
onClick={() => void markAllAsSeen()}
|
||||||
|
>
|
||||||
|
<CheckCheck className="ml-2 h-4 w-4" />
|
||||||
|
خواندن همه
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold">اعلانها</p>
|
||||||
|
<p className="mt-1 text-xs text-muted-foreground">
|
||||||
|
{totalCount > 0 ? `${totalCount} مورد ثبت شده` : "هنوز اعلانی ندارید."}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ScrollArea className="max-h-[24rem] px-4 py-4">
|
||||||
|
<div className="space-y-3">
|
||||||
|
{isLoading ? (
|
||||||
|
<div className="flex items-center justify-center gap-2 py-10 text-sm text-muted-foreground">
|
||||||
|
<Loader2 className="h-4 w-4 animate-spin" />
|
||||||
|
در حال بارگذاری اعلانها...
|
||||||
|
</div>
|
||||||
|
) : notifications.length ? (
|
||||||
|
notifications.map((notification) => (
|
||||||
|
<NotificationItem
|
||||||
|
key={notification.id}
|
||||||
|
notification={notification}
|
||||||
|
onOpen={openNotification}
|
||||||
|
onDelete={deleteNotification}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<div className="rounded-2xl border border-dashed border-border/70 bg-muted/20 px-4 py-10 text-center text-sm text-muted-foreground">
|
||||||
|
اعلان تازهای برای شما ثبت نشده است.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</ScrollArea>
|
||||||
|
|
||||||
|
{hasMore ? (
|
||||||
|
<div className="border-t border-border/70 px-4 py-3">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="secondary"
|
||||||
|
className="w-full rounded-2xl"
|
||||||
|
onClick={() => void loadMore()}
|
||||||
|
disabled={isLoadingMore}
|
||||||
|
>
|
||||||
|
{isLoadingMore ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="ml-2 h-4 w-4 animate-spin" />
|
||||||
|
در حال بارگذاری...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
"نمایش موارد بیشتر"
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
);
|
||||||
|
}
|
||||||
42
src/components/OtpCodeField.tsx
Normal file
42
src/components/OtpCodeField.tsx
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/components/ui/input-otp";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
type OtpCodeFieldProps = {
|
||||||
|
value: string;
|
||||||
|
onChange: (value: string) => void;
|
||||||
|
disabled?: boolean;
|
||||||
|
length?: number;
|
||||||
|
className?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function OtpCodeField({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
disabled = false,
|
||||||
|
length = 5,
|
||||||
|
className,
|
||||||
|
}: OtpCodeFieldProps) {
|
||||||
|
return (
|
||||||
|
<InputOTP
|
||||||
|
dir="ltr"
|
||||||
|
maxLength={length}
|
||||||
|
value={value}
|
||||||
|
onChange={(nextValue) => onChange(nextValue.replace(/[^\d]/g, ""))}
|
||||||
|
disabled={disabled}
|
||||||
|
inputMode="numeric"
|
||||||
|
containerClassName={cn("w-full justify-center", className)}
|
||||||
|
>
|
||||||
|
<InputOTPGroup dir="ltr" className="justify-center">
|
||||||
|
{Array.from({ length }).map((_, index) => (
|
||||||
|
<InputOTPSlot
|
||||||
|
key={index}
|
||||||
|
index={index}
|
||||||
|
className="h-12 w-11 rounded-2xl border border-border/70 bg-background/80 text-base shadow-sm first:rounded-2xl first:border last:rounded-2xl"
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</InputOTPGroup>
|
||||||
|
</InputOTP>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -6,7 +6,9 @@ import { TooltipProvider } from "@/components/ui/tooltip";
|
|||||||
import { Toaster } from "@/components/ui/toaster";
|
import { Toaster } from "@/components/ui/toaster";
|
||||||
import { Toaster as Sonner } from "@/components/ui/sonner";
|
import { Toaster as Sonner } from "@/components/ui/sonner";
|
||||||
import { ThemeProvider } from "@/components/ThemeProvider";
|
import { ThemeProvider } from "@/components/ThemeProvider";
|
||||||
|
import MobileVerificationGate from "@/components/MobileVerificationGate";
|
||||||
import { AuthProvider } from "@/contexts/AuthContext";
|
import { AuthProvider } from "@/contexts/AuthContext";
|
||||||
|
import { NotificationsProvider } from "@/contexts/NotificationsContext";
|
||||||
|
|
||||||
export default function Providers({ children }: { children: React.ReactNode }) {
|
export default function Providers({ children }: { children: React.ReactNode }) {
|
||||||
const [queryClient] = React.useState(() => new QueryClient());
|
const [queryClient] = React.useState(() => new QueryClient());
|
||||||
@@ -20,11 +22,14 @@ export default function Providers({ children }: { children: React.ReactNode }) {
|
|||||||
>
|
>
|
||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
<AuthProvider>
|
<AuthProvider>
|
||||||
<TooltipProvider>
|
<NotificationsProvider>
|
||||||
<Toaster />
|
<TooltipProvider>
|
||||||
<Sonner />
|
<Toaster />
|
||||||
{children}
|
<Sonner />
|
||||||
</TooltipProvider>
|
{children}
|
||||||
|
<MobileVerificationGate />
|
||||||
|
</TooltipProvider>
|
||||||
|
</NotificationsProvider>
|
||||||
</AuthProvider>
|
</AuthProvider>
|
||||||
</QueryClientProvider>
|
</QueryClientProvider>
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
|
import { createContext, useContext, useEffect, useState, ReactNode, useCallback } from 'react';
|
||||||
import { api } from '@/lib/api';
|
import { api } from '@/lib/api';
|
||||||
import type { UserProfileSchema } from '@/lib/types';
|
import type { UserProfileSchema } from '@/lib/types';
|
||||||
|
|
||||||
@@ -7,47 +7,83 @@ type User = UserProfileSchema;
|
|||||||
interface AuthContextType {
|
interface AuthContextType {
|
||||||
user: User | null;
|
user: User | null;
|
||||||
loading: boolean;
|
loading: boolean;
|
||||||
login: (email: string, password: string) => Promise<void>;
|
login: (identifier: string, password: string) => Promise<void>;
|
||||||
|
loginWithOtp: (mobile: string, code: string) => Promise<void>;
|
||||||
|
setSessionTokens: (accessToken: string, refreshToken: string) => Promise<void>;
|
||||||
|
refreshProfile: () => Promise<User | null>;
|
||||||
|
setUser: (user: User | null) => void;
|
||||||
logout: () => void;
|
logout: () => void;
|
||||||
isAuthenticated: boolean;
|
isAuthenticated: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||||
|
|
||||||
|
const ACCESS_TOKEN_KEY = 'access_token';
|
||||||
|
const REFRESH_TOKEN_KEY = 'refresh_token';
|
||||||
|
|
||||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||||
const [user, setUser] = useState<User | null>(null);
|
const [user, setUser] = useState<User | null>(null);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
useEffect(() => {
|
const clearSession = useCallback(() => {
|
||||||
checkAuth();
|
localStorage.removeItem(ACCESS_TOKEN_KEY);
|
||||||
|
localStorage.removeItem(REFRESH_TOKEN_KEY);
|
||||||
|
setUser(null);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const checkAuth = async () => {
|
const refreshProfile = useCallback(async () => {
|
||||||
const token = localStorage.getItem('access_token');
|
const token = localStorage.getItem(ACCESS_TOKEN_KEY);
|
||||||
if (token) {
|
if (!token) {
|
||||||
try {
|
setUser(null);
|
||||||
const profile = await api.getProfile();
|
setLoading(false);
|
||||||
setUser(profile as User);
|
return null;
|
||||||
} catch (error) {
|
|
||||||
localStorage.removeItem('access_token');
|
|
||||||
localStorage.removeItem('refresh_token');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
setLoading(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
const login = async (email: string, password: string) => {
|
try {
|
||||||
const response = await api.login({ email, password });
|
const profile = await api.getProfile();
|
||||||
localStorage.setItem('access_token', response.access_token);
|
setUser(profile as User);
|
||||||
localStorage.setItem('refresh_token', response.refresh_token);
|
return profile as User;
|
||||||
await checkAuth();
|
} catch {
|
||||||
};
|
clearSession();
|
||||||
|
return null;
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [clearSession]);
|
||||||
|
|
||||||
const logout = () => {
|
useEffect(() => {
|
||||||
localStorage.removeItem('access_token');
|
void refreshProfile();
|
||||||
localStorage.removeItem('refresh_token');
|
}, [refreshProfile]);
|
||||||
setUser(null);
|
|
||||||
};
|
const setSessionTokens = useCallback(
|
||||||
|
async (accessToken: string, refreshToken: string) => {
|
||||||
|
localStorage.setItem(ACCESS_TOKEN_KEY, accessToken);
|
||||||
|
localStorage.setItem(REFRESH_TOKEN_KEY, refreshToken);
|
||||||
|
setLoading(true);
|
||||||
|
await refreshProfile();
|
||||||
|
},
|
||||||
|
[refreshProfile],
|
||||||
|
);
|
||||||
|
|
||||||
|
const login = useCallback(
|
||||||
|
async (identifier: string, password: string) => {
|
||||||
|
const response = await api.login({ identifier, password });
|
||||||
|
await setSessionTokens(response.access_token, response.refresh_token);
|
||||||
|
},
|
||||||
|
[setSessionTokens],
|
||||||
|
);
|
||||||
|
|
||||||
|
const loginWithOtp = useCallback(
|
||||||
|
async (mobile: string, code: string) => {
|
||||||
|
const response = await api.loginWithOtp({ mobile, code });
|
||||||
|
await setSessionTokens(response.access_token, response.refresh_token);
|
||||||
|
},
|
||||||
|
[setSessionTokens],
|
||||||
|
);
|
||||||
|
|
||||||
|
const logout = useCallback(() => {
|
||||||
|
clearSession();
|
||||||
|
}, [clearSession]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AuthContext.Provider
|
<AuthContext.Provider
|
||||||
@@ -55,6 +91,10 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
|||||||
user,
|
user,
|
||||||
loading,
|
loading,
|
||||||
login,
|
login,
|
||||||
|
loginWithOtp,
|
||||||
|
setSessionTokens,
|
||||||
|
refreshProfile,
|
||||||
|
setUser,
|
||||||
logout,
|
logout,
|
||||||
isAuthenticated: !!user,
|
isAuthenticated: !!user,
|
||||||
}}
|
}}
|
||||||
|
|||||||
388
src/contexts/NotificationsContext.tsx
Normal file
388
src/contexts/NotificationsContext.tsx
Normal file
@@ -0,0 +1,388 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import {
|
||||||
|
createContext,
|
||||||
|
useCallback,
|
||||||
|
useContext,
|
||||||
|
useEffect,
|
||||||
|
useMemo,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
} from "react";
|
||||||
|
import { toast } from "@/hooks/use-toast";
|
||||||
|
import { useAuth } from "@/contexts/AuthContext";
|
||||||
|
import { api } from "@/lib/api";
|
||||||
|
import type {
|
||||||
|
NotificationDeleteResponseSchema,
|
||||||
|
NotificationListSchema,
|
||||||
|
NotificationSchema,
|
||||||
|
NotificationSeenResponseSchema,
|
||||||
|
} from "@/lib/types";
|
||||||
|
|
||||||
|
type ConnectionStatus = "idle" | "connecting" | "connected" | "disconnected";
|
||||||
|
|
||||||
|
type NotificationsContextValue = {
|
||||||
|
notifications: NotificationSchema[];
|
||||||
|
unreadCount: number;
|
||||||
|
totalCount: number;
|
||||||
|
hasMore: boolean;
|
||||||
|
isLoading: boolean;
|
||||||
|
isLoadingMore: boolean;
|
||||||
|
connectionStatus: ConnectionStatus;
|
||||||
|
refreshNotifications: () => Promise<void>;
|
||||||
|
loadMore: () => Promise<void>;
|
||||||
|
markAsSeen: (notification: NotificationSchema) => Promise<NotificationSeenResponseSchema | null>;
|
||||||
|
deleteNotification: (notification: NotificationSchema) => Promise<NotificationDeleteResponseSchema | null>;
|
||||||
|
markAllAsSeen: () => Promise<void>;
|
||||||
|
openNotification: (notification: NotificationSchema) => Promise<void>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const NotificationsContext = createContext<NotificationsContextValue | undefined>(undefined);
|
||||||
|
const PAGE_SIZE = 12;
|
||||||
|
|
||||||
|
const mergeNotifications = (
|
||||||
|
current: NotificationSchema[],
|
||||||
|
incoming: NotificationSchema[],
|
||||||
|
) => {
|
||||||
|
const byId = new Map<string, NotificationSchema>();
|
||||||
|
for (const notification of current) {
|
||||||
|
byId.set(notification.id, notification);
|
||||||
|
}
|
||||||
|
for (const notification of incoming) {
|
||||||
|
const existing = byId.get(notification.id);
|
||||||
|
byId.set(notification.id, existing ? { ...existing, ...notification } : notification);
|
||||||
|
}
|
||||||
|
return Array.from(byId.values()).sort((left, right) => {
|
||||||
|
return new Date(right.created_at).getTime() - new Date(left.created_at).getTime();
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const openNotificationTarget = (notification: NotificationSchema) => {
|
||||||
|
if (typeof window === "undefined" || !notification.action_url) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const targetUrl = notification.action_url;
|
||||||
|
if (/^https?:\/\//i.test(targetUrl)) {
|
||||||
|
window.open(targetUrl, "_blank", "noopener,noreferrer");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
window.location.assign(targetUrl);
|
||||||
|
};
|
||||||
|
|
||||||
|
export function NotificationsProvider({ children }: { children: ReactNode }) {
|
||||||
|
const { isAuthenticated } = useAuth();
|
||||||
|
const [notifications, setNotifications] = useState<NotificationSchema[]>([]);
|
||||||
|
const [unreadCount, setUnreadCount] = useState(0);
|
||||||
|
const [totalCount, setTotalCount] = useState(0);
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [isLoadingMore, setIsLoadingMore] = useState(false);
|
||||||
|
const [connectionStatus, setConnectionStatus] = useState<ConnectionStatus>("idle");
|
||||||
|
const eventSourceRef = useRef<EventSource | null>(null);
|
||||||
|
const reconnectTimeoutRef = useRef<number | null>(null);
|
||||||
|
const reconnectAttemptRef = useRef(0);
|
||||||
|
const shownToastIdsRef = useRef<Set<string>>(new Set());
|
||||||
|
|
||||||
|
const hasMore = notifications.length < totalCount;
|
||||||
|
|
||||||
|
const cleanupStream = useCallback(() => {
|
||||||
|
if (reconnectTimeoutRef.current !== null) {
|
||||||
|
window.clearTimeout(reconnectTimeoutRef.current);
|
||||||
|
reconnectTimeoutRef.current = null;
|
||||||
|
}
|
||||||
|
eventSourceRef.current?.close();
|
||||||
|
eventSourceRef.current = null;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const applyNotificationList = useCallback((payload: NotificationListSchema) => {
|
||||||
|
setNotifications(payload.notifications);
|
||||||
|
setUnreadCount(payload.unread_count);
|
||||||
|
setTotalCount(payload.count);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const refreshNotifications = useCallback(async () => {
|
||||||
|
if (!isAuthenticated) {
|
||||||
|
setNotifications([]);
|
||||||
|
setUnreadCount(0);
|
||||||
|
setTotalCount(0);
|
||||||
|
setConnectionStatus("idle");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsLoading(true);
|
||||||
|
try {
|
||||||
|
const payload = await api.getNotifications({ limit: PAGE_SIZE, offset: 0 });
|
||||||
|
applyNotificationList(payload);
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
}, [applyNotificationList, isAuthenticated]);
|
||||||
|
|
||||||
|
const loadMore = useCallback(async () => {
|
||||||
|
if (!isAuthenticated || isLoadingMore || !hasMore) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsLoadingMore(true);
|
||||||
|
try {
|
||||||
|
const payload = await api.getNotifications({
|
||||||
|
limit: PAGE_SIZE,
|
||||||
|
offset: notifications.length,
|
||||||
|
});
|
||||||
|
setNotifications((current) => mergeNotifications(current, payload.notifications));
|
||||||
|
setUnreadCount(payload.unread_count);
|
||||||
|
setTotalCount(payload.count);
|
||||||
|
} finally {
|
||||||
|
setIsLoadingMore(false);
|
||||||
|
}
|
||||||
|
}, [hasMore, isAuthenticated, isLoadingMore, notifications.length]);
|
||||||
|
|
||||||
|
const markAsSeen = useCallback(async (notification: NotificationSchema) => {
|
||||||
|
if (notification.is_seen) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = await api.markNotificationSeen(notification.id);
|
||||||
|
if (payload.deleted) {
|
||||||
|
setNotifications((current) => current.filter((item) => item.id !== notification.id));
|
||||||
|
setTotalCount((current) => Math.max(current - 1, 0));
|
||||||
|
} else {
|
||||||
|
setNotifications((current) =>
|
||||||
|
current.map((item) =>
|
||||||
|
item.id === notification.id ? { ...item, is_seen: true } : item,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (typeof payload.unread_count === "number") {
|
||||||
|
setUnreadCount(payload.unread_count);
|
||||||
|
} else {
|
||||||
|
setUnreadCount((current) => Math.max(current - 1, 0));
|
||||||
|
}
|
||||||
|
return payload;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const deleteNotification = useCallback(async (notification: NotificationSchema) => {
|
||||||
|
const payload = await api.deleteNotification(notification.id);
|
||||||
|
setNotifications((current) => current.filter((item) => item.id !== notification.id));
|
||||||
|
setTotalCount((current) => Math.max(current - 1, 0));
|
||||||
|
if (typeof payload.unread_count === "number") {
|
||||||
|
setUnreadCount(payload.unread_count);
|
||||||
|
} else if (!notification.is_seen) {
|
||||||
|
setUnreadCount((current) => Math.max(current - 1, 0));
|
||||||
|
}
|
||||||
|
return payload;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const markAllAsSeen = useCallback(async () => {
|
||||||
|
if (!isAuthenticated) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await api.markAllNotificationsRead();
|
||||||
|
setUnreadCount(0);
|
||||||
|
setNotifications((current) =>
|
||||||
|
current.map((notification) => ({ ...notification, is_seen: true })),
|
||||||
|
);
|
||||||
|
}, [isAuthenticated]);
|
||||||
|
|
||||||
|
const openNotification = useCallback(async (notification: NotificationSchema) => {
|
||||||
|
await markAsSeen(notification);
|
||||||
|
openNotificationTarget(notification);
|
||||||
|
}, [markAsSeen]);
|
||||||
|
|
||||||
|
const announceIncomingNotification = useCallback((notification: NotificationSchema) => {
|
||||||
|
if (notification.is_seen || shownToastIdsRef.current.has(notification.id)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
shownToastIdsRef.current.add(notification.id);
|
||||||
|
toast({
|
||||||
|
title: notification.title,
|
||||||
|
description: notification.message,
|
||||||
|
variant:
|
||||||
|
notification.level === "error"
|
||||||
|
? "destructive"
|
||||||
|
: notification.level === "success"
|
||||||
|
? "success"
|
||||||
|
: "default",
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const connectToStream = useCallback(async () => {
|
||||||
|
if (!isAuthenticated) {
|
||||||
|
cleanupStream();
|
||||||
|
setConnectionStatus("idle");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanupStream();
|
||||||
|
setConnectionStatus("connecting");
|
||||||
|
try {
|
||||||
|
const tokenPayload = await api.issueNotificationStreamToken();
|
||||||
|
const stream = new EventSource(api.buildNotificationStreamUrl(tokenPayload.token));
|
||||||
|
eventSourceRef.current = stream;
|
||||||
|
|
||||||
|
stream.onopen = () => {
|
||||||
|
reconnectAttemptRef.current = 0;
|
||||||
|
setConnectionStatus("connected");
|
||||||
|
};
|
||||||
|
|
||||||
|
stream.addEventListener("connected", (event) => {
|
||||||
|
const payload = JSON.parse((event as MessageEvent<string>).data) as {
|
||||||
|
notifications?: NotificationSchema[];
|
||||||
|
unread_count?: number;
|
||||||
|
};
|
||||||
|
if (Array.isArray(payload.notifications)) {
|
||||||
|
setNotifications((current) => mergeNotifications(current, payload.notifications || []));
|
||||||
|
setTotalCount((current) => Math.max(current, payload.notifications?.length || 0));
|
||||||
|
}
|
||||||
|
if (typeof payload.unread_count === "number") {
|
||||||
|
setUnreadCount(payload.unread_count);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
stream.addEventListener("notification", (event) => {
|
||||||
|
const payload = JSON.parse((event as MessageEvent<string>).data) as {
|
||||||
|
notification?: NotificationSchema;
|
||||||
|
unread_count?: number;
|
||||||
|
};
|
||||||
|
const incomingNotification = payload.notification;
|
||||||
|
if (!incomingNotification) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setNotifications((current) => {
|
||||||
|
const exists = current.some((item) => item.id === incomingNotification.id);
|
||||||
|
if (!exists) {
|
||||||
|
setTotalCount((count) => count + 1);
|
||||||
|
}
|
||||||
|
return mergeNotifications(current, [incomingNotification]);
|
||||||
|
});
|
||||||
|
if (typeof payload.unread_count === "number") {
|
||||||
|
setUnreadCount(payload.unread_count);
|
||||||
|
}
|
||||||
|
announceIncomingNotification(incomingNotification);
|
||||||
|
});
|
||||||
|
|
||||||
|
stream.addEventListener("notification_seen", (event) => {
|
||||||
|
const payload = JSON.parse((event as MessageEvent<string>).data) as {
|
||||||
|
notification_id?: string;
|
||||||
|
notification?: NotificationSchema | null;
|
||||||
|
deleted?: boolean;
|
||||||
|
unread_count?: number;
|
||||||
|
};
|
||||||
|
if (payload.deleted && payload.notification_id) {
|
||||||
|
setNotifications((current) =>
|
||||||
|
current.filter((item) => item.id !== payload.notification_id),
|
||||||
|
);
|
||||||
|
setTotalCount((current) => Math.max(current - 1, 0));
|
||||||
|
} else if (payload.notification) {
|
||||||
|
setNotifications((current) => mergeNotifications(current, [payload.notification!]));
|
||||||
|
} else if (payload.notification_id) {
|
||||||
|
setNotifications((current) =>
|
||||||
|
current.map((item) =>
|
||||||
|
item.id === payload.notification_id ? { ...item, is_seen: true } : item,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (typeof payload.unread_count === "number") {
|
||||||
|
setUnreadCount(payload.unread_count);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
stream.addEventListener("notification_mark_all_read", (event) => {
|
||||||
|
const payload = JSON.parse((event as MessageEvent<string>).data) as {
|
||||||
|
unread_count?: number;
|
||||||
|
};
|
||||||
|
setNotifications((current) =>
|
||||||
|
current.map((notification) => ({ ...notification, is_seen: true })),
|
||||||
|
);
|
||||||
|
if (typeof payload.unread_count === "number") {
|
||||||
|
setUnreadCount(payload.unread_count);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
stream.addEventListener("unread_count", (event) => {
|
||||||
|
const payload = JSON.parse((event as MessageEvent<string>).data) as {
|
||||||
|
unread_count?: number;
|
||||||
|
};
|
||||||
|
if (typeof payload.unread_count === "number") {
|
||||||
|
setUnreadCount(payload.unread_count);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
stream.onerror = () => {
|
||||||
|
stream.close();
|
||||||
|
eventSourceRef.current = null;
|
||||||
|
setConnectionStatus("disconnected");
|
||||||
|
reconnectAttemptRef.current += 1;
|
||||||
|
const delay = Math.min(1000 * 2 ** reconnectAttemptRef.current, 30000);
|
||||||
|
reconnectTimeoutRef.current = window.setTimeout(() => {
|
||||||
|
void connectToStream();
|
||||||
|
}, delay);
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
setConnectionStatus("disconnected");
|
||||||
|
}
|
||||||
|
}, [announceIncomingNotification, cleanupStream, isAuthenticated]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isAuthenticated) {
|
||||||
|
cleanupStream();
|
||||||
|
setNotifications([]);
|
||||||
|
setUnreadCount(0);
|
||||||
|
setTotalCount(0);
|
||||||
|
setConnectionStatus("idle");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
void refreshNotifications();
|
||||||
|
void connectToStream();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cleanupStream();
|
||||||
|
};
|
||||||
|
}, [cleanupStream, connectToStream, isAuthenticated, refreshNotifications]);
|
||||||
|
|
||||||
|
const value = useMemo<NotificationsContextValue>(() => ({
|
||||||
|
notifications,
|
||||||
|
unreadCount,
|
||||||
|
totalCount,
|
||||||
|
hasMore,
|
||||||
|
isLoading,
|
||||||
|
isLoadingMore,
|
||||||
|
connectionStatus,
|
||||||
|
refreshNotifications,
|
||||||
|
loadMore,
|
||||||
|
markAsSeen,
|
||||||
|
deleteNotification,
|
||||||
|
markAllAsSeen,
|
||||||
|
openNotification,
|
||||||
|
}), [
|
||||||
|
connectionStatus,
|
||||||
|
deleteNotification,
|
||||||
|
hasMore,
|
||||||
|
isLoading,
|
||||||
|
isLoadingMore,
|
||||||
|
loadMore,
|
||||||
|
markAllAsSeen,
|
||||||
|
markAsSeen,
|
||||||
|
notifications,
|
||||||
|
openNotification,
|
||||||
|
refreshNotifications,
|
||||||
|
totalCount,
|
||||||
|
unreadCount,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<NotificationsContext.Provider value={value}>
|
||||||
|
{children}
|
||||||
|
</NotificationsContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useNotifications() {
|
||||||
|
const context = useContext(NotificationsContext);
|
||||||
|
if (!context) {
|
||||||
|
throw new Error("useNotifications must be used within a NotificationsProvider");
|
||||||
|
}
|
||||||
|
return context;
|
||||||
|
}
|
||||||
133
src/lib/api.ts
133
src/lib/api.ts
@@ -179,6 +179,27 @@ class ApiClient {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async loginWithOtp(data: Types.UserOtpLoginSchema) {
|
||||||
|
return this.request<Types.TokenSchema>('/api/auth/login/otp', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendOtp(data: Types.OtpSendSchema) {
|
||||||
|
return this.request<Types.OtpSendResponseSchema>('/api/auth/otp/send', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async verifyRegisterOtp(data: Types.RegisterOtpVerifySchema) {
|
||||||
|
return this.request<Types.MessageSchema>('/api/auth/otp/verify-register', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
async refreshToken(data: Types.TokenRefreshIn) {
|
async refreshToken(data: Types.TokenRefreshIn) {
|
||||||
return this.request<Types.TokenSchema>('/api/auth/refresh', {
|
return this.request<Types.TokenSchema>('/api/auth/refresh', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@@ -186,6 +207,60 @@ class ApiClient {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async resetPassword(data: Types.PasswordResetSchema) {
|
||||||
|
return this.request<Types.MessageSchema>('/api/auth/reset-password', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendMobileVerificationOtp(data: Types.MobileOtpSendSchema) {
|
||||||
|
return this.request<Types.OtpSendResponseSchema>('/api/auth/mobile/send-otp', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async verifyMobile(data: Types.MobileOtpVerifySchema) {
|
||||||
|
return this.request<Types.UserProfileSchema>('/api/auth/mobile/verify', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async startGoogleLogin() {
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
window.location.href = `${this.baseUrl}/api/auth/oauth/google/start`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async getGoogleFlow(flow: string) {
|
||||||
|
return this.request<Types.GoogleFlowResponseSchema>(
|
||||||
|
`/api/auth/oauth/google/flow?flow=${encodeURIComponent(flow)}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async completeGoogleSignup(data: Types.GoogleCompleteSchema) {
|
||||||
|
return this.request<Types.GoogleFlowResponseSchema>('/api/auth/oauth/google/complete', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async resendGoogleClaimOtp(flow: string) {
|
||||||
|
return this.request<Types.MessageSchema>('/api/auth/oauth/google/claim/send-otp', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ flow }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async verifyGoogleClaim(flow: string, code: string) {
|
||||||
|
return this.request<Types.GoogleFlowResponseSchema>('/api/auth/oauth/google/claim/verify', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ flow, code }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
async verifyEmail(token: string): Promise<Types.MessageSchema> {
|
async verifyEmail(token: string): Promise<Types.MessageSchema> {
|
||||||
const url = `${this.baseUrl}/api/auth/verify-email/${encodeURIComponent(token)}`;
|
const url = `${this.baseUrl}/api/auth/verify-email/${encodeURIComponent(token)}`;
|
||||||
const response = await fetch(url, { method: 'GET' });
|
const response = await fetch(url, { method: 'GET' });
|
||||||
@@ -265,6 +340,17 @@ class ApiClient {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getLegacyVerifyEmailMessage(token: string) {
|
||||||
|
return this.request<Types.MessageSchema>(`/api/auth/verify-email/${encodeURIComponent(token)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getLegacyResetTokenMessage(token: string) {
|
||||||
|
return this.request<Types.MessageSchema>('/api/auth/reset-password-confirm', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ token }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
async checkUsername(username: string) {
|
async checkUsername(username: string) {
|
||||||
return this.request<Types.UsernameCheckSchema>(
|
return this.request<Types.UsernameCheckSchema>(
|
||||||
@@ -272,6 +358,12 @@ class ApiClient {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async checkMobile(mobile: string) {
|
||||||
|
return this.request<Types.MobileLookupSchema>(
|
||||||
|
`/api/auth/check-mobile?mobile=${encodeURIComponent(mobile)}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Admin auth endpoints
|
// Admin auth endpoints
|
||||||
async listDeletedUsers() {
|
async listDeletedUsers() {
|
||||||
return this.request<Types.UserProfileSchema[]>('/api/auth/users/deleted');
|
return this.request<Types.UserProfileSchema[]>('/api/auth/users/deleted');
|
||||||
@@ -681,6 +773,47 @@ class ApiClient {
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getNotifications(params?: { limit?: number; offset?: number; type?: string }) {
|
||||||
|
const query = new URLSearchParams();
|
||||||
|
if (params?.limit != null) query.set('limit', String(params.limit));
|
||||||
|
if (params?.offset != null) query.set('offset', String(params.offset));
|
||||||
|
if (params?.type) query.set('type', params.type);
|
||||||
|
return this.request<Types.NotificationListSchema>(
|
||||||
|
`/api/notifications/${query.toString() ? `?${query.toString()}` : ''}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async markNotificationSeen(id: string) {
|
||||||
|
return this.request<Types.NotificationSeenResponseSchema>('/api/notifications/mark-seen', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ id }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteNotification(id: string) {
|
||||||
|
return this.request<Types.NotificationDeleteResponseSchema>(`/api/notifications/${encodeURIComponent(id)}`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async markAllNotificationsRead(type?: string) {
|
||||||
|
const query = type ? `?type=${encodeURIComponent(type)}` : '';
|
||||||
|
return this.request<{ marked_read: number }>(`/api/notifications/mark-all-read${query}`, {
|
||||||
|
method: 'POST',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async issueNotificationStreamToken() {
|
||||||
|
return this.request<Types.NotificationStreamTokenResponseSchema>('/api/notifications/stream-token', {
|
||||||
|
method: 'POST',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
buildNotificationStreamUrl(token: string) {
|
||||||
|
const cleanBaseUrl = this.baseUrl.replace(/\/+$/, '');
|
||||||
|
return `${cleanBaseUrl}/api/notifications/stream/?token=${encodeURIComponent(token)}`;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const api = new ApiClient(API_BASE_URL);
|
export const api = new ApiClient(API_BASE_URL);
|
||||||
|
|||||||
129
src/lib/types.ts
129
src/lib/types.ts
@@ -12,6 +12,7 @@ export interface ErrorSchema {
|
|||||||
export interface TokenSchema {
|
export interface TokenSchema {
|
||||||
access_token: string;
|
access_token: string;
|
||||||
refresh_token: string;
|
refresh_token: string;
|
||||||
|
token_type?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MajorOption {
|
export interface MajorOption {
|
||||||
@@ -21,7 +22,8 @@ export interface MajorOption {
|
|||||||
|
|
||||||
export interface UserProfileSchema {
|
export interface UserProfileSchema {
|
||||||
id: number;
|
id: number;
|
||||||
email: string;
|
email?: string | null;
|
||||||
|
mobile?: string | null;
|
||||||
username: string;
|
username: string;
|
||||||
first_name: string;
|
first_name: string;
|
||||||
last_name: string;
|
last_name: string;
|
||||||
@@ -36,6 +38,9 @@ export interface UserProfileSchema {
|
|||||||
date_joined: string;
|
date_joined: string;
|
||||||
|
|
||||||
is_email_verified?: boolean;
|
is_email_verified?: boolean;
|
||||||
|
is_mobile_verified?: boolean;
|
||||||
|
requires_mobile_verification?: boolean;
|
||||||
|
has_google_link?: boolean;
|
||||||
is_active?: boolean;
|
is_active?: boolean;
|
||||||
is_staff?: boolean;
|
is_staff?: boolean;
|
||||||
is_superuser?: boolean;
|
is_superuser?: boolean;
|
||||||
@@ -47,7 +52,8 @@ export interface UserProfileSchema {
|
|||||||
export interface UserListSchema {
|
export interface UserListSchema {
|
||||||
id: number;
|
id: number;
|
||||||
username: string;
|
username: string;
|
||||||
email: string;
|
email?: string | null;
|
||||||
|
mobile?: string | null;
|
||||||
first_name: string;
|
first_name: string;
|
||||||
last_name: string;
|
last_name: string;
|
||||||
full_name?: string | null;
|
full_name?: string | null;
|
||||||
@@ -60,11 +66,13 @@ export interface UserListSchema {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface UserRegistrationSchema {
|
export interface UserRegistrationSchema {
|
||||||
email: string;
|
mobile: string;
|
||||||
|
code: string;
|
||||||
password: string;
|
password: string;
|
||||||
username: string;
|
username: string;
|
||||||
first_name: string;
|
email?: string | null;
|
||||||
last_name: string;
|
first_name?: string | null;
|
||||||
|
last_name?: string | null;
|
||||||
student_id?: string | null;
|
student_id?: string | null;
|
||||||
year_of_study?: number | null;
|
year_of_study?: number | null;
|
||||||
major?: string | null;
|
major?: string | null;
|
||||||
@@ -72,6 +80,7 @@ export interface UserRegistrationSchema {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type UserUpdateSchema = {
|
export type UserUpdateSchema = {
|
||||||
|
email?: string | null;
|
||||||
first_name?: string | null;
|
first_name?: string | null;
|
||||||
last_name?: string | null;
|
last_name?: string | null;
|
||||||
bio?: string | null;
|
bio?: string | null;
|
||||||
@@ -83,25 +92,123 @@ export type UserUpdateSchema = {
|
|||||||
|
|
||||||
|
|
||||||
export interface UserLoginSchema {
|
export interface UserLoginSchema {
|
||||||
email: string;
|
identifier: string;
|
||||||
password: string;
|
password: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface UserOtpLoginSchema {
|
||||||
|
mobile: string;
|
||||||
|
code: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RegisterOtpVerifySchema {
|
||||||
|
mobile: string;
|
||||||
|
code: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OtpSendSchema {
|
||||||
|
mobile: string;
|
||||||
|
mode: "register" | "login" | "reset_password" | "verify_mobile" | "google_claim";
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OtpSendResponseSchema {
|
||||||
|
message: string;
|
||||||
|
expires_in_seconds: number;
|
||||||
|
expires_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface TokenRefreshIn {
|
export interface TokenRefreshIn {
|
||||||
refresh_token: string;
|
refresh_token: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UsernameCheckSchema {
|
export interface UsernameCheckSchema {
|
||||||
available: boolean;
|
exists: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PasswordResetRequestSchema {
|
export interface MobileLookupSchema {
|
||||||
email: string;
|
exists: boolean;
|
||||||
|
has_password: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PasswordResetConfirmSchema {
|
export interface PasswordResetSchema {
|
||||||
|
mobile: string;
|
||||||
|
code: string;
|
||||||
|
new_password: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MobileOtpSendSchema {
|
||||||
|
mobile: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MobileOtpVerifySchema {
|
||||||
|
mobile: string;
|
||||||
|
code: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GoogleFlowResponseSchema {
|
||||||
|
status: "authenticated" | "collect_profile" | "claim_required" | "error";
|
||||||
|
email?: string | null;
|
||||||
|
first_name?: string | null;
|
||||||
|
last_name?: string | null;
|
||||||
|
avatar_url?: string | null;
|
||||||
|
resolution?: "new_account" | "existing_email_claim" | "existing_mobile_claim" | null;
|
||||||
|
mobile?: string | null;
|
||||||
|
mobile_hint?: string | null;
|
||||||
|
detail?: string | null;
|
||||||
|
access_token?: string | null;
|
||||||
|
refresh_token?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GoogleCompleteSchema {
|
||||||
|
flow: string;
|
||||||
|
mobile: string;
|
||||||
|
username?: string | null;
|
||||||
|
student_id?: string | null;
|
||||||
|
year_of_study?: number | null;
|
||||||
|
major?: string | null;
|
||||||
|
university?: string | null;
|
||||||
|
first_name?: string | null;
|
||||||
|
last_name?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NotificationSchema {
|
||||||
|
id: string;
|
||||||
|
type: string;
|
||||||
|
title: string;
|
||||||
|
message: string;
|
||||||
|
level: "info" | "success" | "warning" | "error";
|
||||||
|
created_at: string;
|
||||||
|
is_seen: boolean;
|
||||||
|
delete_on_seen: boolean;
|
||||||
|
action_url?: string | null;
|
||||||
|
entity_type?: string | null;
|
||||||
|
entity_id?: string | number | null;
|
||||||
|
meta?: Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NotificationListSchema {
|
||||||
|
count: number;
|
||||||
|
unread_count: number;
|
||||||
|
notifications: NotificationSchema[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NotificationSeenResponseSchema {
|
||||||
|
marked_read: boolean;
|
||||||
|
notification_id?: string | null;
|
||||||
|
deleted?: boolean;
|
||||||
|
notification?: NotificationSchema | null;
|
||||||
|
unread_count?: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NotificationDeleteResponseSchema {
|
||||||
|
deleted: boolean;
|
||||||
|
notification_id?: string | null;
|
||||||
|
unread_count?: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NotificationStreamTokenResponseSchema {
|
||||||
token: string;
|
token: string;
|
||||||
password: string;
|
expires_in: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Blog Types
|
// Blog Types
|
||||||
|
|||||||
1211
src/views/Auth.tsx
1211
src/views/Auth.tsx
File diff suppressed because it is too large
Load Diff
471
src/views/GoogleAuthCallback.tsx
Normal file
471
src/views/GoogleAuthCallback.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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-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-1 flex-col items-start gap-5 text-right lg:items-end">
|
||||||
<div className="flex flex-wrap items-center gap-2 lg:justify-end">
|
<div className="flex flex-wrap items-center gap-2 lg:justify-end">
|
||||||
<Badge variant={me?.is_email_verified ? "default" : "secondary"}>
|
<Badge variant={me?.is_mobile_verified ? "default" : "secondary"}>
|
||||||
{me?.is_email_verified ? "ایمیل تأیید شده" : "در انتظار تأیید ایمیل"}
|
{me?.is_mobile_verified ? "موبایل تأیید شده" : "نیازمند تأیید موبایل"}
|
||||||
</Badge>
|
</Badge>
|
||||||
{isAdminUser ? <Badge variant="outline">دسترسی مدیریتی</Badge> : null}
|
{isAdminUser ? <Badge variant="outline">دسترسی مدیریتی</Badge> : null}
|
||||||
<Badge variant="secondary">
|
<Badge variant="secondary">
|
||||||
@@ -786,6 +786,7 @@ export default function Profile() {
|
|||||||
<CardTitle className="text-base">وضعیت حساب</CardTitle>
|
<CardTitle className="text-base">وضعیت حساب</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-1">
|
<CardContent className="space-y-1">
|
||||||
|
<InfoRow label="موبایل" value={me?.mobile || "—"} />
|
||||||
<InfoRow label="ایمیل" value={me?.email || "—"} />
|
<InfoRow label="ایمیل" value={me?.email || "—"} />
|
||||||
<InfoRow label="نام کاربری" value={me?.username || "—"} />
|
<InfoRow label="نام کاربری" value={me?.username || "—"} />
|
||||||
<InfoRow
|
<InfoRow
|
||||||
@@ -793,18 +794,22 @@ export default function Profile() {
|
|||||||
value={me?.date_joined ? formatJalali(me.date_joined, false) : "—"}
|
value={me?.date_joined ? formatJalali(me.date_joined, false) : "—"}
|
||||||
/>
|
/>
|
||||||
<InfoRow
|
<InfoRow
|
||||||
label="تأیید ایمیل"
|
label="تأیید موبایل"
|
||||||
value={
|
value={
|
||||||
<span className="inline-flex items-center gap-2">
|
<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" />
|
<BadgeCheck className="h-4 w-4 text-emerald-600" />
|
||||||
) : (
|
) : (
|
||||||
<Clock3 className="h-4 w-4 text-amber-600" />
|
<Clock3 className="h-4 w-4 text-amber-600" />
|
||||||
)}
|
)}
|
||||||
{me?.is_email_verified ? "تأیید شده" : "در انتظار"}
|
{me?.is_mobile_verified ? "تأیید شده" : "در انتظار"}
|
||||||
</span>
|
</span>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
<InfoRow
|
||||||
|
label="اتصال گوگل"
|
||||||
|
value={me?.has_google_link ? "متصل" : "متصل نیست"}
|
||||||
|
/>
|
||||||
<InfoRow
|
<InfoRow
|
||||||
label="سطح دسترسی"
|
label="سطح دسترسی"
|
||||||
value={isAdminUser ? "مدیریتی" : "کاربر عادی"}
|
value={isAdminUser ? "مدیریتی" : "کاربر عادی"}
|
||||||
@@ -829,7 +834,7 @@ export default function Profile() {
|
|||||||
|
|
||||||
<Button variant="secondary" className="justify-between rounded-2xl py-6" asChild>
|
<Button variant="secondary" className="justify-between rounded-2xl py-6" asChild>
|
||||||
<Link to="/reset-password">
|
<Link to="/reset-password">
|
||||||
<span>درخواست تغییر رمز عبور</span>
|
<span>بازیابی یا تغییر رمز با موبایل</span>
|
||||||
<Mail className="h-4 w-4" />
|
<Mail className="h-4 w-4" />
|
||||||
</Link>
|
</Link>
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -1,77 +1,77 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from 'react';
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { useParams, useNavigate } from '@/lib/router';
|
import { AlertTriangle, ArrowLeft, Loader2, ShieldAlert } from "lucide-react";
|
||||||
import { useToast } from '@/hooks/use-toast';
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { api } from '@/lib/api';
|
import { Button } from "@/components/ui/button";
|
||||||
import { resolveErrorMessage } from '@/lib/utils';
|
import { api } from "@/lib/api";
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Link, useParams } from "@/lib/router";
|
||||||
import { Label } from '@/components/ui/label';
|
import { resolveErrorMessage } from "@/lib/utils";
|
||||||
import { Input } from '@/components/ui/input';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
|
|
||||||
export default function ResetPasswordConfirm() {
|
export default function ResetPasswordConfirm() {
|
||||||
const { token } = useParams<{ token: string }>();
|
const { token } = useParams<{ token: string }>();
|
||||||
const navigate = useNavigate();
|
const { data, isLoading, isError, error } = useQuery({
|
||||||
const { toast } = useToast();
|
queryKey: ["legacy-reset-guidance", token],
|
||||||
const [password, setPassword] = useState('');
|
queryFn: () => api.getLegacyResetTokenMessage(token || ""),
|
||||||
const [confirm, setConfirm] = useState('');
|
retry: false,
|
||||||
const [loading, setLoading] = useState(false);
|
});
|
||||||
|
|
||||||
const onSubmit = async (e: React.FormEvent) => {
|
const message = isError
|
||||||
e.preventDefault();
|
? resolveErrorMessage(error, "این مسیر دیگر برای بازیابی رمز عبور فعال نیست.")
|
||||||
if (!token) {
|
: data?.message ||
|
||||||
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);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-background flex items-center justify-center p-4">
|
<div className="min-h-screen bg-background px-4 py-10" dir="rtl">
|
||||||
<Card className="w-full max-w-md" dir="rtl">
|
<div className="mx-auto max-w-2xl">
|
||||||
<CardHeader>
|
<Card className="border-border/70 bg-background/90 shadow-xl">
|
||||||
<CardTitle>تعیین رمز جدید</CardTitle>
|
<CardHeader className="text-right">
|
||||||
<CardDescription>رمز عبور جدید را وارد کنید</CardDescription>
|
<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">
|
||||||
</CardHeader>
|
<ShieldAlert className="h-5 w-5" />
|
||||||
<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>
|
</div>
|
||||||
<div>
|
<CardTitle>لینک بازیابی قدیمی غیرفعال شده است</CardTitle>
|
||||||
<Label htmlFor="confirm">تکرار رمز</Label>
|
<CardDescription className="leading-7">
|
||||||
<Input id="confirm" type="password" required value={confirm} onChange={(e) => setConfirm(e.target.value)} />
|
مسیرهای مبتنی بر ایمیل دیگر برای بازیابی حساب استفاده نمیشوند.
|
||||||
|
</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>
|
||||||
<Button type="submit" className="w-full" disabled={loading}>
|
|
||||||
{loading ? 'در حال ثبت...' : 'ثبت رمز جدید'}
|
<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">
|
||||||
</Button>
|
<div className="flex items-start justify-between gap-3">
|
||||||
</form>
|
<AlertTriangle className="mt-0.5 h-5 w-5 shrink-0" />
|
||||||
</CardContent>
|
<div>
|
||||||
</Card>
|
<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>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,35 +1,103 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from 'react';
|
import { useEffect, useState } from "react";
|
||||||
import { useToast } from '@/hooks/use-toast';
|
import { AlertTriangle, Loader2, ShieldCheck } from "lucide-react";
|
||||||
import { api } from '@/lib/api';
|
import OtpCodeField from "@/components/OtpCodeField";
|
||||||
import { resolveErrorMessage } from '@/lib/utils';
|
import { Button } from "@/components/ui/button";
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { Label } from '@/components/ui/label';
|
import { Input } from "@/components/ui/input";
|
||||||
import { Input } from '@/components/ui/input';
|
import { Label } from "@/components/ui/label";
|
||||||
import { Button } from '@/components/ui/button';
|
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() {
|
export default function ResetPasswordRequest() {
|
||||||
const { toast } = useToast();
|
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 [loading, setLoading] = useState(false);
|
||||||
|
const [cooldown, setCooldown] = useState(0);
|
||||||
|
|
||||||
const onSubmit = async (e: React.FormEvent) => {
|
useEffect(() => {
|
||||||
e.preventDefault();
|
if (cooldown <= 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const timer = window.setTimeout(() => setCooldown((current) => current - 1), 1000);
|
||||||
|
return () => window.clearTimeout(timer);
|
||||||
|
}, [cooldown]);
|
||||||
|
|
||||||
|
const handleSendOtp = async () => {
|
||||||
try {
|
try {
|
||||||
setLoading(true);
|
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({
|
toast({
|
||||||
title: 'اگر ایمیلی ثبت شده باشد، لینک بازیابی ارسال شد',
|
title: "کد بازیابی ارسال شد",
|
||||||
description: 'ایمیل خود را بررسی کنید.',
|
description: response.message,
|
||||||
variant: 'success'
|
variant: "success",
|
||||||
});
|
});
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
// بکاند 200 میدهد حتی اگر ایمیل نباشد؛ اما اگر اروری بیاید، نشان بده
|
|
||||||
toast({
|
toast({
|
||||||
title: 'خطا',
|
title: "ارسال کد انجام نشد",
|
||||||
description: resolveErrorMessage(error, 'مشکلی رخ داد'),
|
description: resolveErrorMessage(error, "امکان ارسال پیامک بازیابی وجود ندارد."),
|
||||||
variant: 'destructive',
|
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 {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
@@ -37,24 +105,131 @@ export default function ResetPasswordRequest() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-background flex items-center justify-center p-4">
|
<div className="min-h-screen bg-background px-4 py-10" dir="rtl">
|
||||||
<Card className="w-full max-w-md" dir="rtl">
|
<div className="mx-auto flex w-full max-w-4xl flex-col gap-6 lg:flex-row">
|
||||||
<CardHeader>
|
<Card className="border-border/70 bg-background/85 shadow-xl backdrop-blur-xl lg:w-[22rem]">
|
||||||
<CardTitle>بازیابی رمز عبور</CardTitle>
|
<CardHeader className="text-right">
|
||||||
<CardDescription>ایمیلتان را وارد کنید تا لینک بازیابی برای شما ارسال شود</CardDescription>
|
<CardTitle>بازیابی حساب بدون ایمیل</CardTitle>
|
||||||
</CardHeader>
|
<CardDescription className="leading-7">
|
||||||
<CardContent>
|
بازیابی رمز عبور اکنون با موبایل و کد پیامکی انجام میشود. اگر به موبایل ثبتشده هم دسترسی ندارید، از همان حساب گوگلی که قبلاً با ایمیلتان استفاده میکردید کمک بگیرید.
|
||||||
<form onSubmit={onSubmit} className="space-y-4">
|
</CardDescription>
|
||||||
<div>
|
</CardHeader>
|
||||||
<Label htmlFor="email">ایمیل</Label>
|
<CardContent className="space-y-4 text-right">
|
||||||
<Input id="email" type="email" required value={email} onChange={(e) => setEmail(e.target.value)} />
|
<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>
|
||||||
<Button type="submit" className="w-full" disabled={loading}>
|
<Button
|
||||||
{loading ? 'در حال ارسال...' : 'ارسال لینک بازیابی'}
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
className="h-12 w-full rounded-2xl"
|
||||||
|
onClick={() => void api.startGoogleLogin()}
|
||||||
|
>
|
||||||
|
ادامه با حساب گوگل
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
<div className="rounded-[1.5rem] border border-border/70 bg-muted/20 p-4 text-sm leading-7 text-muted-foreground">
|
||||||
</CardContent>
|
<p className="font-medium text-foreground">گامهای بازیابی</p>
|
||||||
</Card>
|
<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>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,122 +1,77 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect } from "react";
|
|
||||||
import { useParams, Link } from "@/lib/router";
|
|
||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import { api } from "@/lib/api";
|
import { AlertTriangle, ArrowLeft, Loader2, MailWarning } from "lucide-react";
|
||||||
import {
|
|
||||||
Card,
|
|
||||||
CardHeader,
|
|
||||||
CardTitle,
|
|
||||||
CardContent,
|
|
||||||
CardFooter,
|
|
||||||
} from "@/components/ui/card";
|
|
||||||
import { Alert, AlertTitle, AlertDescription } from "@/components/ui/alert";
|
|
||||||
import { Button } from "@/components/ui/button";
|
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";
|
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() {
|
export default function VerifyEmail() {
|
||||||
const { token } = useParams<{ token: string }>();
|
const { token } = useParams<{ token: string }>();
|
||||||
|
const { data, isLoading, isError, error } = useQuery({
|
||||||
const query = useQuery({
|
queryKey: ["legacy-email-guidance", token],
|
||||||
queryKey: ["verify-email", token],
|
queryFn: () => api.getLegacyVerifyEmailMessage(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: "متأسفانه خطایی رخ داد. لطفاً دوباره تلاش کنید.",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
},
|
|
||||||
retry: false,
|
retry: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
const message = isError
|
||||||
document.title = "تأیید ایمیل";
|
? resolveErrorMessage(error, "تأیید ایمیل دیگر برای ورود و بازیابی حساب استفاده نمیشود.")
|
||||||
}, []);
|
: data?.message ||
|
||||||
|
"تأیید ایمیل غیرفعال شده است. برای ادامه باید موبایل خود را تأیید کنید یا با همان حساب گوگل مرتبط وارد شوید.";
|
||||||
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>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-[70vh] flex items-center justify-center bg-background p-4">
|
<div className="min-h-screen bg-background px-4 py-10" dir="rtl">
|
||||||
<Card className="w-full max-w-lg" dir="rtl">
|
<div className="mx-auto max-w-2xl">
|
||||||
<CardHeader className="text-right">
|
<Card className="border-border/70 bg-background/90 shadow-xl">
|
||||||
<CardTitle>تأیید ایمیل</CardTitle>
|
<CardHeader className="text-right">
|
||||||
</CardHeader>
|
<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">
|
||||||
<CardContent className="space-y-6">{renderBody()}</CardContent>
|
<MailWarning className="h-5 w-5" />
|
||||||
<CardFooter className="flex items-center justify-between gap-3">
|
</div>
|
||||||
<Button asChild variant="secondary" className="min-w-32">
|
<CardTitle>تأیید ایمیل کنار گذاشته شده است</CardTitle>
|
||||||
<Link to="/">رفتن به صفحهٔ اصلی</Link>
|
<CardDescription className="leading-7">
|
||||||
</Button>
|
دسترسی کاربران به ایمیل محدود شده و مسیر تأیید حساب به موبایل و گوگل منتقل شده است.
|
||||||
<div className="flex items-center gap-2">
|
</CardDescription>
|
||||||
<Button asChild className="min-w-32">
|
</CardHeader>
|
||||||
<Link to="/auth">ورود به حساب</Link>
|
<CardContent className="space-y-5 text-right">
|
||||||
</Button>
|
<div className="rounded-[1.5rem] border border-border/70 bg-muted/25 p-4 text-sm leading-7 text-muted-foreground">
|
||||||
<Button asChild variant="outline" className="min-w-32">
|
{isLoading ? (
|
||||||
<Link to="/profile">پروفایل</Link>
|
<span className="flex items-center justify-end gap-2">
|
||||||
</Button>
|
<Loader2 className="h-4 w-4 animate-spin" />
|
||||||
</div>
|
در حال دریافت پیام راهنما...
|
||||||
</CardFooter>
|
</span>
|
||||||
</Card>
|
) : (
|
||||||
|
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>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user