feat: add auth related utilities
This commit is contained in:
parent
f48aee80a5
commit
3cbb51f8ee
29
src/components/RequireAuth.tsx
Normal file
29
src/components/RequireAuth.tsx
Normal file
@ -0,0 +1,29 @@
|
||||
import type React from "react";
|
||||
import { Link as ReactRouterLink } from "react-router-dom";
|
||||
import { Box, Heading, Link, Text } from "@chakra-ui/react";
|
||||
import { WarningTwoIcon } from "@chakra-ui/icons";
|
||||
|
||||
import { useAuth } from "../hooks/useAuth";
|
||||
|
||||
export const RequireAuth = ({ children }: { children: React.ReactNode }) => {
|
||||
const auth = useAuth();
|
||||
|
||||
if (!auth.token) {
|
||||
return (
|
||||
<Box textAlign="center" py={10} px={6}>
|
||||
<WarningTwoIcon boxSize={"50px"} color={"orange.300"} />
|
||||
<Heading as="h2" size="lg" mt={6} mb={2}>
|
||||
Unauthorized :(
|
||||
</Heading>
|
||||
<Text color={"gray.500"}>
|
||||
<Link as={ReactRouterLink} to="/login" color="teal">
|
||||
Login
|
||||
</Link>{" "}
|
||||
to gain access
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
return children;
|
||||
};
|
8
src/hooks/useAuth.ts
Normal file
8
src/hooks/useAuth.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import { useMemo } from "react";
|
||||
import { selectCurrentUser } from "../features/auth/authSlice";
|
||||
import { useAppSelector } from "./store";
|
||||
|
||||
export const useAuth = () => {
|
||||
const auth = useAppSelector(selectCurrentUser);
|
||||
return useMemo(() => ({ token: auth.token, profile: auth.profile }), [auth]);
|
||||
};
|
@ -1,5 +1,13 @@
|
||||
import { Heading } from "@chakra-ui/react";
|
||||
import { Heading, Link } from "@chakra-ui/react";
|
||||
import { Link as ReactRouterLink } from "react-router-dom";
|
||||
|
||||
export default function HomePage() {
|
||||
return <Heading>Hello World!</Heading>;
|
||||
return (
|
||||
<>
|
||||
<Heading>Hello World!</Heading>
|
||||
<Link as={ReactRouterLink} to="/test/protected">
|
||||
test protected middleware
|
||||
</Link>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
@ -3,6 +3,7 @@ import type { RouteObject } from "react-router-dom";
|
||||
|
||||
import { Root } from "./pages/Root";
|
||||
import { ErrorPage } from "./pages/ErrorPage";
|
||||
import { RequireAuth } from "./components/RequireAuth";
|
||||
|
||||
const HomePage = lazy(() => import("./pages/HomePage"));
|
||||
const LoginPage = lazy(() => import("./pages/LoginPage"));
|
||||
@ -16,6 +17,10 @@ export const router: RouteObject[] = [
|
||||
{ index: true, element: <HomePage /> },
|
||||
{ path: "home", element: <HomePage /> },
|
||||
{ path: "login", element: <LoginPage /> },
|
||||
{
|
||||
path: "/test",
|
||||
children: [{ path: "protected", element: <RequireAuth>Protected</RequireAuth> }],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
Loading…
Reference in New Issue
Block a user