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

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

View File

@@ -27,7 +27,7 @@ export default function MobileBottomNav() {
const pathname = usePathname() || "/";
const { isAuthenticated } = useAuth();
if (pathname.startsWith("/admin") || pathname === "/logout") {
if (pathname.startsWith("/admin") || pathname === "/logout" || pathname.startsWith("/auth/google")) {
return null;
}

View 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>
);
}

View File

@@ -5,6 +5,7 @@ import { useMemo } from "react";
import { Link, NavLink } from "@/lib/router";
import { useAuth } from "@/contexts/AuthContext";
import ModeToggle from "@/components/ModeToggle";
import NotificationsBell from "@/components/NotificationsBell";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
@@ -70,6 +71,7 @@ export default function Navbar() {
<NavItem to="/blog">بلاگ</NavItem>
<NavItem to="/events">رویدادها</NavItem>
<ModeToggle />
{isAuthenticated ? <NotificationsBell /> : null}
{isAuthenticated ? (
<Link
@@ -106,6 +108,7 @@ export default function Navbar() {
</div>
<div className="flex items-center gap-2 md:hidden">
{isAuthenticated ? <NotificationsBell /> : null}
<ModeToggle />
</div>
</div>

View 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>
);
}

View 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>
);
}

View File

@@ -6,7 +6,9 @@ import { TooltipProvider } from "@/components/ui/tooltip";
import { Toaster } from "@/components/ui/toaster";
import { Toaster as Sonner } from "@/components/ui/sonner";
import { ThemeProvider } from "@/components/ThemeProvider";
import MobileVerificationGate from "@/components/MobileVerificationGate";
import { AuthProvider } from "@/contexts/AuthContext";
import { NotificationsProvider } from "@/contexts/NotificationsContext";
export default function Providers({ children }: { children: React.ReactNode }) {
const [queryClient] = React.useState(() => new QueryClient());
@@ -20,11 +22,14 @@ export default function Providers({ children }: { children: React.ReactNode }) {
>
<QueryClientProvider client={queryClient}>
<AuthProvider>
<TooltipProvider>
<Toaster />
<Sonner />
{children}
</TooltipProvider>
<NotificationsProvider>
<TooltipProvider>
<Toaster />
<Sonner />
{children}
<MobileVerificationGate />
</TooltipProvider>
</NotificationsProvider>
</AuthProvider>
</QueryClientProvider>
</ThemeProvider>