Auto-logout users when page is closed
- Create LogoutOnUnload component that triggers logout on page close - Uses beforeunload/unload events with navigator.sendBeacon() for reliability - Create /api/logout endpoint that clears both admin and customer sessions - Add LogoutOnUnload to root layout so it runs on all pages - Works for both admin and customer users Behavior: - When user closes browser tab/window, logout happens automatically - Session cookies are cleared via API endpoint - Improves security by preventing session hijacking from closed windows Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Haiku 4.5
parent
a2908e8ae1
commit
3aa2b730bc
@@ -0,0 +1,14 @@
|
||||
import { cookies } from 'next/headers';
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
export async function POST() {
|
||||
const cookieStore = await cookies();
|
||||
|
||||
// Clear admin session
|
||||
cookieStore.delete('adminSession');
|
||||
|
||||
// Clear customer session
|
||||
cookieStore.delete('session');
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import Header from '@/components/Header';
|
||||
import Footer from '@/components/Footer';
|
||||
import PromotionBanner from '@/components/PromotionBanner';
|
||||
import MaintenancePage from '@/components/MaintenancePage';
|
||||
import LogoutOnUnload from '@/components/LogoutOnUnload';
|
||||
import { CurrencyProvider } from '@/lib/CurrencyContext';
|
||||
import { getSiteSettings } from '@/lib/settings';
|
||||
import { isAdminAuthenticated } from '@/lib/adminAuth';
|
||||
@@ -60,6 +61,7 @@ export default async function RootLayout({ children }: { children: React.ReactNo
|
||||
/>
|
||||
</head>
|
||||
<body className="flex min-h-screen flex-col">
|
||||
<LogoutOnUnload />
|
||||
<CurrencyProvider>
|
||||
{showMaintenance ? (
|
||||
<MaintenancePage message={maintenanceMessage} />
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
|
||||
/**
|
||||
* Logs out the user when they close/leave the page
|
||||
* Works for both admin and customer sessions
|
||||
*/
|
||||
export default function LogoutOnUnload() {
|
||||
useEffect(() => {
|
||||
const handleUnload = () => {
|
||||
// Use sendBeacon to reliably send logout even when page is closing
|
||||
// This doesn't wait for a response, which is fine for logout
|
||||
navigator.sendBeacon('/api/logout');
|
||||
};
|
||||
|
||||
window.addEventListener('beforeunload', handleUnload);
|
||||
window.addEventListener('unload', handleUnload);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('beforeunload', handleUnload);
|
||||
window.removeEventListener('unload', handleUnload);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
}
|
||||
Reference in New Issue
Block a user