From b5280b70a14b23fcfca384d7fdd082187b423a63 Mon Sep 17 00:00:00 2001 From: lnn0q Date: Fri, 18 Apr 2025 15:26:18 +0300 Subject: [PATCH] added log out --- app/client/hooks/auth.tsx | 18 ++++++++++++++- app/client/pages/__root.tsx | 46 ++++++++++++++++++++++--------------- 2 files changed, 45 insertions(+), 19 deletions(-) diff --git a/app/client/hooks/auth.tsx b/app/client/hooks/auth.tsx index 0e83fa6..fdfe8a5 100644 --- a/app/client/hooks/auth.tsx +++ b/app/client/hooks/auth.tsx @@ -7,7 +7,7 @@ import { url } from '../main'; interface AuthContextProps { headers: Session | null; - setHeaders: (session: Session) => void; + setHeaders: (session: Session | null) => void; } export const AuthContext = createContext(null); @@ -16,6 +16,7 @@ export const AuthProvider = AuthContext.Provider; interface UseAuthOutput extends AuthContextProps { isAuthenticated: boolean; login: (value: { email: string; password: string }) => Promise; + logout: () => Promise; } export function useAuth(): UseAuthOutput { @@ -25,6 +26,11 @@ export function useAuth(): UseAuthOutput { successMsg: 'Logged in successfully.' }); + const { update: logout } = useToastMutation({ + mutation: logoutMutation, + successMsg: 'Logged out successfully.' + }); + if (!authContext) throw new Error('useAuth must be used within an AuthProvider'); return { @@ -45,6 +51,10 @@ export function useAuth(): UseAuthOutput { return data.login; } return data; + }, + logout: async () => { + await logout(); + authContext.setHeaders(null); } }; } @@ -81,3 +91,9 @@ const loginMutation = gql` ${sessionFragment} `; + +const logoutMutation = gql` + mutation AuthLogout { + logout + } +`; diff --git a/app/client/pages/__root.tsx b/app/client/pages/__root.tsx index 8aa2483..25c2d04 100644 --- a/app/client/pages/__root.tsx +++ b/app/client/pages/__root.tsx @@ -1,6 +1,7 @@ import { Button, Stack } from '@chakra-ui/react'; import { createRootRoute, Link, Outlet } from '@tanstack/react-router'; import React from 'react'; +import { useAuth } from '../hooks/auth'; const TanStackRouterDevtools = process.env.NODE_ENV === 'production' @@ -15,25 +16,34 @@ const TanStackRouterDevtools = ); export const Route = createRootRoute({ - component: () => ( - - - - - + component: () => { + const { isAuthenticated, logout } = useAuth(); + return ( + + + + + - - - - - - - + + {!isAuthenticated ? ( + <> + + + + + + + + ) : ( + + )} + +
+ +
-
- - -
- ) + ); + } });