-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathAuthGuard.tsx
More file actions
66 lines (55 loc) · 1.86 KB
/
Copy pathAuthGuard.tsx
File metadata and controls
66 lines (55 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
'use client';
import React, { useEffect, useState } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { useAuth } from '@/hooks/useAuth';
import { Loader2 } from 'lucide-react';
export function AuthGuard({ children }: { children: React.ReactNode }) {
const { isAuthenticated, isLoading, sessionExpiresAt, WARN_BEFORE_MS } = useAuth();
const router = useRouter();
const pathname = usePathname();
const [showTimeoutWarning, setShowTimeoutWarning] = useState(false);
useEffect(() => {
if (!isLoading && !isAuthenticated) {
router.push(`/?callbackUrl=${encodeURIComponent(pathname)}`);
}
}, [isLoading, isAuthenticated, router, pathname]);
// Schedule a warning announcement 5 minutes before session expiry
useEffect(() => {
if (!sessionExpiresAt) return;
const warnAt = sessionExpiresAt - WARN_BEFORE_MS;
const delay = warnAt - Date.now();
if (delay <= 0) return;
const warningTimer = setTimeout(() => setShowTimeoutWarning(true), delay);
const expireTimer = setTimeout(() => setShowTimeoutWarning(false), sessionExpiresAt - Date.now());
return () => {
clearTimeout(warningTimer);
clearTimeout(expireTimer);
};
}, [sessionExpiresAt, WARN_BEFORE_MS]);
if (isLoading) {
return (
<div className="flex h-screen w-full items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
</div>
);
}
if (!isAuthenticated) {
return null;
}
return (
<>
{/* aria-live region is always mounted so SR picks up dynamic content changes */}
<div
role="alert"
aria-live="assertive"
aria-atomic="true"
className="sr-only"
>
{showTimeoutWarning
? 'Your session will expire in 5 minutes. Please save your work.'
: ''}
</div>
{children}
</>
);
}