refactor(dashboard-v2): move access guards outside of SWRConfig
This commit is contained in:
parent
51952c88ed
commit
2c2a1259d3
|
@ -1,4 +1,5 @@
|
|||
import * as React from "react";
|
||||
import { SWRConfig } from "swr";
|
||||
import "@fontsource/sora/300.css"; // light
|
||||
import "@fontsource/sora/400.css"; // normal
|
||||
import "@fontsource/sora/500.css"; // medium
|
||||
|
@ -6,6 +7,7 @@ import "@fontsource/sora/600.css"; // semibold
|
|||
import "@fontsource/source-sans-pro/400.css"; // normal
|
||||
import "@fontsource/source-sans-pro/600.css"; // semibold
|
||||
import "./src/styles/global.css";
|
||||
import swrConfig from "./src/lib/swrConfig";
|
||||
import { MODAL_ROOT_ID } from "./src/components/Modal";
|
||||
import { PortalSettingsProvider } from "./src/contexts/portal-settings";
|
||||
|
||||
|
@ -13,10 +15,12 @@ export function wrapPageElement({ element, props }) {
|
|||
const Layout = element.type.Layout ?? React.Fragment;
|
||||
return (
|
||||
<PortalSettingsProvider>
|
||||
<SWRConfig value={swrConfig}>
|
||||
<Layout {...props}>
|
||||
{element}
|
||||
<div id={MODAL_ROOT_ID} />
|
||||
</Layout>
|
||||
</SWRConfig>
|
||||
</PortalSettingsProvider>
|
||||
);
|
||||
}
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
import * as React from "react";
|
||||
import { SWRConfig } from "swr";
|
||||
import "@fontsource/sora/300.css"; // light
|
||||
import "@fontsource/sora/400.css"; // normal
|
||||
import "@fontsource/sora/500.css"; // medium
|
||||
|
@ -6,6 +7,7 @@ import "@fontsource/sora/600.css"; // semibold
|
|||
import "@fontsource/source-sans-pro/400.css"; // normal
|
||||
import "@fontsource/source-sans-pro/600.css"; // semibold
|
||||
import "./src/styles/global.css";
|
||||
import swrConfig from "./src/lib/swrConfig";
|
||||
import { MODAL_ROOT_ID } from "./src/components/Modal";
|
||||
import { PortalSettingsProvider } from "./src/contexts/portal-settings";
|
||||
|
||||
|
@ -13,10 +15,12 @@ export function wrapPageElement({ element, props }) {
|
|||
const Layout = element.type.Layout ?? React.Fragment;
|
||||
return (
|
||||
<PortalSettingsProvider>
|
||||
<SWRConfig value={swrConfig}>
|
||||
<Layout {...props}>
|
||||
{element}
|
||||
<div id={MODAL_ROOT_ID} />
|
||||
</Layout>
|
||||
</SWRConfig>
|
||||
</PortalSettingsProvider>
|
||||
);
|
||||
}
|
||||
|
|
|
@ -97,7 +97,7 @@ export const NavBar = () => {
|
|||
as="button"
|
||||
onClick={onLogout}
|
||||
activeClassName="text-primary"
|
||||
className="cursor-pointer"
|
||||
className="cursor-pointer w-full"
|
||||
icon={LockClosedIcon}
|
||||
label="Log out"
|
||||
/>
|
||||
|
|
|
@ -16,7 +16,7 @@ const fetcher = async (path) => {
|
|||
};
|
||||
|
||||
export const PortalSettingsProvider = ({ children }) => {
|
||||
const { data, error } = useSWRImmutable("/__internal/do/not/use/accounts", fetcher);
|
||||
const { data, error } = useSWRImmutable("__internal/do/not/use/accounts", fetcher);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [settings, setSettings] = useState(defaultSettings);
|
||||
|
||||
|
|
|
@ -1,17 +1,41 @@
|
|||
import { navigate } from "gatsby";
|
||||
import { useEffect, useState } from "react";
|
||||
import useSWRImmutable from "swr/immutable";
|
||||
|
||||
import { UnauthorizedError } from "../../lib/swrConfig";
|
||||
import { FullScreenLoadingIndicator } from "../../components/LoadingIndicator";
|
||||
import { UserContext } from "./UserContext";
|
||||
|
||||
export const UserProvider = ({ children }) => {
|
||||
export const UserProvider = ({ children, allowGuests = false, allowAuthenticated = true }) => {
|
||||
const { data: user, error, mutate } = useSWRImmutable("user");
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
if (user || error) {
|
||||
const guard = async () => {
|
||||
if (user) {
|
||||
if (!allowAuthenticated) {
|
||||
navigate("/");
|
||||
} else {
|
||||
setLoading(false);
|
||||
}
|
||||
} else if (error) {
|
||||
if (error instanceof UnauthorizedError && !allowGuests) {
|
||||
await navigate(`/auth/login?return_to=${encodeURIComponent(window.location.href)}`);
|
||||
} else {
|
||||
setLoading(false);
|
||||
}
|
||||
} else if (user === null) {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [user, error]);
|
||||
|
||||
return <UserContext.Provider value={{ user, error, loading, mutate }}>{children}</UserContext.Provider>;
|
||||
};
|
||||
|
||||
guard();
|
||||
}, [user, error, allowGuests, allowAuthenticated]);
|
||||
|
||||
return (
|
||||
<UserContext.Provider value={{ user, error, loading, mutate }}>
|
||||
{loading && <FullScreenLoadingIndicator />}
|
||||
{!loading && children}
|
||||
</UserContext.Provider>
|
||||
);
|
||||
};
|
||||
|
|
|
@ -1,9 +1,7 @@
|
|||
import * as React from "react";
|
||||
import styled from "styled-components";
|
||||
import { SWRConfig } from "swr";
|
||||
|
||||
import { UserProvider } from "../contexts/user";
|
||||
import { guestsOnly, allUsers } from "../lib/swrConfig";
|
||||
|
||||
const Layout = styled.div.attrs({
|
||||
className: "min-h-screen w-screen bg-black flex",
|
||||
|
@ -22,12 +20,11 @@ const Content = styled.div.attrs({
|
|||
})``;
|
||||
|
||||
const AuthLayout =
|
||||
(swrConfig) =>
|
||||
({ children }) => {
|
||||
return (
|
||||
(userProviderProps) =>
|
||||
({ children }) =>
|
||||
(
|
||||
<>
|
||||
<SWRConfig value={swrConfig}>
|
||||
<UserProvider>
|
||||
<UserProvider {...userProviderProps}>
|
||||
<Layout>
|
||||
<SloganContainer className="pl-20 pr-20 lg:pr-30 xl:pr-40">
|
||||
<div className="">
|
||||
|
@ -39,12 +36,16 @@ const AuthLayout =
|
|||
<Content>{children}</Content>
|
||||
</Layout>
|
||||
</UserProvider>
|
||||
</SWRConfig>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
// Some pages (e.g. email confirmation) need to be accessible to both logged-in and guest users.
|
||||
export const AllUsersAuthLayout = AuthLayout(allUsers);
|
||||
export const AllUsersAuthLayout = AuthLayout({
|
||||
allowGuests: true,
|
||||
allowAuthenticated: true,
|
||||
});
|
||||
|
||||
export default AuthLayout(guestsOnly);
|
||||
export default AuthLayout({
|
||||
allowGuests: true,
|
||||
allowAuthenticated: false,
|
||||
});
|
||||
|
|
|
@ -1,8 +1,5 @@
|
|||
import * as React from "react";
|
||||
import styled from "styled-components";
|
||||
import { SWRConfig } from "swr";
|
||||
|
||||
import { authenticatedOnly } from "../lib/swrConfig";
|
||||
|
||||
import { PageContainer } from "../components/PageContainer";
|
||||
import { NavBar } from "../components/NavBar";
|
||||
|
@ -30,22 +27,16 @@ const Layout = ({ children }) => {
|
|||
);
|
||||
};
|
||||
|
||||
const DashboardLayout = ({ children }) => {
|
||||
return (
|
||||
const DashboardLayout = ({ children }) => (
|
||||
<>
|
||||
<SWRConfig value={authenticatedOnly}>
|
||||
<UserProvider>
|
||||
<Layout>
|
||||
<NavBar />
|
||||
<PageContainer>
|
||||
<main className="mt-14">{children}</main>
|
||||
</PageContainer>
|
||||
<PageContainer className="mt-2 md:mt-14">{children}</PageContainer>
|
||||
<Footer />
|
||||
</Layout>
|
||||
</UserProvider>
|
||||
</SWRConfig>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default DashboardLayout;
|
||||
|
|
|
@ -1,43 +1,12 @@
|
|||
import * as React from "react";
|
||||
import { Link } from "gatsby";
|
||||
import styled from "styled-components";
|
||||
import { SWRConfig } from "swr";
|
||||
|
||||
import { authenticatedOnly } from "../lib/swrConfig";
|
||||
|
||||
import { PageContainer } from "../components/PageContainer";
|
||||
import { NavBar } from "../components/NavBar";
|
||||
import { Footer } from "../components/Footer";
|
||||
import { UserProvider, useUser } from "../contexts/user";
|
||||
import { ContainerLoadingIndicator } from "../components/LoadingIndicator";
|
||||
|
||||
const Wrapper = styled.div.attrs({
|
||||
className: "min-h-screen overflow-hidden",
|
||||
})`
|
||||
background-image: url(/images/dashboard-bg.svg);
|
||||
background-position: center -280px;
|
||||
background-repeat: no-repeat;
|
||||
`;
|
||||
|
||||
const Layout = ({ children }) => {
|
||||
const { user } = useUser();
|
||||
|
||||
// Prevent from flashing the dashboard screen to unauthenticated users.
|
||||
return (
|
||||
<Wrapper>
|
||||
{!user && (
|
||||
<div className="fixed inset-0 flex justify-center items-center bg-palette-100/50">
|
||||
<ContainerLoadingIndicator className="!text-palette-200/50" />
|
||||
</div>
|
||||
)}
|
||||
{user && <>{children}</>}
|
||||
</Wrapper>
|
||||
);
|
||||
};
|
||||
import DashboardLayout from "./DashboardLayout";
|
||||
|
||||
const Sidebar = () => (
|
||||
<aside className="w-full lg:w-48 bg-white text-sm font-sans font-light text-palette-600 shrink-0">
|
||||
<nav>
|
||||
<aside className="w-full lg:w-48 text-sm font-sans font-light text-palette-600 shrink-0">
|
||||
<nav className="bg-white">
|
||||
<SidebarLink activeClassName="!border-l-primary" to="/settings">
|
||||
Account
|
||||
</SidebarLink>
|
||||
|
@ -55,7 +24,7 @@ const Sidebar = () => (
|
|||
);
|
||||
|
||||
const SidebarLink = styled(Link).attrs({
|
||||
className: `h-12 py-3 px-6 h-full w-full flex
|
||||
className: `h-12 py-3 px-6 w-full flex
|
||||
border-l-2 border-l-palette-200
|
||||
border-b border-b-palette-100 last:border-b-transparent`,
|
||||
})``;
|
||||
|
@ -67,21 +36,13 @@ const Content = styled.main.attrs({
|
|||
`;
|
||||
|
||||
const UserSettingsLayout = ({ children }) => (
|
||||
<SWRConfig value={authenticatedOnly}>
|
||||
<UserProvider>
|
||||
<Layout>
|
||||
<NavBar />
|
||||
<PageContainer className="mt-2 md:mt-14">
|
||||
<DashboardLayout>
|
||||
<h6 className="hidden md:block mb-2 text-palette-400">Settings</h6>
|
||||
<div className="flex flex-col lg:flex-row">
|
||||
<Sidebar />
|
||||
<Content className="lg:w-settings-lg xl:w-settings-xl">{children}</Content>
|
||||
</div>
|
||||
</PageContainer>
|
||||
<Footer />
|
||||
</Layout>
|
||||
</UserProvider>
|
||||
</SWRConfig>
|
||||
</DashboardLayout>
|
||||
);
|
||||
|
||||
export default UserSettingsLayout;
|
||||
|
|
|
@ -1,39 +1,22 @@
|
|||
import { navigate } from "gatsby";
|
||||
import { StatusCodes } from "http-status-codes";
|
||||
|
||||
// TODO: portal-aware URL
|
||||
const baseUrl = process.env.NODE_ENV !== "production" ? "/api" : "https://account.skynetpro.net/api";
|
||||
export class UnauthorizedError extends Error {}
|
||||
|
||||
const redirectUnauthenticated = (key) =>
|
||||
fetch(`${baseUrl}/${key}`).then((response) => {
|
||||
if (response.status === StatusCodes.UNAUTHORIZED) {
|
||||
navigate(`/auth/login?return_to=${encodeURIComponent(window.location.href)}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
return response.json();
|
||||
});
|
||||
|
||||
const redirectAuthenticated = (key) =>
|
||||
fetch(`${baseUrl}/${key}`).then(async (response) => {
|
||||
const config = {
|
||||
fetcher: (key) =>
|
||||
fetch(`/api/${key}`).then(async (response) => {
|
||||
if (response.ok) {
|
||||
await navigate("/");
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// If there was an error, let's throw so useSWR's "error" property is populated instead "data".
|
||||
const data = await response.json();
|
||||
throw new Error(data?.message || `Error occured when trying to fetch: ${key}`);
|
||||
});
|
||||
|
||||
export const allUsers = {
|
||||
fetcher: (key) => fetch(`${baseUrl}/${key}`).then((response) => response.json()),
|
||||
if (response.status === StatusCodes.UNAUTHORIZED) {
|
||||
throw new UnauthorizedError(data?.message || "Unauthorized");
|
||||
}
|
||||
|
||||
throw new Error(data?.message || `Error occurred when trying to fetch: ${key}`);
|
||||
}),
|
||||
};
|
||||
|
||||
export const authenticatedOnly = {
|
||||
fetcher: redirectUnauthenticated,
|
||||
};
|
||||
|
||||
export const guestsOnly = {
|
||||
fetcher: redirectAuthenticated,
|
||||
};
|
||||
export default config;
|
||||
|
|
Reference in New Issue