Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 26 additions & 3 deletions src/components/Auth/index.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
// TODO: This can now be deleted
// the cookie handling should be done in AuthProvider
// and project resolution in the ProjectProvider
'use client';

import { routes } from '@fleek-platform/utils-routes';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { constants } from '../../constants';
import { matchesPathname } from '../../utils/matchesPathname';
import { FleekLogo } from '../FleekLogo/FleekLogo';

import type { FC, ReactNode } from 'react';

Expand All @@ -18,26 +20,47 @@ export const Auth: FC<AuthProps> = ({ children }) => {
const [isChecking, setIsChecking] = useState(true);

useEffect(() => {
console.log('[debug] Auth: useEffect: deps router: 1');

const checkAuth = () => {
console.log('[debug] Auth: checkAuth: 1');
setIsChecking(true);

const authToken = document.cookie
.split('; ')
.find((row) => row.startsWith('authProviderToken='))
?.split('=')[1];

const projectId =
document.cookie
.split('; ')
.find((row) => row.startsWith('projectId='))
?.split('=')[1] || constants.DEFAULT_PROJECT_ID;
?.split('=')[1];

console.log(`[debug] Auth: checkAuth: ${JSON.stringify({
authToken,
projectId,
})}`);

const hasAuthentication = Boolean(authToken);
const currentPath = window.location.pathname;

console.log(`[debug] Auth: checkAuth: ${JSON.stringify({
hasAuthentication,
currentPath,
})}`);

if (hasAuthentication && currentPath === routes.home()) {
router.push(routes.project.home({ projectId }));
console.log(`[debug] Auth: checkAuth: hasAuth and is path home`);

router.push(routes.project.home({ projectId }));
setIsChecking(false);

return;
}

// TODO: The dashboard should not have public routes
// it's membership only
const isPublicRoute = Boolean(
constants.PUBLIC_ROUTES.find((route) =>
matchesPathname(route, currentPath),
Expand Down
2 changes: 2 additions & 0 deletions src/components/ftw/RootLayout/RootLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,8 @@ const Sidebar: React.FC<SidebarProps> = ({
// on the client side, show versions if not prod or user is internal
if (
!isServerSide() &&
// TODO: This shouldn't be hard-typed
// e.g. staging vs prd URLs
(location.hostname !== 'app.fleek.xyz' || flags.isInternalUser)
) {
setShowVersion(true);
Expand Down
4 changes: 2 additions & 2 deletions src/fragments/App/Navbar/NavbarCombined.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import { NavbarProject } from './NavbarProject';
import { NavbarUnauthenticated } from './NavbarUnauthenticated';

export const NavbarCombined: React.FC = () => {
const session = useSessionContext(true);
const { loading, auth: { accessToken } } = useSessionContext(true);

if (session.loading || session.auth.token) {
if (loading || accessToken) {
return <NavbarProject />;
}

Expand Down
10 changes: 5 additions & 5 deletions src/fragments/IpfsPropagation/Layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ import { App } from '../App/App';
export const IpfsPropagationLayout: React.FC<ChildrenProps> = ({
children,
}) => {
const session = useSessionContext();
const { loading, auth: { accessToken }} = useSessionContext();
const navItems = useMainNavigationItems();

if (!session.auth.token) {
if (!accessToken) {
return (
<>
<LayoutHead title={LayoutHead.titles.ipfsPropagation} />
Expand All @@ -42,7 +42,7 @@ export const IpfsPropagationLayout: React.FC<ChildrenProps> = ({
<RootLayout.Head title={LayoutHead.titles.ipfsPropagation} />
<RootLayout.Page
slotSidebar={<ProjectDropdown />}
isNavigationLoading={session.loading}
isNavigationLoading={loading}
navigation={navItems}
breadcrumbs={breadcrumbs}
>
Expand All @@ -53,9 +53,9 @@ export const IpfsPropagationLayout: React.FC<ChildrenProps> = ({
};

const Content: React.FC<ChildrenProps> = ({ children }) => {
const session = useSessionContext();
const { auth: { accessToken } } = useSessionContext();

if (session.auth.token) {
if (accessToken) {
return <App.Content>{children}</App.Content>;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ import { ActionBox } from '@/components';
import { useSessionContext } from '@/providers/SessionProvider';

export const CreateGatewayButton: React.FC = () => {
const session = useSessionContext();
const { auth: { accessToken, login } } = useSessionContext();

const hasToken = Boolean(session.auth.token);
const hasToken = Boolean(accessToken);

const handleClick = () => {
if (!hasToken) {
session.auth.login(
login(
'dynamic',
routes.project.settings.privateGateways({ projectId: 'project' }),
);
Expand Down
8 changes: 4 additions & 4 deletions src/fragments/Migration/Layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ export type Layout = React.PropsWithChildren<{
}>;

export const Layout: React.FC<Layout> = ({ children }) => {
const session = useSessionContext();
const { error, auth: { login, accessToken }, loading } = useSessionContext();

const handleLogIn = () => {
if (!session.error && !session.loading && !session.auth.token) {
session.auth.login('dynamic', routes.migration());
if (!error && !loading && !accessToken) {
login('dynamic', routes.migration());
}
};

Expand All @@ -26,7 +26,7 @@ export const Layout: React.FC<Layout> = ({ children }) => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

if (session.auth.token) {
if (accessToken) {
return (
<>
<LayoutHead title={LayoutHead.titles.migration} />
Expand Down
4 changes: 2 additions & 2 deletions src/fragments/Migration/Steps/Step1.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ import { useMigrationContext } from '../Migration.context';
import { MigrationStyles as S } from '../Migration.styles';

export const Step1: React.FC = () => {
const session = useSessionContext();
const { auth: { accessToken } } = useSessionContext();
const {
isStep1Loading: isLoading,
handleBeginMigration,
isSubmittingMigration,
migrationToken,
} = useMigrationContext();

const isDisabled = !session.auth.token || isLoading || !migrationToken;
const isDisabled = !accessToken || isLoading || !migrationToken;

return (
<S.Content.Container>
Expand Down
13 changes: 12 additions & 1 deletion src/fragments/Projects/Layout.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useMemo, memo } from 'react';
import { ProjectDropdown, RootLayout } from '@/components';
import { useMainNavigationItems } from '@/hooks/useMainNavigationItems';
import { useSessionContext } from '@/providers/SessionProvider';
Expand All @@ -6,9 +7,17 @@ export type Layout = React.PropsWithChildren<{
nav?: React.ReactNode | React.ReactNode[];
}>;

// TODO: When clicking outside the menu, e.g. right side
// content area, this component re-renders. Why?
export const Layout: React.FC<Layout> = ({ children, nav: pageNavContent }) => {
const session = useSessionContext(true);
const navigation = useMainNavigationItems();
const navigationItems = useMainNavigationItems();
// TODO: The memo won't be effective as the nav items
// has the URL attribute which includes diff projectid
// per navigation selection
const navigation = useMemo(() => navigationItems, [navigationItems]);

console.log('[debug] Layout: re-render: 1', JSON.stringify(navigation))

return (
<RootLayout.Container>
Expand All @@ -26,3 +35,5 @@ export const Layout: React.FC<Layout> = ({ children, nav: pageNavContent }) => {
</RootLayout.Container>
);
};

Layout.displayName = 'Layout';
6 changes: 3 additions & 3 deletions src/fragments/Template/List/Hero/Hero.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,12 @@ export const Hero: React.FC = () => {
};

const SubmitTemplateButton: React.FC = () => {
const session = useSessionContext();
const { auth: { accessToken, login } } = useSessionContext();
const router = useRouter();

const handleSubmitTemplate = () => {
if (!session.auth.token) {
return session.auth.login('dynamic', routes.profile.settings.templates());
if (!accessToken) {
return login('dynamic', routes.profile.settings.templates());
}

return router.push(routes.profile.settings.templates());
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useAuthCookie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const useAuthCookie = (): [

const set = (jwt: string) => {
try {
const parsed = decodeAccessToken({ token: jwt });
const parsed = decodeAccessToken({ accessToken: jwt });

cookies.set(key, jwt, {
expires: DateTime.fromSeconds(parsed.exp).toJSDate(),
Expand Down
17 changes: 11 additions & 6 deletions src/hooks/useAuthProviders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ export type AuthProviders = 'dynamic';

export type AuthWith = {
handleLogin: () => void;
handleLogout: () => void;
handleLogout: () => Promise<void>;
requestAccessToken: (projectId?: string) => Promise<string>;
token: string | undefined;
authProviderToken?: string;
};

export const useAuthProviders = (): Record<AuthProviders, AuthWith> => {
Expand All @@ -29,17 +29,22 @@ const useAuthWithDynamic = (): AuthWith => {

const handleLogin = () => dynamic.setShowAuthFlow(true);

const handleLogout = () => dynamic.handleLogOut();
const handleLogout = async () => dynamic.handleLogOut();

const requestAccessToken = async (projectId?: string): Promise<string> => {
console.log('[debug] useAuthProvidders: requestAccessToken: 1')
if (!dynamic.authToken) {
console.log('[debug] useAuthProvidders: requestAccessToken: requestAccessToken NOT')

return '';
}

const { data, error } = await loginWithDynamic({
data: { authToken: dynamic.authToken, projectId },
});

console.log(`[debug] useAuthProvidders: requestAccessToken: loginWithDynamic: response: ${JSON.stringify(data)}`)

if (data && data.loginWithDynamic) {
return data.loginWithDynamic;
}
Expand All @@ -51,7 +56,7 @@ const useAuthWithDynamic = (): AuthWith => {
handleLogin,
handleLogout,
requestAccessToken,
token: dynamic.authToken,
authProviderToken: dynamic.authToken,
};
};

Expand All @@ -61,8 +66,8 @@ const getMockedProvider: () => AuthWith = () => {

return {
handleLogin: () => {},
handleLogout: () => {},
handleLogout: async () => {},
requestAccessToken: async () => 'mocked-token',
token: cookies.values.authProviderToken,
accessToken: cookies.values.authProviderToken,
};
};
10 changes: 4 additions & 6 deletions src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,10 @@ const App = ({ Component, pageProps, requestCookies }: AppProps) => {
</Head>
)}
<Providers requestCookies={requestCookies} forcedTheme={forcedTheme}>
<Auth>
<h1>{noCanonical}</h1>
{getLayout(<Component {...pageProps} />)}
<ToastsContainer />
<FeedbackModal />
</Auth>
<h1>{noCanonical}</h1>
{getLayout(<Component {...pageProps} />)}
<ToastsContainer />
<FeedbackModal />
</Providers>
</>
);
Expand Down
8 changes: 4 additions & 4 deletions src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@ import { useSessionContext } from '@/providers/SessionProvider';
import { Page } from '@/types/App';

const HomePage: Page = () => {
const session = useSessionContext();
const { error, loading, auth: { accessToken, login } } = useSessionContext();

const handleLogIn = () => {
if (!session.error && !session.loading && !session.auth.token) {
session.auth.login('dynamic');
if (!error && !loading && !accessToken) {
login('dynamic');
}
};

useEffect(() => {
handleLogIn();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [session.loading]);
}, [loading]);

return (
<>
Expand Down
12 changes: 6 additions & 6 deletions src/pages/login/[verificationSessionId].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { Log } from '@/utils/log';

const LoginWithSessionPage: Page = () => {
const router = useRouter();
const session = useSessionContext();
const { auth: { accessToken, login }, project, loading } = useSessionContext();

const [
createLoginVerificationSessionMutation,
Expand All @@ -26,9 +26,9 @@ const LoginWithSessionPage: Page = () => {

const handleRedirect = useCallback(() => {
return router.replace(
routes.project.home({ projectId: session.project.id }),
routes.project.home({ projectId: project.id }),
);
}, [router, session.project.id]);
}, [router, project.id]);

const handleCreateVerificationSession = useCallback(async () => {
try {
Expand Down Expand Up @@ -76,7 +76,7 @@ const LoginWithSessionPage: Page = () => {
}

if (
session.auth.token &&
accessToken &&
!createLoginVerificationSessionMutation?.data
?.createLoginVerificationSession
) {
Expand Down Expand Up @@ -106,8 +106,8 @@ const LoginWithSessionPage: Page = () => {
withExternalLink
>
<Button
onClick={() => session.auth.login('dynamic')}
loading={session.loading}
onClick={() => login('dynamic')}
loading={loading}
className="w-full"
>
Sign in
Expand Down
4 changes: 2 additions & 2 deletions src/pages/migration/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ import { Button, Stepper } from '@/ui';
import { withAccess } from '@/utils/withAccess';

const MigrationPage: Page = () => {
const session = useSessionContext();
const { auth: { accessToken } } = useSessionContext();

return (
<>
{session.auth.token && (
{accessToken && (
<Link href={routes.home()}>
<Button intent="neutral" iconLeft="arrow-left">
Go back
Expand Down
Loading
Loading