690331:1616 Correspondence Page Refactor by GPT-5.3-Codex Medium #03
This commit is contained in:
@@ -3,6 +3,7 @@
|
|||||||
import { useSession, signOut } from 'next-auth/react';
|
import { useSession, signOut } from 'next-auth/react';
|
||||||
import { useEffect } from 'react';
|
import { useEffect } from 'react';
|
||||||
import { useAuthStore } from '@/lib/stores/auth-store';
|
import { useAuthStore } from '@/lib/stores/auth-store';
|
||||||
|
import { clearAuthTokenCache } from '@/lib/api/client';
|
||||||
|
|
||||||
export function AuthSync() {
|
export function AuthSync() {
|
||||||
const { data: session, status } = useSession();
|
const { data: session, status } = useSession();
|
||||||
@@ -10,6 +11,7 @@ export function AuthSync() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (session?.error === 'RefreshAccessTokenError') {
|
if (session?.error === 'RefreshAccessTokenError') {
|
||||||
|
clearAuthTokenCache(); // Clear cached token on auth error
|
||||||
signOut({ callbackUrl: '/login' });
|
signOut({ callbackUrl: '/login' });
|
||||||
} else if (status === 'authenticated' && session?.user) {
|
} else if (status === 'authenticated' && session?.user) {
|
||||||
// Map NextAuth session to AuthStore user
|
// Map NextAuth session to AuthStore user
|
||||||
@@ -40,6 +42,7 @@ export function AuthSync() {
|
|||||||
(session as { accessToken?: string }).accessToken || ''
|
(session as { accessToken?: string }).accessToken || ''
|
||||||
);
|
);
|
||||||
} else if (status === 'unauthenticated') {
|
} else if (status === 'unauthenticated') {
|
||||||
|
clearAuthTokenCache(); // Clear cached token on logout
|
||||||
logout();
|
logout();
|
||||||
}
|
}
|
||||||
}, [session, status, setAuth, logout]);
|
}, [session, status, setAuth, logout]);
|
||||||
|
|||||||
@@ -25,15 +25,6 @@ interface CorrespondenceDetailProps {
|
|||||||
selectedRevisionId?: string;
|
selectedRevisionId?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const normalizeUuid = (value?: string): string | undefined => {
|
|
||||||
if (typeof value !== 'string') {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
const normalized = value.trim().toLowerCase();
|
|
||||||
return normalized.length > 0 ? normalized : undefined;
|
|
||||||
};
|
|
||||||
|
|
||||||
const normalizeRecipientType = (value?: string): string | undefined => {
|
const normalizeRecipientType = (value?: string): string | undefined => {
|
||||||
if (typeof value !== 'string') {
|
if (typeof value !== 'string') {
|
||||||
return undefined;
|
return undefined;
|
||||||
@@ -54,9 +45,9 @@ export function CorrespondenceDetail({ data, selectedRevisionId }: Correspondenc
|
|||||||
|
|
||||||
if (!data) return <div>No data found</div>;
|
if (!data) return <div>No data found</div>;
|
||||||
|
|
||||||
const normalizedSelectedRevisionId = normalizeUuid(selectedRevisionId);
|
// เลือก revision ตาม selectedRevisionId ถ้ามี ถ้าไม่มีใช้ revision ปัจจุบัน
|
||||||
const selectedRevision = normalizedSelectedRevisionId
|
const selectedRevision = selectedRevisionId
|
||||||
? data.revisions?.find((r) => normalizeUuid(r.publicId) === normalizedSelectedRevisionId)
|
? data.revisions?.find((r) => r.publicId === selectedRevisionId)
|
||||||
: undefined;
|
: undefined;
|
||||||
const currentRevision = selectedRevision || data.revisions?.find((r) => r.isCurrent) || data.revisions?.[0];
|
const currentRevision = selectedRevision || data.revisions?.find((r) => r.isCurrent) || data.revisions?.[0];
|
||||||
const subject = currentRevision?.subject || '-';
|
const subject = currentRevision?.subject || '-';
|
||||||
|
|||||||
+50
-13
@@ -5,6 +5,49 @@ import { v4 as uuidv4 } from 'uuid';
|
|||||||
// อ่านค่า Base URL จาก Environment Variable
|
// อ่านค่า Base URL จาก Environment Variable
|
||||||
const baseURL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api';
|
const baseURL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api';
|
||||||
|
|
||||||
|
// Token cache for API calls outside React components
|
||||||
|
let cachedToken: string | null = null;
|
||||||
|
let tokenPromise: Promise<string | null> | null = null;
|
||||||
|
|
||||||
|
// Async function to get token
|
||||||
|
async function getAuthToken(): Promise<string | null> {
|
||||||
|
if (cachedToken) return cachedToken;
|
||||||
|
|
||||||
|
if (tokenPromise) return tokenPromise;
|
||||||
|
|
||||||
|
tokenPromise = (async () => {
|
||||||
|
try {
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
const { getSession } = await import('next-auth/react');
|
||||||
|
const session = await getSession();
|
||||||
|
cachedToken = session?.accessToken || null;
|
||||||
|
return cachedToken;
|
||||||
|
}
|
||||||
|
} catch (_error) {
|
||||||
|
// Fallback to localStorage
|
||||||
|
try {
|
||||||
|
const authStorage = localStorage.getItem('auth-storage');
|
||||||
|
if (authStorage) {
|
||||||
|
const parsed = JSON.parse(authStorage);
|
||||||
|
cachedToken = parsed?.state?.token || null;
|
||||||
|
return cachedToken;
|
||||||
|
}
|
||||||
|
} catch (__error) {
|
||||||
|
// All methods failed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
})();
|
||||||
|
|
||||||
|
return tokenPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Function to clear token cache (call on logout)
|
||||||
|
export function clearAuthTokenCache(): void {
|
||||||
|
cachedToken = null;
|
||||||
|
tokenPromise = null;
|
||||||
|
}
|
||||||
|
|
||||||
// สร้าง Axios Instance หลัก
|
// สร้าง Axios Instance หลัก
|
||||||
const apiClient: AxiosInstance = axios.create({
|
const apiClient: AxiosInstance = axios.create({
|
||||||
baseURL,
|
baseURL,
|
||||||
@@ -28,22 +71,13 @@ apiClient.interceptors.request.use(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 2. Authentication Token Injection
|
// 2. Authentication Token Injection
|
||||||
// ดึง Token จาก Zustand persist store (localStorage)
|
// ดึง Token จาก NextAuth session ผ่าน getSession()
|
||||||
if (typeof window !== 'undefined') {
|
if (typeof window !== 'undefined') {
|
||||||
try {
|
const token = await getAuthToken();
|
||||||
const authStorage = localStorage.getItem('auth-storage');
|
|
||||||
if (authStorage) {
|
|
||||||
const parsed = JSON.parse(authStorage);
|
|
||||||
const token = parsed?.state?.token;
|
|
||||||
|
|
||||||
if (token) {
|
if (token) {
|
||||||
config.headers['Authorization'] = `Bearer ${token}`;
|
config.headers['Authorization'] = `Bearer ${token}`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (_error) {
|
|
||||||
// Auth token retrieval failed - request will proceed without token
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return config;
|
return config;
|
||||||
},
|
},
|
||||||
@@ -66,8 +100,11 @@ apiClient.interceptors.response.use(
|
|||||||
|
|
||||||
// กรณี Token หมดอายุ หรือ ไม่มีสิทธิ์
|
// กรณี Token หมดอายุ หรือ ไม่มีสิทธิ์
|
||||||
if (status === 401) {
|
if (status === 401) {
|
||||||
// Unauthorized: redirect handled by auth interceptor
|
// Clear cached token and redirect to login
|
||||||
// สามารถเพิ่ม Logic Redirect ไปหน้า Login ได้ถ้าต้องการ
|
clearAuthTokenCache();
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
window.location.href = '/login';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return Promise.reject(error);
|
return Promise.reject(error);
|
||||||
|
|||||||
+2
-1
@@ -55,8 +55,9 @@ export const config = {
|
|||||||
* - _next/static (static files)
|
* - _next/static (static files)
|
||||||
* - _next/image (image optimization files)
|
* - _next/image (image optimization files)
|
||||||
* - favicon.ico (favicon file)
|
* - favicon.ico (favicon file)
|
||||||
|
* - robots.txt (robots file)
|
||||||
* - images (public images)
|
* - images (public images)
|
||||||
*/
|
*/
|
||||||
'/((?!api|_next/static|_next/image|favicon.ico|images).*)',
|
'/((?!api|_next/static|_next/image|favicon.ico|robots.txt|images).*)',
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user