add useAuth hook to route depending on auth status

This commit is contained in:
Guillaume Dorce 2023-09-10 13:59:58 +02:00
parent 8695b27c83
commit bf75645322
4 changed files with 45 additions and 25 deletions

View File

@ -1,7 +1,8 @@
import { createContext } from "preact";
import Login from "./Login";
import PocketBase from 'pocketbase';
import { useContext, useState } from "preact/hooks";
import { useContext, useEffect, useState } from "preact/hooks";
import Home from "./Members/Home";
const pb = new PocketBase(import.meta.env.PUBLIC_PB_API);
export const Pb = createContext(pb);
@ -12,22 +13,46 @@ export const Router = createContext({
},
});
function Fake() {
export function useAuth() {
const pb = useContext(Pb);
const router = useContext(Router);
const handleClick = () => {
router.navigate('/login');
const [isAuth, setIsAuth] = useState(pb.authStore.isValid);
const login = async (email: string, password: string) => {
try {
await pb.collection('users').authWithPassword(email, password);
router.navigate('/');
setIsAuth(true)
} catch (error) {
return error;
}
}
return (
<div className="flex min-h-full flex-col justify-center px-6 py-12 lg:px-8">
<h1 className="text-2xl font-bold leading-9 tracking-tight text-gray-900">Fake</h1>
<button onClick={handleClick}>Go to login</button>
</div>
)
const logout = () => {
try {
pb.authStore.clear()
setIsAuth(false)
} catch (error) {
return error;
}
}
return {
isAuth,
login,
logout,
}
}
export default function EspaceMembres() {
const [route, setRoute] = useState('/');
const { isAuth } = useAuth();
useEffect(() => {
if (!isAuth) {
setRoute('/login');
}
}, [isAuth]);
const navigate = (path: string) => {
setRoute(path);
@ -39,7 +64,7 @@ export default function EspaceMembres() {
navigate,
}}>
{{
'/': <Fake />,
'/': <Home />,
'/login': <Login />,
}[route]}
</Router.Provider>

View File

@ -1,26 +1,14 @@
import { type TargetedEvent } from "preact/compat"
import { useContext } from "preact/compat"
import { Pb, Router } from "./EspaceMembres"
import { useAuth } from "./EspaceMembres";
export default function Login() {
const pb = useContext(Pb);
const router = useContext(Router);
const { login } = useAuth();
const handleSubmit = (event: TargetedEvent<HTMLFormElement>) => {
event.preventDefault()
login(event.currentTarget.email.value, event.currentTarget.password.value)
}
const login = async (email: string, password: string) => {
try {
await pb.collection('users').authWithPassword(email, password);
router.navigate('/');
} catch (error) {
if (error instanceof Error)
console.error(error.message);
}
}
return (
<div className="flex min-h-full flex-col justify-center px-6 py-12 lg:px-8">
<div className="sm:mx-auto sm:w-full sm:max-w-sm">

View File

@ -0,0 +1,7 @@
export default function Home() {
return (
<>
<h1 className="text-2xl font-bold leading-9 tracking-tight text-gray-900">Bienvenue sur votre espace membre</h1>
</>
)
}

View File