feat(admin): implement Phase 3 Admin SPA Router and Dual-Token Auth integration
This commit is contained in:
1 parent
71e19bfe43
commit
eaa2621a17
11 files changed
+561
-153
No files matched your search
@@ -1,43 +1,75 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Navigate, Outlet } from 'react-router-dom';
|
||||
import api from '../services/api';
|
||||
import { useAdminAuthStore } from '../store/adminAuthStore';
|
||||
import type { ApiResponse, AuthResponseData, AdminUser } from '../types/admin';
|
||||
|
||||
export default function ProtectedRoute() {
|
||||
const token = localStorage.getItem('adminToken');
|
||||
const { isAuthenticated, accessToken, setAuth, clearAuth } = useAdminAuthStore();
|
||||
const [isValidating, setIsValidating] = useState(true);
|
||||
const [isValid, setIsValid] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) {
|
||||
setIsValid(false);
|
||||
setIsValidating(false);
|
||||
return;
|
||||
}
|
||||
let isMounted = true;
|
||||
|
||||
api.get('/users/profile')
|
||||
.then(() => {
|
||||
setIsValid(true);
|
||||
})
|
||||
.catch(() => {
|
||||
localStorage.removeItem('adminToken');
|
||||
setIsValid(false);
|
||||
})
|
||||
.finally(() => {
|
||||
const validateSession = async () => {
|
||||
if (isAuthenticated && accessToken) {
|
||||
setIsValidating(false);
|
||||
});
|
||||
}, [token]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!token || !isValid) {
|
||||
return <Navigate to="/login" replace />;
|
||||
}
|
||||
try {
|
||||
const response = await api.post<ApiResponse<AuthResponseData>>('/auth/refresh');
|
||||
if (response.data?.success && response.data.data?.accessToken) {
|
||||
if (isMounted) {
|
||||
setAuth(response.data.data.accessToken, response.data.data.user);
|
||||
setIsValidating(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// Fallback profile check if token already in memory
|
||||
}
|
||||
|
||||
if (accessToken) {
|
||||
try {
|
||||
const profileRes = await api.get<ApiResponse<AdminUser>>('/users/profile');
|
||||
if (profileRes.data?.data && isMounted) {
|
||||
setAuth(accessToken, profileRes.data.data);
|
||||
setIsValidating(false);
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// Token invalid
|
||||
}
|
||||
}
|
||||
|
||||
if (isMounted) {
|
||||
clearAuth();
|
||||
setIsValidating(false);
|
||||
}
|
||||
};
|
||||
|
||||
validateSession();
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, [isAuthenticated, accessToken, setAuth, clearAuth]);
|
||||
|
||||
if (isValidating) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||
<div className="w-8 h-8 border-4 border-purple-600 border-t-transparent rounded-full animate-spin"></div>
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50 font-vazir" dir="rtl">
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<div className="w-10 h-10 border-4 border-purple-600 border-t-transparent rounded-full animate-spin"></div>
|
||||
<span className="text-sm font-bold text-gray-500">در حال اعتبارسنجی نشست کاری ادمین...</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!useAdminAuthStore.getState().isAuthenticated) {
|
||||
return <Navigate to="/login" replace />;
|
||||
}
|
||||
|
||||
return <Outlet />;
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useRef } from 'react';
|
||||
import { Link, useLocation, useNavigate } from 'react-router-dom';
|
||||
import { Users, ShoppingCart, Tag, Settings, LogOut, TrendingUp, FolderTree, FileText, BookOpen, Heart, Package, LayoutDashboard, Languages, Image, Video, PhoneCall } from 'lucide-react';
|
||||
import api from '../services/api';
|
||||
import { useAdminAuthStore } from '../store/adminAuthStore';
|
||||
|
||||
const menuGroups = [
|
||||
{
|
||||
@@ -57,8 +58,10 @@ export default function Sidebar({ isOpen, setIsOpen }: SidebarProps) {
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const [newOrdersCount, setNewOrdersCount] = useState(0);
|
||||
const clearAuth = useAdminAuthStore((state) => state.clearAuth);
|
||||
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
useState(() => {
|
||||
const fetchOrdersCount = async () => {
|
||||
try {
|
||||
const response = await api.get('/admin/dashboard/stats');
|
||||
@@ -70,14 +73,22 @@ export default function Sidebar({ isOpen, setIsOpen }: SidebarProps) {
|
||||
}
|
||||
};
|
||||
fetchOrdersCount();
|
||||
// Poll stats every 60 seconds
|
||||
const interval = setInterval(fetchOrdersCount, 60000);
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
intervalRef.current = setInterval(fetchOrdersCount, 60000);
|
||||
return () => {
|
||||
if (intervalRef.current) clearInterval(intervalRef.current);
|
||||
};
|
||||
});
|
||||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem('adminToken');
|
||||
navigate('/login');
|
||||
const handleLogout = async () => {
|
||||
try {
|
||||
await api.post('/auth/logout');
|
||||
} catch {
|
||||
// Ignore logout errors
|
||||
} finally {
|
||||
clearAuth();
|
||||
localStorage.removeItem('adminToken');
|
||||
navigate('/login');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -2,6 +2,8 @@ import { useState, useRef, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Bell, Search, UserCircle, Menu } from 'lucide-react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import api from '../services/api';
|
||||
import { useAdminAuthStore } from '../store/adminAuthStore';
|
||||
|
||||
interface TopbarProps {
|
||||
toggleMenu: () => void;
|
||||
@@ -28,8 +30,9 @@ export default function Topbar({ toggleMenu }: TopbarProps) {
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [showResults, setShowResults] = useState(false);
|
||||
const searchContainerRef = useRef<HTMLDivElement>(null);
|
||||
const clearAuth = useAdminAuthStore((state) => state.clearAuth);
|
||||
const adminUser = useAdminAuthStore((state) => state.adminUser);
|
||||
|
||||
// Close search results dropdown on clicking outside
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (searchContainerRef.current && !searchContainerRef.current.contains(event.target as Node)) {
|
||||
@@ -68,12 +71,23 @@ export default function Topbar({ toggleMenu }: TopbarProps) {
|
||||
return () => document.removeEventListener('mousedown', handleOutsideClick);
|
||||
}, []);
|
||||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem('adminToken');
|
||||
toast.success('خروج با موفقیت انجام شد');
|
||||
navigate('/login');
|
||||
const handleLogout = async () => {
|
||||
try {
|
||||
await api.post('/auth/logout');
|
||||
} catch {
|
||||
// Ignore
|
||||
} finally {
|
||||
clearAuth();
|
||||
localStorage.removeItem('adminToken');
|
||||
toast.success('خروج با موفقیت انجام شد');
|
||||
navigate('/login');
|
||||
}
|
||||
};
|
||||
|
||||
const displayName = adminUser
|
||||
? `${adminUser.firstName || ''} ${adminUser.lastName || ''}`.trim() || adminUser.email || adminUser.mobile
|
||||
: 'مدیر سیستم';
|
||||
|
||||
return (
|
||||
<header className="h-16 bg-white border-b border-gray-200 flex items-center justify-between px-4 sm:px-6 sticky top-0 z-40 shadow-sm font-vazir">
|
||||
<div className="flex-1 flex items-center gap-3 max-w-xl" ref={searchContainerRef}>
|
||||
@@ -99,7 +113,6 @@ export default function Topbar({ toggleMenu }: TopbarProps) {
|
||||
className="w-full bg-gray-50 border border-gray-200 text-gray-900 text-sm rounded-xl focus:ring-purple-500 focus:border-purple-500 block pr-10 p-2.5 outline-none font-bold transition-all"
|
||||
/>
|
||||
|
||||
{/* Live Search Results Dropdown */}
|
||||
{showResults && searchQuery.trim() !== '' && (
|
||||
<div className="absolute top-full right-0 left-0 mt-2 bg-white border border-gray-100 rounded-xl shadow-2xl z-50 overflow-hidden max-h-60 overflow-y-auto">
|
||||
{filteredResults.length > 0 ? (
|
||||
@@ -124,7 +137,6 @@ export default function Topbar({ toggleMenu }: TopbarProps) {
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
{/* Realtime Notifications (TASK-2.20) */}
|
||||
<div className="relative" ref={notifRef}>
|
||||
<button
|
||||
onClick={() => setShowNotifications(!showNotifications)}
|
||||
@@ -159,15 +171,14 @@ export default function Topbar({ toggleMenu }: TopbarProps) {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* User Profile Dropdown (TASK-2.19) */}
|
||||
<div className="relative" ref={userMenuRef}>
|
||||
<button
|
||||
onClick={() => setShowUserMenu(!showUserMenu)}
|
||||
className="flex items-center gap-3 pl-2 border-l border-gray-200 cursor-pointer hover:opacity-80 transition-opacity"
|
||||
>
|
||||
<div className="text-left hidden md:block">
|
||||
<p className="text-sm font-bold text-gray-900">مدیر سیستم</p>
|
||||
<p className="text-xs font-medium text-purple-600">ادمین ارشد</p>
|
||||
<p className="text-sm font-bold text-gray-900">{displayName}</p>
|
||||
<p className="text-xs font-medium text-purple-600">{adminUser?.role || 'ادمین ارشد'}</p>
|
||||
</div>
|
||||
<UserCircle className="w-10 h-10 text-purple-600" />
|
||||
</button>
|
||||
|
||||
Reference in new issue
Block a user