From 2154990079adb2c7accd8a163092fd6482658503 Mon Sep 17 00:00:00 2001 From: Pedro Losas Date: Mon, 11 Nov 2024 21:47:43 +0100 Subject: [PATCH] handle auth --- src/components/layout/Layout.tsx | 6 +++--- src/guards/AuthGuard.tsx | 27 +++++++++++++++++++++++++-- src/services/auth/login.ts | 9 +-------- 3 files changed, 29 insertions(+), 13 deletions(-) diff --git a/src/components/layout/Layout.tsx b/src/components/layout/Layout.tsx index d7957ae..2b8b491 100644 --- a/src/components/layout/Layout.tsx +++ b/src/components/layout/Layout.tsx @@ -1,17 +1,17 @@ import { FC } from 'react'; -// import { Sidebar } from './sidebar/Sidebar'; +import { Sidebar } from '../sidebar/Sidebar'; import { Box, Toolbar } from '@mui/material'; interface LayoutProps { children: React.ReactNode; } -// const drawerWidth = 240; +const drawerWidth = 240; export const Layout: FC = ({ children }) => { return ( - {/* */} + diff --git a/src/guards/AuthGuard.tsx b/src/guards/AuthGuard.tsx index 8c05b54..adc8906 100644 --- a/src/guards/AuthGuard.tsx +++ b/src/guards/AuthGuard.tsx @@ -1,9 +1,32 @@ import { Navigate, Outlet } from 'react-router-dom'; import { PublicRoutes } from '../config/routes'; +import { Layout } from '../components/layout/Layout'; +import { useEffect, useMemo, useState } from 'react'; +import PocketBase from 'pocketbase'; const AuthGuard = () => { - const user = true; - return user ? : ; + const pb = useMemo( + () => new PocketBase(import.meta.env.VITE_BASE_URL_API), + [] + ); + + const [, setToken] = useState(pb.authStore.token); + const [user, setUser] = useState(pb.authStore.model); + + useEffect(() => { + return pb.authStore.onChange((token, model) => { + setToken(token); + setUser(model); + }); + }, [pb.authStore]); + + return user ? ( + + + + ) : ( + + ); }; export default AuthGuard; diff --git a/src/services/auth/login.ts b/src/services/auth/login.ts index 02d9b37..e4c4fce 100644 --- a/src/services/auth/login.ts +++ b/src/services/auth/login.ts @@ -1,7 +1,5 @@ import PocketBase from 'pocketbase'; -const pb = new PocketBase(import.meta.env.VITE_BASE_URL_API); - export interface LoginResponse { record: { avatar: string; @@ -19,6 +17,7 @@ export const login = async ( email: string, password: string ): Promise => { + const pb = new PocketBase(import.meta.env.VITE_BASE_URL_API); const collection = 'users'; try { @@ -26,12 +25,6 @@ export const login = async ( .collection(collection) .authWithPassword(email, password); - document.cookie = pb.authStore.exportToCookie({ - maxAge: 3600000, - httpOnly: false, - }); - - pb.authStore.clear(); return { record: { avatar: authData.record.avatar,