re-implemented JWT auth
This commit is contained in:
parent
c190d368de
commit
b47b0f3752
18 changed files with 390 additions and 174 deletions
83
app/client/hooks/auth.tsx
Normal file
83
app/client/hooks/auth.tsx
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
import { gql } from '@apollo/client';
|
||||
import { Session } from '@generated/types';
|
||||
import { createContext, useContext } from 'react';
|
||||
import { sessionFragment } from '../fragments';
|
||||
import { useToastMutation } from '../hooks/useToastMutation';
|
||||
import { url } from '../main';
|
||||
|
||||
interface AuthContextProps {
|
||||
headers: Session | null;
|
||||
setHeaders: (session: Session) => void;
|
||||
}
|
||||
|
||||
export const AuthContext = createContext<AuthContextProps | null>(null);
|
||||
export const AuthProvider = AuthContext.Provider;
|
||||
|
||||
interface UseAuthOutput extends AuthContextProps {
|
||||
isAuthenticated: boolean;
|
||||
login: (value: { email: string; password: string }) => Promise<Session | null | undefined>;
|
||||
}
|
||||
|
||||
export function useAuth(): UseAuthOutput {
|
||||
const authContext = useContext(AuthContext);
|
||||
const { update: login } = useToastMutation<{ login: Session }>({
|
||||
mutation: loginMutation,
|
||||
successMsg: 'Logged in successfully.'
|
||||
});
|
||||
|
||||
if (!authContext) throw new Error('useAuth must be used within an AuthProvider');
|
||||
|
||||
return {
|
||||
...authContext,
|
||||
isAuthenticated: authContext.headers != null,
|
||||
login: async ({ email, password }: { email: string; password: string }) => {
|
||||
const { data } = await login({
|
||||
variables: {
|
||||
input: {
|
||||
email,
|
||||
password
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (data != null) {
|
||||
authContext.setHeaders(data.login);
|
||||
return data.login;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
interface UseRestAuthOutput {
|
||||
refreshToken: () => Promise<Session | null | undefined>;
|
||||
}
|
||||
|
||||
export function useRestAuth(): UseRestAuthOutput {
|
||||
return {
|
||||
refreshToken: async () => {
|
||||
try {
|
||||
const response = await fetch(`${url}/api/refreshAccessToken`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`[error]: ${response.status}`);
|
||||
}
|
||||
const session = await response.json();
|
||||
return session;
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const loginMutation = gql`
|
||||
mutation AuthLogin($input: LoginInput!) {
|
||||
login(input: $input) {
|
||||
...Session
|
||||
}
|
||||
}
|
||||
|
||||
${sessionFragment}
|
||||
`;
|
||||
|
|
@ -32,7 +32,5 @@ export function useToastMutation<T>(props: UseToastMutationProps): UseToastMutat
|
|||
}
|
||||
});
|
||||
|
||||
return {
|
||||
update
|
||||
};
|
||||
return { update };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,19 +1,24 @@
|
|||
import { ApolloClient, ApolloProvider, HttpLink, InMemoryCache, from } from '@apollo/client';
|
||||
import { loadDevMessages, loadErrorMessages } from '@apollo/client/dev';
|
||||
import { onError } from '@apollo/client/link/error';
|
||||
import { Skeleton } from '@chakra-ui/react';
|
||||
import '@client/assets/styles/index.css';
|
||||
import '@client/assets/styles/nerd-fonts-icons.css';
|
||||
import { Provider } from '@client/components/ui/provider';
|
||||
import { Provider as ChakraProvider } from '@client/components/ui/provider';
|
||||
import { Toaster } from '@client/components/ui/toaster';
|
||||
import { RouterProvider, createRouter } from '@tanstack/react-router';
|
||||
import { StrictMode, createContext, useState } from 'react';
|
||||
import { StrictMode, useEffect, useState } from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { AuthProvider, useRestAuth } from './hooks/auth';
|
||||
|
||||
// TanStackRouter - Import the generated route tree
|
||||
import { Session } from 'inspector';
|
||||
import { Session } from '@generated/types';
|
||||
import { routeTree } from './routeTree.gen';
|
||||
|
||||
// Create a new router instance
|
||||
const router = createRouter({ routeTree });
|
||||
const router = createRouter({
|
||||
routeTree
|
||||
});
|
||||
|
||||
// Register the router instance for type safety
|
||||
declare module '@tanstack/react-router' {
|
||||
|
|
@ -28,35 +33,63 @@ const isProd = MODE === 'prod';
|
|||
|
||||
const HOST = import.meta.env.VITE_HOST || 'localhost';
|
||||
const PORT = import.meta.env.VITE_PORT || '3000';
|
||||
const uri = `https://${HOST}:${PORT}/graphql`;
|
||||
|
||||
// Auth context
|
||||
export const AuthContext = createContext<any>(null);
|
||||
export const url = `https://${HOST}:${PORT}`;
|
||||
const graphql_uri = `${url}/graphql`;
|
||||
|
||||
function App() {
|
||||
const [authHeaders, setAuthHeaders] = useState<Session | null>(null);
|
||||
const AuthProvider = AuthContext.Provider;
|
||||
const [initialLoading, setInitialLoading] = useState<boolean>(true);
|
||||
const { refreshToken } = useRestAuth();
|
||||
|
||||
// if (authHeaders == null) refreshToken();
|
||||
useEffect(() => {
|
||||
const getPreviousSession = async () => {
|
||||
const session = await refreshToken();
|
||||
if (session !== undefined) setAuthHeaders(session);
|
||||
setInitialLoading(false);
|
||||
};
|
||||
if (initialLoading) getPreviousSession();
|
||||
}, []);
|
||||
|
||||
if (initialLoading)
|
||||
return (
|
||||
<StrictMode>
|
||||
<ChakraProvider>
|
||||
<Skeleton />
|
||||
</ChakraProvider>
|
||||
</StrictMode>
|
||||
);
|
||||
|
||||
const httpLink = new HttpLink({
|
||||
uri,
|
||||
uri: graphql_uri,
|
||||
credentials: 'include',
|
||||
headers: authHeaders != null ? { authorization: JSON.stringify(authHeaders) } : undefined
|
||||
});
|
||||
|
||||
const errorLink = onError(({ graphQLErrors, networkError }) => {
|
||||
if (graphQLErrors)
|
||||
graphQLErrors.forEach(({ message, locations, path }) =>
|
||||
console.error(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`)
|
||||
);
|
||||
const errorLink = onError(({ graphQLErrors, networkError, operation, forward }) => {
|
||||
if (graphQLErrors != null && graphQLErrors.length > 0)
|
||||
graphQLErrors.map(async error => {
|
||||
if (error.message.includes('jwt expired')) {
|
||||
const session = await refreshToken();
|
||||
if (session != undefined) setAuthHeaders(session);
|
||||
return forward(operation);
|
||||
}
|
||||
if (!isProd)
|
||||
console.error(
|
||||
`[GraphQlError]: Message: ${error.message}, Location: ${JSON.stringify(error.locations)}, Path: ${error.path}`
|
||||
);
|
||||
});
|
||||
|
||||
if (networkError) console.error(`[Network error]: ${networkError}`);
|
||||
if (networkError != null && graphQLErrors == null) console.error(networkError);
|
||||
});
|
||||
|
||||
if (!isProd) {
|
||||
loadDevMessages();
|
||||
loadErrorMessages();
|
||||
}
|
||||
|
||||
const client = new ApolloClient({
|
||||
uri,
|
||||
link: isProd ? undefined : from([errorLink, httpLink]),
|
||||
uri: graphql_uri,
|
||||
link: from([errorLink, httpLink]),
|
||||
cache: new InMemoryCache(),
|
||||
connectToDevTools: !isProd,
|
||||
credentials: 'include'
|
||||
|
|
@ -66,17 +99,17 @@ function App() {
|
|||
<StrictMode>
|
||||
<AuthProvider
|
||||
value={{
|
||||
authHeaders,
|
||||
headers: authHeaders,
|
||||
setHeaders: (session: Session) => {
|
||||
setAuthHeaders(session);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<ApolloProvider client={client}>
|
||||
<Provider>
|
||||
<ChakraProvider>
|
||||
<Toaster />
|
||||
<RouterProvider router={router} />
|
||||
</Provider>
|
||||
</ChakraProvider>
|
||||
</ApolloProvider>
|
||||
</AuthProvider>
|
||||
</StrictMode>
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { Stack, Text } from '@chakra-ui/react';
|
||||
import { Box, Button, Stack, Text } from '@chakra-ui/react';
|
||||
import { createFileRoute } from '@tanstack/react-router';
|
||||
|
||||
import { gql, useQuery } from '@apollo/client';
|
||||
|
|
@ -10,7 +10,7 @@ export const Route = createFileRoute('/')({
|
|||
});
|
||||
|
||||
function Index() {
|
||||
const { data } = useQuery<BooksManyQuery>(getBooksQuery);
|
||||
const { data, refetch } = useQuery<BooksManyQuery>(getBooksQuery);
|
||||
|
||||
return (
|
||||
<Stack>
|
||||
|
|
@ -27,6 +27,9 @@ function Index() {
|
|||
))}
|
||||
</>
|
||||
)}
|
||||
<Box>
|
||||
<Button onClick={async () => refetch()}>Refetch</Button>
|
||||
</Box>
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,17 +1,12 @@
|
|||
import { gql } from '@apollo/client';
|
||||
import { Heading, Input, Stack } from '@chakra-ui/react';
|
||||
import { Button } from '@client/components/ui/button';
|
||||
import { Field } from '@client/components/ui/field';
|
||||
import { valibotResolver } from '@hookform/resolvers/valibot';
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router';
|
||||
import { Session } from 'inspector';
|
||||
import { useContext } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import * as v from 'valibot';
|
||||
import { PasswordInput } from '../components/ui/password-input';
|
||||
import { sessionFragment } from '../fragments';
|
||||
import { useToastMutation } from '../hooks/useToastMutation';
|
||||
import { AuthContext } from '../main';
|
||||
import { useAuth } from '../hooks/auth';
|
||||
|
||||
export const Route = createFileRoute('/login')({
|
||||
component: LoginComponent
|
||||
|
|
@ -33,10 +28,6 @@ interface FormValues {
|
|||
|
||||
function LoginForm() {
|
||||
const navigate = useNavigate();
|
||||
const { update: login } = useToastMutation<{ login: Session }>({
|
||||
mutation,
|
||||
successMsg: 'Logged in successfully.'
|
||||
});
|
||||
|
||||
const schema = v.pipe(
|
||||
v.object({
|
||||
|
|
@ -51,24 +42,16 @@ function LoginForm() {
|
|||
formState: { errors }
|
||||
} = useForm<FormValues>({ resolver: valibotResolver(schema) });
|
||||
|
||||
const { header, setHeaders } = useContext(AuthContext);
|
||||
if (header != null) navigate({ to: '/' });
|
||||
const { login } = useAuth();
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={handleSubmit(async values => {
|
||||
const { data } = await login({
|
||||
variables: {
|
||||
input: {
|
||||
email: values.email,
|
||||
password: values.password
|
||||
}
|
||||
}
|
||||
const session = await login({
|
||||
email: values.email,
|
||||
password: values.password
|
||||
});
|
||||
if (data != null) {
|
||||
setHeaders(data.login);
|
||||
navigate({ to: '/' });
|
||||
}
|
||||
if (session != null) navigate({ to: '/' });
|
||||
})}
|
||||
>
|
||||
<Stack>
|
||||
|
|
@ -87,13 +70,3 @@ function LoginForm() {
|
|||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
const mutation = gql`
|
||||
mutation AuthLogin($input: LoginInput!) {
|
||||
login(input: $input) {
|
||||
...Session
|
||||
}
|
||||
}
|
||||
|
||||
${sessionFragment}
|
||||
`;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue