implemented session
This commit is contained in:
parent
b6b7cea210
commit
d179b8c7c8
9 changed files with 700 additions and 783 deletions
|
|
@ -1,33 +1,27 @@
|
|||
import { Field as ChakraField } from "@chakra-ui/react"
|
||||
import * as React from "react"
|
||||
import { Field as ChakraField } from '@chakra-ui/react';
|
||||
import * as React from 'react';
|
||||
|
||||
export interface FieldProps extends Omit<ChakraField.RootProps, "label"> {
|
||||
label?: React.ReactNode
|
||||
helperText?: React.ReactNode
|
||||
errorText?: React.ReactNode
|
||||
optionalText?: React.ReactNode
|
||||
export interface FieldProps extends Omit<ChakraField.RootProps, 'label'> {
|
||||
label?: React.ReactNode;
|
||||
helperText?: React.ReactNode;
|
||||
errorText?: React.ReactNode;
|
||||
optionalText?: React.ReactNode;
|
||||
type?: 'text' | 'password';
|
||||
}
|
||||
|
||||
export const Field = React.forwardRef<HTMLDivElement, FieldProps>(
|
||||
function Field(props, ref) {
|
||||
const { label, children, helperText, errorText, optionalText, ...rest } =
|
||||
props
|
||||
return (
|
||||
<ChakraField.Root ref={ref} {...rest}>
|
||||
{label && (
|
||||
<ChakraField.Label>
|
||||
{label}
|
||||
<ChakraField.RequiredIndicator fallback={optionalText} />
|
||||
</ChakraField.Label>
|
||||
)}
|
||||
{children}
|
||||
{helperText && (
|
||||
<ChakraField.HelperText>{helperText}</ChakraField.HelperText>
|
||||
)}
|
||||
{errorText && (
|
||||
<ChakraField.ErrorText>{errorText}</ChakraField.ErrorText>
|
||||
)}
|
||||
</ChakraField.Root>
|
||||
)
|
||||
},
|
||||
)
|
||||
export const Field = React.forwardRef<HTMLDivElement, FieldProps>(function Field(props, ref) {
|
||||
const { label, children, helperText, errorText, optionalText, ...rest } = props;
|
||||
return (
|
||||
<ChakraField.Root ref={ref} {...rest}>
|
||||
{label && (
|
||||
<ChakraField.Label>
|
||||
{label}
|
||||
<ChakraField.RequiredIndicator fallback={optionalText} />
|
||||
</ChakraField.Label>
|
||||
)}
|
||||
{children}
|
||||
{helperText && <ChakraField.HelperText>{helperText}</ChakraField.HelperText>}
|
||||
{errorText && <ChakraField.ErrorText>{errorText}</ChakraField.ErrorText>}
|
||||
</ChakraField.Root>
|
||||
);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -0,0 +1,3 @@
|
|||
interface UseIdentityProps {}
|
||||
|
||||
export function useIdentity(props: UseIdentityProps) {}
|
||||
|
|
@ -4,11 +4,12 @@ import '@client/assets/styles/nerd-fonts-icons.css';
|
|||
import { Provider } from '@client/components/ui/provider';
|
||||
import { Toaster } from '@client/components/ui/toaster';
|
||||
import { RouterProvider, createRouter } from '@tanstack/react-router';
|
||||
import { StrictMode } from 'react';
|
||||
import { StrictMode, createContext, useState } from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
|
||||
// TanStackRouter - Import the generated route tree
|
||||
import { routeTree } from './routeTree.gen';
|
||||
import { Session } from 'inspector';
|
||||
|
||||
// Create a new router instance
|
||||
const router = createRouter({ routeTree });
|
||||
|
|
@ -20,28 +21,52 @@ declare module '@tanstack/react-router' {
|
|||
}
|
||||
}
|
||||
|
||||
// Apollo
|
||||
// Environment
|
||||
const HOST = import.meta.env.VITE_HOST || 'localhost';
|
||||
const PORT = import.meta.env.VITE_PORT || '3000';
|
||||
const uri = `http://${HOST}:${PORT}/graphql`;
|
||||
|
||||
const client = new ApolloClient({
|
||||
uri,
|
||||
cache: new InMemoryCache(),
|
||||
connectToDevTools: true
|
||||
});
|
||||
// Auth context
|
||||
export const AuthContext = createContext<any>(null);
|
||||
|
||||
function App() {
|
||||
const sessionRaw = localStorage.getItem('session');
|
||||
const session: Session | null = sessionRaw !== null ? JSON.parse(sessionRaw) : null;
|
||||
|
||||
const [authHeaders, setAuthHeaders] = useState<Session | null>(session);
|
||||
const AuthProvider = AuthContext.Provider;
|
||||
|
||||
const client = new ApolloClient({
|
||||
uri,
|
||||
cache: new InMemoryCache(),
|
||||
connectToDevTools: true,
|
||||
headers: authHeaders != null ? { authorization: JSON.stringify(authHeaders) } : undefined
|
||||
});
|
||||
|
||||
return (
|
||||
<StrictMode>
|
||||
<AuthProvider
|
||||
value={{
|
||||
authHeaders,
|
||||
setHeaders: (session: Session) => {
|
||||
localStorage.setItem('session', JSON.stringify(session));
|
||||
setAuthHeaders(session);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<ApolloProvider client={client}>
|
||||
<Provider>
|
||||
<Toaster />
|
||||
<RouterProvider router={router} />
|
||||
</Provider>
|
||||
</ApolloProvider>
|
||||
</AuthProvider>
|
||||
</StrictMode>
|
||||
);
|
||||
}
|
||||
|
||||
const rootElement = document.getElementById('root')!;
|
||||
if (!rootElement.innerHTML) {
|
||||
const root = ReactDOM.createRoot(rootElement);
|
||||
root.render(
|
||||
<StrictMode>
|
||||
<ApolloProvider client={client}>
|
||||
<Provider>
|
||||
<Toaster />
|
||||
<RouterProvider router={router} />
|
||||
</Provider>
|
||||
</ApolloProvider>
|
||||
</StrictMode>
|
||||
);
|
||||
root.render(<App />);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,12 +3,15 @@ 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 } from '@tanstack/react-router';
|
||||
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';
|
||||
|
||||
export const Route = createFileRoute('/login')({
|
||||
component: LoginComponent
|
||||
|
|
@ -29,7 +32,8 @@ interface FormValues {
|
|||
}
|
||||
|
||||
function LoginForm() {
|
||||
const { update: login } = useToastMutation<Session>({
|
||||
const navigate = useNavigate();
|
||||
const { update: login } = useToastMutation<{ login: Session }>({
|
||||
mutation,
|
||||
successMsg: 'Logged in successfully.'
|
||||
});
|
||||
|
|
@ -47,6 +51,9 @@ function LoginForm() {
|
|||
formState: { errors }
|
||||
} = useForm<FormValues>({ resolver: valibotResolver(schema) });
|
||||
|
||||
const { header, setHeaders } = useContext(AuthContext);
|
||||
if (header != null) navigate({ to: '/' });
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={handleSubmit(async values => {
|
||||
|
|
@ -58,7 +65,10 @@ function LoginForm() {
|
|||
}
|
||||
}
|
||||
});
|
||||
alert(JSON.stringify(data));
|
||||
if (data != null) {
|
||||
setHeaders(data.login);
|
||||
navigate({ to: '/' });
|
||||
}
|
||||
})}
|
||||
>
|
||||
<Stack>
|
||||
|
|
@ -70,7 +80,7 @@ function LoginForm() {
|
|||
invalid={errors.password != null}
|
||||
errorText={errors.password?.message}
|
||||
>
|
||||
<Input {...register('password')} />
|
||||
<PasswordInput {...register('password')} />
|
||||
</Field>
|
||||
<Button type="submit">Sign in</Button>
|
||||
</Stack>
|
||||
|
|
|
|||
|
|
@ -2,9 +2,10 @@ 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 { PasswordInput } from '@client/components/ui/password-input';
|
||||
import { Session } from '@generated/types';
|
||||
import { valibotResolver } from '@hookform/resolvers/valibot';
|
||||
import { createFileRoute, redirect } from '@tanstack/react-router';
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import * as v from 'valibot';
|
||||
import { useToastMutation } from '../hooks/useToastMutation';
|
||||
|
|
@ -30,7 +31,11 @@ interface FormValues {
|
|||
}
|
||||
|
||||
function SignUpForm() {
|
||||
const { update: signUp } = useToastMutation<Session>({ mutation });
|
||||
const navigate = useNavigate();
|
||||
const { update: signUp } = useToastMutation<Session>({
|
||||
mutation,
|
||||
successMsg: 'Account created successfully'
|
||||
});
|
||||
|
||||
const schema = v.pipe(
|
||||
v.object({
|
||||
|
|
@ -65,7 +70,7 @@ function SignUpForm() {
|
|||
}
|
||||
}
|
||||
});
|
||||
redirect({
|
||||
navigate({
|
||||
to: '/login'
|
||||
});
|
||||
});
|
||||
|
|
@ -88,14 +93,14 @@ function SignUpForm() {
|
|||
invalid={errors.password != null}
|
||||
errorText={errors.password?.message}
|
||||
>
|
||||
<Input {...register('password')} />
|
||||
<PasswordInput {...register('password')} />
|
||||
</Field>
|
||||
<Field
|
||||
label="Confirm password"
|
||||
invalid={errors.confirm_password != null}
|
||||
errorText={errors.confirm_password?.message}
|
||||
>
|
||||
<Input {...register('confirm_password')} />
|
||||
<PasswordInput {...register('confirm_password')} />
|
||||
</Field>
|
||||
<Button type="submit">Submit</Button>
|
||||
</Stack>
|
||||
|
|
|
|||
|
|
@ -19,5 +19,6 @@ export async function BooksManyResolver(
|
|||
__: any,
|
||||
{ identity }: IdentityContext
|
||||
): Promise<Book[]> {
|
||||
if (identity == null) throw Error('Unauthorized');
|
||||
return books;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import 'dotenv/config';
|
||||
import { Request, Response } from 'express';
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
import { prisma } from './prisma/client';
|
||||
import { Session } from '@generated/types';
|
||||
|
||||
export interface IdentityContext {
|
||||
identity?: {
|
||||
|
|
@ -18,14 +18,22 @@ export async function getIdentityContext({
|
|||
req: Request;
|
||||
res: Response;
|
||||
}): Promise<IdentityContext> {
|
||||
const authHeader = req.headers.authorization;
|
||||
if (authHeader == null) return {};
|
||||
const token = authHeader.split(' ')[1];
|
||||
const authHeaders = req.headers.authorization;
|
||||
if (authHeaders == null) return {};
|
||||
|
||||
const session: Session = JSON.parse(authHeaders);
|
||||
console.log(session);
|
||||
const accessToken = session.accessToken;
|
||||
|
||||
const accessTokenSecret = process.env.ACCESS_TOKEN_SECRET;
|
||||
if (accessTokenSecret == null) throw new Error('No `accessToken`.');
|
||||
|
||||
const decoded = jwt.verify(token, accessTokenSecret) as { userId: string };
|
||||
const decoded = jwt.verify(accessToken, accessTokenSecret) as {
|
||||
userId: string;
|
||||
iat: number;
|
||||
exp: number;
|
||||
};
|
||||
|
||||
const identity = await prisma.user.findUnique({
|
||||
where: { id: decoded.userId },
|
||||
select: {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue