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 { Field as ChakraField } from '@chakra-ui/react';
|
||||||
import * as React from "react"
|
import * as React from 'react';
|
||||||
|
|
||||||
export interface FieldProps extends Omit<ChakraField.RootProps, "label"> {
|
export interface FieldProps extends Omit<ChakraField.RootProps, 'label'> {
|
||||||
label?: React.ReactNode
|
label?: React.ReactNode;
|
||||||
helperText?: React.ReactNode
|
helperText?: React.ReactNode;
|
||||||
errorText?: React.ReactNode
|
errorText?: React.ReactNode;
|
||||||
optionalText?: React.ReactNode
|
optionalText?: React.ReactNode;
|
||||||
|
type?: 'text' | 'password';
|
||||||
}
|
}
|
||||||
|
|
||||||
export const Field = React.forwardRef<HTMLDivElement, FieldProps>(
|
export const Field = React.forwardRef<HTMLDivElement, FieldProps>(function Field(props, ref) {
|
||||||
function Field(props, ref) {
|
const { label, children, helperText, errorText, optionalText, ...rest } = props;
|
||||||
const { label, children, helperText, errorText, optionalText, ...rest } =
|
return (
|
||||||
props
|
<ChakraField.Root ref={ref} {...rest}>
|
||||||
return (
|
{label && (
|
||||||
<ChakraField.Root ref={ref} {...rest}>
|
<ChakraField.Label>
|
||||||
{label && (
|
{label}
|
||||||
<ChakraField.Label>
|
<ChakraField.RequiredIndicator fallback={optionalText} />
|
||||||
{label}
|
</ChakraField.Label>
|
||||||
<ChakraField.RequiredIndicator fallback={optionalText} />
|
)}
|
||||||
</ChakraField.Label>
|
{children}
|
||||||
)}
|
{helperText && <ChakraField.HelperText>{helperText}</ChakraField.HelperText>}
|
||||||
{children}
|
{errorText && <ChakraField.ErrorText>{errorText}</ChakraField.ErrorText>}
|
||||||
{helperText && (
|
</ChakraField.Root>
|
||||||
<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 { Provider } from '@client/components/ui/provider';
|
||||||
import { Toaster } from '@client/components/ui/toaster';
|
import { Toaster } from '@client/components/ui/toaster';
|
||||||
import { RouterProvider, createRouter } from '@tanstack/react-router';
|
import { RouterProvider, createRouter } from '@tanstack/react-router';
|
||||||
import { StrictMode } from 'react';
|
import { StrictMode, createContext, useState } from 'react';
|
||||||
import ReactDOM from 'react-dom/client';
|
import ReactDOM from 'react-dom/client';
|
||||||
|
|
||||||
// TanStackRouter - Import the generated route tree
|
// TanStackRouter - Import the generated route tree
|
||||||
import { routeTree } from './routeTree.gen';
|
import { routeTree } from './routeTree.gen';
|
||||||
|
import { Session } from 'inspector';
|
||||||
|
|
||||||
// Create a new router instance
|
// Create a new router instance
|
||||||
const router = createRouter({ routeTree });
|
const router = createRouter({ routeTree });
|
||||||
|
|
@ -20,28 +21,52 @@ declare module '@tanstack/react-router' {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Apollo
|
// Environment
|
||||||
const HOST = import.meta.env.VITE_HOST || 'localhost';
|
const HOST = import.meta.env.VITE_HOST || 'localhost';
|
||||||
const PORT = import.meta.env.VITE_PORT || '3000';
|
const PORT = import.meta.env.VITE_PORT || '3000';
|
||||||
const uri = `http://${HOST}:${PORT}/graphql`;
|
const uri = `http://${HOST}:${PORT}/graphql`;
|
||||||
|
|
||||||
const client = new ApolloClient({
|
// Auth context
|
||||||
uri,
|
export const AuthContext = createContext<any>(null);
|
||||||
cache: new InMemoryCache(),
|
|
||||||
connectToDevTools: true
|
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')!;
|
const rootElement = document.getElementById('root')!;
|
||||||
if (!rootElement.innerHTML) {
|
if (!rootElement.innerHTML) {
|
||||||
const root = ReactDOM.createRoot(rootElement);
|
const root = ReactDOM.createRoot(rootElement);
|
||||||
root.render(
|
root.render(<App />);
|
||||||
<StrictMode>
|
|
||||||
<ApolloProvider client={client}>
|
|
||||||
<Provider>
|
|
||||||
<Toaster />
|
|
||||||
<RouterProvider router={router} />
|
|
||||||
</Provider>
|
|
||||||
</ApolloProvider>
|
|
||||||
</StrictMode>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,12 +3,15 @@ import { Heading, Input, Stack } from '@chakra-ui/react';
|
||||||
import { Button } from '@client/components/ui/button';
|
import { Button } from '@client/components/ui/button';
|
||||||
import { Field } from '@client/components/ui/field';
|
import { Field } from '@client/components/ui/field';
|
||||||
import { valibotResolver } from '@hookform/resolvers/valibot';
|
import { valibotResolver } from '@hookform/resolvers/valibot';
|
||||||
import { createFileRoute } from '@tanstack/react-router';
|
import { createFileRoute, useNavigate } from '@tanstack/react-router';
|
||||||
import { Session } from 'inspector';
|
import { Session } from 'inspector';
|
||||||
|
import { useContext } from 'react';
|
||||||
import { useForm } from 'react-hook-form';
|
import { useForm } from 'react-hook-form';
|
||||||
import * as v from 'valibot';
|
import * as v from 'valibot';
|
||||||
|
import { PasswordInput } from '../components/ui/password-input';
|
||||||
import { sessionFragment } from '../fragments';
|
import { sessionFragment } from '../fragments';
|
||||||
import { useToastMutation } from '../hooks/useToastMutation';
|
import { useToastMutation } from '../hooks/useToastMutation';
|
||||||
|
import { AuthContext } from '../main';
|
||||||
|
|
||||||
export const Route = createFileRoute('/login')({
|
export const Route = createFileRoute('/login')({
|
||||||
component: LoginComponent
|
component: LoginComponent
|
||||||
|
|
@ -29,7 +32,8 @@ interface FormValues {
|
||||||
}
|
}
|
||||||
|
|
||||||
function LoginForm() {
|
function LoginForm() {
|
||||||
const { update: login } = useToastMutation<Session>({
|
const navigate = useNavigate();
|
||||||
|
const { update: login } = useToastMutation<{ login: Session }>({
|
||||||
mutation,
|
mutation,
|
||||||
successMsg: 'Logged in successfully.'
|
successMsg: 'Logged in successfully.'
|
||||||
});
|
});
|
||||||
|
|
@ -47,6 +51,9 @@ function LoginForm() {
|
||||||
formState: { errors }
|
formState: { errors }
|
||||||
} = useForm<FormValues>({ resolver: valibotResolver(schema) });
|
} = useForm<FormValues>({ resolver: valibotResolver(schema) });
|
||||||
|
|
||||||
|
const { header, setHeaders } = useContext(AuthContext);
|
||||||
|
if (header != null) navigate({ to: '/' });
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<form
|
<form
|
||||||
onSubmit={handleSubmit(async values => {
|
onSubmit={handleSubmit(async values => {
|
||||||
|
|
@ -58,7 +65,10 @@ function LoginForm() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
alert(JSON.stringify(data));
|
if (data != null) {
|
||||||
|
setHeaders(data.login);
|
||||||
|
navigate({ to: '/' });
|
||||||
|
}
|
||||||
})}
|
})}
|
||||||
>
|
>
|
||||||
<Stack>
|
<Stack>
|
||||||
|
|
@ -70,7 +80,7 @@ function LoginForm() {
|
||||||
invalid={errors.password != null}
|
invalid={errors.password != null}
|
||||||
errorText={errors.password?.message}
|
errorText={errors.password?.message}
|
||||||
>
|
>
|
||||||
<Input {...register('password')} />
|
<PasswordInput {...register('password')} />
|
||||||
</Field>
|
</Field>
|
||||||
<Button type="submit">Sign in</Button>
|
<Button type="submit">Sign in</Button>
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
|
||||||
|
|
@ -2,9 +2,10 @@ import { gql } from '@apollo/client';
|
||||||
import { Heading, Input, Stack } from '@chakra-ui/react';
|
import { Heading, Input, Stack } from '@chakra-ui/react';
|
||||||
import { Button } from '@client/components/ui/button';
|
import { Button } from '@client/components/ui/button';
|
||||||
import { Field } from '@client/components/ui/field';
|
import { Field } from '@client/components/ui/field';
|
||||||
|
import { PasswordInput } from '@client/components/ui/password-input';
|
||||||
import { Session } from '@generated/types';
|
import { Session } from '@generated/types';
|
||||||
import { valibotResolver } from '@hookform/resolvers/valibot';
|
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 { useForm } from 'react-hook-form';
|
||||||
import * as v from 'valibot';
|
import * as v from 'valibot';
|
||||||
import { useToastMutation } from '../hooks/useToastMutation';
|
import { useToastMutation } from '../hooks/useToastMutation';
|
||||||
|
|
@ -30,7 +31,11 @@ interface FormValues {
|
||||||
}
|
}
|
||||||
|
|
||||||
function SignUpForm() {
|
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(
|
const schema = v.pipe(
|
||||||
v.object({
|
v.object({
|
||||||
|
|
@ -65,7 +70,7 @@ function SignUpForm() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
redirect({
|
navigate({
|
||||||
to: '/login'
|
to: '/login'
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
@ -88,14 +93,14 @@ function SignUpForm() {
|
||||||
invalid={errors.password != null}
|
invalid={errors.password != null}
|
||||||
errorText={errors.password?.message}
|
errorText={errors.password?.message}
|
||||||
>
|
>
|
||||||
<Input {...register('password')} />
|
<PasswordInput {...register('password')} />
|
||||||
</Field>
|
</Field>
|
||||||
<Field
|
<Field
|
||||||
label="Confirm password"
|
label="Confirm password"
|
||||||
invalid={errors.confirm_password != null}
|
invalid={errors.confirm_password != null}
|
||||||
errorText={errors.confirm_password?.message}
|
errorText={errors.confirm_password?.message}
|
||||||
>
|
>
|
||||||
<Input {...register('confirm_password')} />
|
<PasswordInput {...register('confirm_password')} />
|
||||||
</Field>
|
</Field>
|
||||||
<Button type="submit">Submit</Button>
|
<Button type="submit">Submit</Button>
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|
|
||||||
|
|
@ -19,5 +19,6 @@ export async function BooksManyResolver(
|
||||||
__: any,
|
__: any,
|
||||||
{ identity }: IdentityContext
|
{ identity }: IdentityContext
|
||||||
): Promise<Book[]> {
|
): Promise<Book[]> {
|
||||||
|
if (identity == null) throw Error('Unauthorized');
|
||||||
return books;
|
return books;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
import 'dotenv/config';
|
import 'dotenv/config';
|
||||||
import { Request, Response } from 'express';
|
import { Request, Response } from 'express';
|
||||||
import jwt from 'jsonwebtoken';
|
import jwt from 'jsonwebtoken';
|
||||||
|
|
||||||
import { prisma } from './prisma/client';
|
import { prisma } from './prisma/client';
|
||||||
|
import { Session } from '@generated/types';
|
||||||
|
|
||||||
export interface IdentityContext {
|
export interface IdentityContext {
|
||||||
identity?: {
|
identity?: {
|
||||||
|
|
@ -18,14 +18,22 @@ export async function getIdentityContext({
|
||||||
req: Request;
|
req: Request;
|
||||||
res: Response;
|
res: Response;
|
||||||
}): Promise<IdentityContext> {
|
}): Promise<IdentityContext> {
|
||||||
const authHeader = req.headers.authorization;
|
const authHeaders = req.headers.authorization;
|
||||||
if (authHeader == null) return {};
|
if (authHeaders == null) return {};
|
||||||
const token = authHeader.split(' ')[1];
|
|
||||||
|
const session: Session = JSON.parse(authHeaders);
|
||||||
|
console.log(session);
|
||||||
|
const accessToken = session.accessToken;
|
||||||
|
|
||||||
const accessTokenSecret = process.env.ACCESS_TOKEN_SECRET;
|
const accessTokenSecret = process.env.ACCESS_TOKEN_SECRET;
|
||||||
if (accessTokenSecret == null) throw new Error('No `accessToken`.');
|
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({
|
const identity = await prisma.user.findUnique({
|
||||||
where: { id: decoded.userId },
|
where: { id: decoded.userId },
|
||||||
select: {
|
select: {
|
||||||
|
|
|
||||||
1313
package-lock.json
generated
1313
package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -15,7 +15,7 @@
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@apollo/client": "^3.12.2",
|
"@apollo/client": "^3.12.2",
|
||||||
"@apollo/server": "^4.11.2",
|
"@apollo/server": "^4.11.2",
|
||||||
"@chakra-ui/react": "^3.2.3",
|
"@chakra-ui/react": "^3.15.0",
|
||||||
"@chakra-ui/toast": "^7.0.2",
|
"@chakra-ui/toast": "^7.0.2",
|
||||||
"@deftomat/opinionated": "^1.1.3",
|
"@deftomat/opinionated": "^1.1.3",
|
||||||
"@emotion/react": "^11.13.5",
|
"@emotion/react": "^11.13.5",
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue