Skip to content

Commit

Permalink
refactor: improve auth flow
Browse files Browse the repository at this point in the history
  • Loading branch information
solufa committed Jun 21, 2024
1 parent f8e4c96 commit 9439186
Show file tree
Hide file tree
Showing 5 changed files with 16 additions and 18 deletions.
18 changes: 6 additions & 12 deletions client/components/auth/AuthLoader.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { fetchAuthSession, signOut } from 'aws-amplify/auth';
import { fetchAuthSession, getCurrentUser, signOut } from 'aws-amplify/auth';
import { Hub } from 'aws-amplify/utils';
import { isAxiosError } from 'axios';
import { useAlert } from 'components/alert/useAlert';
Expand All @@ -25,14 +25,10 @@ export const AuthLoader = () => {
}, [catchApiErr, setUser]);

useEffect(() => {
const controller = new AbortController();
apiClient.private.me
.$get({ config: { signal: controller.signal } })
.then(setUser)
.catch((e) => (isAxiosError(e) && e.response?.status === 401 ? setUser(null) : null));

return () => controller.abort();
}, [setUser]);
getCurrentUser()
.then(updateCookie)
.catch(() => setUser(null));
}, [setUser, updateCookie]);

useEffect(() => {
const useId = apiAxios.interceptors.response.use(undefined, async (err) => {
Expand All @@ -56,17 +52,15 @@ export const AuthLoader = () => {
async (data) => {
switch (data.payload.event) {
case 'customOAuthState':
break;
case 'signInWithRedirect':
break;
case 'signInWithRedirect_failure':
case 'tokenRefresh':
break;
case 'signedOut':
await apiClient.session.$delete().catch(catchApiErr);
setUser(null);
break;
case 'signedIn':
case 'tokenRefresh':
await updateCookie().catch(catchApiErr);
break;
case 'tokenRefresh_failure':
Expand Down
2 changes: 1 addition & 1 deletion compose.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
services:
magnito:
image: frourio/magnito:0.7.0
image: frourio/magnito:0.8.0
ports:
- 5000:5000
- 5001:5001
Expand Down
2 changes: 1 addition & 1 deletion server/api/private/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export default defineHooks(() => ({
try {
await req.jwtVerify({ onlyCookie: true });
} catch (e) {
res.status(401).send();
res.status(401).send((e as Error).message);
return;
}

Expand Down
9 changes: 6 additions & 3 deletions server/api/session/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,21 @@ const options: CookieSerializeOptions = {
sameSite: 'strict',
};

export default defineController(() => ({
export default defineController((fastify) => ({
post: {
validators: { body: z.object({ jwt: z.string() }) },
hooks: {
preHandler: (req, reply, done) => {
assert(req.body);

const expiresIn = 60 * 60 * 24 * 5 * 1000;
const decoded = z
.object({ payload: z.object({ exp: z.number() }).passthrough() })
.passthrough()
.parse(fastify.jwt.decode(req.body.jwt));

reply.setCookie(COOKIE_NAME, req.body.jwt, {
...options,
expires: new Date(Date.now() + expiresIn),
expires: new Date(decoded.payload.exp * 1000),
});

done();
Expand Down
3 changes: 2 additions & 1 deletion server/tests/api/public.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { createSigner } from 'fast-jwt';
import { COOKIE_NAME } from 'service/constants';
import { expect, test } from 'vitest';
import { createUserClient, noCookieClient } from './apiClient';
Expand All @@ -24,7 +25,7 @@ test(GET(noCookieClient.health), async () => {
});

test(POST(noCookieClient.session), async () => {
const jwt = 'dummy-jwt';
const jwt = createSigner({ key: 'dummy' })({ exp: Math.floor(Date.now() / 1000) + 100 });
const res = await noCookieClient.session.post({ body: { jwt } });

expect(res.headers['set-cookie'][0].startsWith(`${COOKIE_NAME}=${jwt};`)).toBeTruthy();
Expand Down

0 comments on commit 9439186

Please sign in to comment.