ifixkart-admin/components/security/IdleSessionManager.tsx

195 lines
7.5 KiB
TypeScript

'use client';
import React, { useEffect, useState, useRef, useCallback } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { AlertTriangle, Clock, LogOut, ShieldAlert } from 'lucide-react';
import { authService } from '@/services/api/authService';
import { getAccessToken } from '@/services/api/client';
import { toast } from 'sonner';
// Idle timeout: 30 minutes in ms
const IDLE_TIMEOUT_MS = 30 * 60 * 1000;
// Warning prompt starts at 28 minutes (2 minutes before auto-logout)
const WARNING_BEFORE_MS = 2 * 60 * 1000;
const WARNING_THRESHOLD_MS = IDLE_TIMEOUT_MS - WARNING_BEFORE_MS; // 28 minutes
const STORAGE_KEY_LAST_ACTIVITY = 'ifixkart_last_active_timestamp';
export function IdleSessionManager() {
const router = useRouter();
const pathname = usePathname();
const [showWarning, setShowWarning] = useState(false);
const [secondsRemaining, setSecondsRemaining] = useState(120);
const lastActivityRef = useRef<number>(Date.now());
const timerCheckIntervalRef = useRef<NodeJS.Timeout | null>(null);
const recordActivity = useCallback(() => {
const now = Date.now();
lastActivityRef.current = now;
if (typeof window !== 'undefined') {
try {
localStorage.setItem(STORAGE_KEY_LAST_ACTIVITY, String(now));
} catch {
// Storage access fallback
}
}
if (showWarning) {
setShowWarning(false);
}
}, [showWarning]);
const handleLogout = useCallback(async (reason: string = 'idle') => {
setShowWarning(false);
if (timerCheckIntervalRef.current) {
clearInterval(timerCheckIntervalRef.current);
}
toast.error('Session expired due to 30 minutes of inactivity. Please log in again.');
try {
await authService.logout();
} catch {
// Ignore network errors during logout
}
router.push(`/login?reason=${reason}`);
}, [router]);
const handleStayLoggedIn = () => {
recordActivity();
setShowWarning(false);
toast.success('Session extended. You are still securely signed in.');
};
useEffect(() => {
// Only monitor authenticated pages (exclude login / forgot password pages)
if (pathname?.includes('/login') || pathname?.includes('/forgot-password')) {
return;
}
const token = getAccessToken();
if (!token) return;
// Initialize timestamp
const now = Date.now();
lastActivityRef.current = now;
try {
localStorage.setItem(STORAGE_KEY_LAST_ACTIVITY, String(now));
} catch {}
// Throttle activity capture
let lastRecorded = 0;
const onUserInteraction = () => {
const current = Date.now();
if (current - lastRecorded > 10000) { // Throttle every 10 seconds
lastRecorded = current;
recordActivity();
}
};
const events = ['mousedown', 'mousemove', 'keydown', 'scroll', 'touchstart', 'click'];
events.forEach((evt) => {
window.addEventListener(evt, onUserInteraction, { passive: true });
});
// Cross-tab synchronization listener
const onStorageUpdate = (e: StorageEvent) => {
if (e.key === STORAGE_KEY_LAST_ACTIVITY && e.newValue) {
const remoteTimestamp = parseInt(e.newValue, 10);
if (!isNaN(remoteTimestamp) && remoteTimestamp > lastActivityRef.current) {
lastActivityRef.current = remoteTimestamp;
setShowWarning(false);
}
}
};
window.addEventListener('storage', onStorageUpdate);
// Heartbeat ticker checks every 1000ms
timerCheckIntervalRef.current = setInterval(() => {
const currentTimestamp = Date.now();
const elapsed = currentTimestamp - lastActivityRef.current;
if (elapsed >= IDLE_TIMEOUT_MS) {
handleLogout('idle_timeout');
} else if (elapsed >= WARNING_THRESHOLD_MS) {
setShowWarning(true);
const rem = Math.max(0, Math.ceil((IDLE_TIMEOUT_MS - elapsed) / 1000));
setSecondsRemaining(rem);
} else {
setShowWarning(false);
}
}, 1000);
return () => {
events.forEach((evt) => {
window.removeEventListener(evt, onUserInteraction);
});
window.removeEventListener('storage', onStorageUpdate);
if (timerCheckIntervalRef.current) {
clearInterval(timerCheckIntervalRef.current);
}
};
}, [pathname, recordActivity, handleLogout]);
if (!showWarning) return null;
const minutes = Math.floor(secondsRemaining / 60);
const seconds = secondsRemaining % 60;
const formattedCountdown = `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70 backdrop-blur-md animate-in fade-in duration-200">
<div className="relative w-full max-w-md overflow-hidden rounded-2xl border border-amber-500/30 bg-card p-6 shadow-2xl text-card-foreground">
{/* Glow Accent Header */}
<div className="absolute top-0 left-0 right-0 h-1.5 bg-gradient-to-r from-amber-500 via-orange-500 to-red-500 animate-pulse" />
<div className="flex items-start gap-4 mb-4">
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-amber-500/10 text-amber-500 ring-1 ring-amber-500/20">
<ShieldAlert className="h-6 w-6" />
</div>
<div>
<h3 className="text-lg font-bold tracking-tight text-foreground flex items-center gap-2">
Inactivity Security Notice
</h3>
<p className="text-xs text-muted-foreground mt-0.5">
30-Minute Automatic Session Protection
</p>
</div>
</div>
<p className="text-sm text-muted-foreground leading-relaxed">
You have been inactive for nearly 30 minutes. To protect internal e-commerce and CRM data, your session will automatically terminate in:
</p>
{/* Big Countdown Timer */}
<div className="my-5 flex flex-col items-center justify-center rounded-xl border border-border/80 bg-muted/40 p-4">
<div className="flex items-center gap-2 text-3xl font-extrabold tracking-wider text-amber-500 dark:text-amber-400 font-mono">
<Clock className="h-6 w-6 animate-spin text-amber-500" style={{ animationDuration: '4s' }} />
<span>{formattedCountdown}</span>
</div>
<span className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground mt-1">
Minutes Remaining Before Auto-Logout
</span>
</div>
{/* Action Buttons */}
<div className="flex flex-col-reverse sm:flex-row gap-2.5 mt-5">
<button
type="button"
onClick={() => handleLogout('user_initiated')}
className="flex-1 inline-flex items-center justify-center gap-2 rounded-xl border border-border bg-background px-4 py-2.5 text-sm font-semibold text-foreground hover:bg-muted/80 transition shadow-sm"
>
<LogOut className="h-4 w-4 text-muted-foreground" />
Log Out Now
</button>
<button
type="button"
onClick={handleStayLoggedIn}
className="flex-1 inline-flex items-center justify-center gap-2 rounded-xl bg-gradient-to-r from-blue-600 to-indigo-600 px-4 py-2.5 text-sm font-semibold text-white shadow hover:from-blue-700 hover:to-indigo-700 transition"
>
Stay Logged In
</button>
</div>
</div>
</div>
);
}