Skip to content

Commit

Permalink
fix: do not redirect on api proxy authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
ooooorobo committed Sep 23, 2024
1 parent f42a30e commit 1743bb5
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 15 deletions.
25 changes: 11 additions & 14 deletions src/app/routes/api.$.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { ActionFunction, json, LoaderFunction } from '@remix-run/node';
import { authenticate } from 'src/app/server/authenticate';
import { ActionFunction, LoaderFunction } from '@remix-run/node';
import { authenticate, authenticateWithoutRedirection } from 'src/app/server/authenticate';
import { commitSession } from 'src/app/server/sessions';

const apiURL = new URL(process.env.API_BASE_URL ?? '');

export const loader: LoaderFunction = async (args) => {
const { accessToken, newSession } = await authenticate(args.request);
const { accessToken, newSession } = (await authenticate(args.request)) ?? {};

const url = new URL(args.request.url);
url.protocol = apiURL.protocol;
Expand All @@ -21,15 +21,13 @@ export const loader: LoaderFunction = async (args) => {
},
}),
);
return json(await response.json(), {
headers: {
...(newSession && { 'Set-Cookie': await commitSession(newSession) }),
},
});
if (newSession) response.headers.set('Set-Cookie', await commitSession(newSession));

return response;
};

export const action: ActionFunction = async (args) => {
const { accessToken, newSession } = await authenticate(args.request);
const { accessToken, newSession } = (await authenticateWithoutRedirection(args.request)) ?? {};

const url = new URL(args.request.url);
url.protocol = apiURL.protocol;
Expand All @@ -46,9 +44,8 @@ export const action: ActionFunction = async (args) => {
},
}),
);
return json(await response.json(), {
headers: {
...(newSession && { 'Set-Cookie': await commitSession(newSession) }),
},
});

if (newSession) response.headers.set('Set-Cookie', await commitSession(newSession));

return response;
};
12 changes: 11 additions & 1 deletion src/app/server/authenticate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,22 @@ import { destroySession, generateExpiredDate, getAuthSession, isDateExpired } fr
import { refreshToken } from 'src/types';

export const authenticate = async (request: Request) => {
const token = authenticateWithoutRedirection(request);

if (!token) {
throw redirect('/login');
}

return token;
};

export const authenticateWithoutRedirection = async (request: Request) => {
const session = await getAuthSession(request);
const expiredAt = session.get('expiredAt');
const accessToken = session.get('accessToken');

if (!accessToken) {
throw redirect('/login');
return null;
}

if (!expiredAt || isDateExpired(expiredAt)) {
Expand Down

0 comments on commit 1743bb5

Please sign in to comment.