diff --git a/src/app/entry.server.tsx b/src/app/entry.server.tsx index 64f4d46..aa73a97 100644 --- a/src/app/entry.server.tsx +++ b/src/app/entry.server.tsx @@ -28,9 +28,9 @@ axios.interceptors.response.use( async (e) => { console.error(e); - if (e.status !== 401 || e.request.url.includes('refresh') || e.request.config.sent || !e.config) return; + if (e.response.status !== 401 || e.config.url.includes('refresh') || e.config.sent) return; - const accessToken = await requestRefreshToken(e.request); + const accessToken = await requestRefreshToken(e.config.headers); e.config.headers.Authorization = `Bearer ${accessToken}`; e.config.sent = true; return axios(e.config); diff --git a/src/app/server/authenticate.ts b/src/app/server/authenticate.ts index 7751d67..74b4c31 100644 --- a/src/app/server/authenticate.ts +++ b/src/app/server/authenticate.ts @@ -1,5 +1,11 @@ import { redirect } from '@remix-run/node'; -import { destroySession, generateExpiredDate, getAuthSession, isDateExpired } from 'src/app/server/sessions'; +import { + destroySession, + generateExpiredDate, + getAuthSession, + getAuthSessionFromHeaders, + isDateExpired, +} from 'src/app/server/sessions'; import { refreshToken } from 'src/types'; export const authenticate = async (request: Request) => { @@ -20,7 +26,7 @@ export const authenticateWithoutRedirection = async (request: Request) => { } if (!expiredAt || isDateExpired(expiredAt)) { - const { data } = await requestRefreshToken(request); + const { data } = await requestRefreshToken(request.headers); session.set('accessToken', data.accessToken); session.set('refreshToken', data.refreshToken); @@ -32,8 +38,8 @@ export const authenticateWithoutRedirection = async (request: Request) => { return { accessToken }; }; -export const requestRefreshToken = async (request: Request) => { - const session = await getAuthSession(request); +export const requestRefreshToken = async (headers: Headers) => { + const session = await getAuthSessionFromHeaders(headers); try { const { data } = await refreshToken({ accessToken: session.get('accessToken')!, diff --git a/src/app/server/sessions.ts b/src/app/server/sessions.ts index 95bdee3..ead8331 100644 --- a/src/app/server/sessions.ts +++ b/src/app/server/sessions.ts @@ -30,4 +30,8 @@ const getAuthSession = async (request: Request) => { return await getSession(request.headers.get('Cookie')); }; -export { getAuthSession, commitSession, destroySession }; +const getAuthSessionFromHeaders = async (headers: Headers) => { + return await getSession(headers.get('Cookie')); +}; + +export { getAuthSession, getAuthSessionFromHeaders, commitSession, destroySession };