added log out

This commit is contained in:
lnn0q 2025-04-18 15:26:18 +03:00
parent b47b0f3752
commit b5280b70a1
2 changed files with 45 additions and 19 deletions

View file

@ -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<AuthContextProps | null>(null);
@ -16,6 +16,7 @@ export const AuthProvider = AuthContext.Provider;
interface UseAuthOutput extends AuthContextProps {
isAuthenticated: boolean;
login: (value: { email: string; password: string }) => Promise<Session | null | undefined>;
logout: () => Promise<void>;
}
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
}
`;

View file

@ -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,7 +16,9 @@ const TanStackRouterDevtools =
);
export const Route = createRootRoute({
component: () => (
component: () => {
const { isAuthenticated, logout } = useAuth();
return (
<Stack padding={3}>
<Stack flexDirection={'row'} justifyContent={'space-between'}>
<Link to="/">
@ -23,17 +26,24 @@ export const Route = createRootRoute({
</Link>
<Stack flexDirection={'row'}>
{!isAuthenticated ? (
<>
<Link to="/login">
<Button>Sign in</Button>
</Link>
<Link to="/register">
<Button>Sign up</Button>
</Link>
</>
) : (
<Button onClick={async () => logout()}>Log out</Button>
)}
</Stack>
</Stack>
<hr style={{ padding: '4px' }} />
<Outlet />
<TanStackRouterDevtools />
</Stack>
)
);
}
});