Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: B2B authentication and navigation #1744

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
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
15 changes: 13 additions & 2 deletions core/app/[locale]/(default)/account/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { ReactNode } from 'react';
import { Link } from '~/components/link';

import { AccountNotification } from './_components/account-notification';
import { auth } from '~/auth';
import { redirect } from 'next/navigation';

interface AccountItem {
children: ReactNode;
Expand Down Expand Up @@ -37,9 +39,8 @@ export async function generateMetadata() {
};
}

export default function Account() {
const AccountComponent = () => {
const t = useTranslations('Account.Home');

return (
<div className="mx-auto">
<h1 className="my-8 text-4xl font-black lg:my-8 lg:text-5xl">{t('heading')}</h1>
Expand All @@ -61,4 +62,14 @@ export default function Account() {
);
}

export default async function Account() {
const session = await auth()

if (session?.b2bToken) {
redirect('/#/orders')
}

return <AccountComponent />;
}

export const runtime = 'edge';
24 changes: 24 additions & 0 deletions core/app/[locale]/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Inter } from 'next/font/google';
import { NextIntlClientProvider } from 'next-intl';
import { getMessages, setRequestLocale } from 'next-intl/server';
import { PropsWithChildren } from 'react';
import B2B from '~/components/b2b';

import '../globals.css';

Expand Down Expand Up @@ -92,14 +93,37 @@ export default async function RootLayout({ params, children }: Props) {
setRequestLocale(locale);

const messages = await getMessages();
const environment = process.env.NODE_ENV


return (
<html className={`${inter.variable} font-sans`} lang={locale}>
<head>
{
process.env.NODE_ENV !== 'production' && (
<>
<script type="module">
{
`
import RefreshRuntime from 'http://localhost:3001/@react-refresh'
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true
`
}
</script>
<script type="module" src="http://localhost:3001/@vite/client"></script>
</>
)
}
</head>
<body className="flex h-screen min-w-[375px] flex-col">
<Notifications />
<NextIntlClientProvider locale={locale} messages={messages}>
<Providers>{children}</Providers>
</NextIntlClientProvider>
<B2B />
<VercelComponents />
</body>
</html>
Expand Down
98 changes: 93 additions & 5 deletions core/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const LoginMutation = graphql(`
login(email: $email, password: $password) {
customerAccessToken {
value
expiresAt
}
customer {
entityId
Expand Down Expand Up @@ -63,9 +64,18 @@ const config = {
token.customerAccessToken = user.customerAccessToken;
}

if (user?.b2bToken) {
token.b2bToken = user?.b2bToken
}

return token;
},
session({ session, token }) {
if (token?.b2bToken){
//@ts-ignore
session.b2bToken = token?.b2bToken;
}

if (token.customerAccessToken) {
session.customerAccessToken = token.customerAccessToken;
}
Expand Down Expand Up @@ -145,11 +155,54 @@ const config = {
return null;
}

return {
name: `${result.customer.firstName} ${result.customer.lastName}`,
email: result.customer.email,
customerAccessToken: result.customerAccessToken.value,
};
const user = {
id: result.customer.entityId.toString(),
name: `${result.customer.firstName} ${result.customer.lastName}`,
email: result.customer.email,
customerAccessToken: result.customerAccessToken.value,
expiresAt: result.customerAccessToken.expiresAt,
}

if (!process.env.B2B_API_HOST || !process.env.B2B_API_TOKEN) {
return user;
}

try {
const payload = {
channelId: Number(process.env.BIGCOMMERCE_CHANNEL_ID),
customerId: result.customer.entityId,
customerAccessToken: {
value: result.customerAccessToken.value,
expiresAt: result.customerAccessToken.expiresAt,
},
}

const response = await client.b2bFetch<{
data: {
token: string[]
}
}>(
'/api/io/auth/customers/storefront',
{
method: 'POST',
body: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json',
}
},
);

const b2bToken = response.data?.token?.[0];

if (b2bToken)
return {...user, b2bToken };

return user
} catch (e) {
e
return user;
}

},
}),
],
Expand All @@ -173,12 +226,15 @@ declare module 'next-auth' {
interface Session {
user?: DefaultSession['user'];
customerAccessToken?: string;
b2bToken?: string
}

interface User {
name?: string | null;
email?: string | null;
customerAccessToken?: string;
expiresAt?: string;
b2bToken?: string;
}
}

Expand All @@ -188,3 +244,35 @@ declare module 'next-auth/jwt' {
customerAccessToken?: string;
}
}


type B2BEvent = string;
type CallbackEvent = {
data: any; // Adjust to match the actual type of CustomFieldItems
preventDefault: () => void;
};
type Callback = (event: CallbackEvent) => any;
type CallbackManagerType = {
callbacks: Map<B2BEvent, Callback[]>;
addEventListener(callbackKey: B2BEvent, callback: Callback): void;
removeEventListener(callbackKey: B2BEvent, callback: Callback): boolean;
dispatchEvent(callbackKey: B2BEvent, data?: any): boolean;
};

declare global {
interface Window {
b2b: {
callbacks: CallbackManagerType;
utils: {
getRoutes: () => any[]
openPage: (path: string, url?: string) => void;
user: {
getProfile: () => { role: number };
loginWithB2BStorefrontToken: (b2bStorefrontJWTToken: string) => Promise<void>;
logout: (params?: { handleError?: (error: any) => any }) => Promise<void>;
getB2BToken: () => string;
};
};
};
}
}
44 changes: 44 additions & 0 deletions core/components/b2b/auth.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
'use client';
import { useActionState, useEffect, useRef } from 'react';
import { logout } from '../header/_actions/logout';
import { Form } from '../ui/form';
import { useRouter } from 'next/navigation';

interface B2BProviderProps {
b2bToken?: string;
}

const loginToB2b = async (b2bToken: string) => {
const token = window.b2b.utils.user.getB2BToken();
if (!b2bToken) {
if (token) await window.b2b.utils.user.logout();
return;
}

if (!token || (token !== '' && token !== b2bToken)) {
await window.b2b.utils.user.loginWithB2BStorefrontToken(b2bToken);
window.location.reload()
}
};

export default function B2BProvider({ b2bToken }: B2BProviderProps) {
const router = useRouter()
const [, formAction] = useActionState(logout, null);
const formRef = useRef<HTMLFormElement | null>(null)
const refresh = () => router.refresh()
useEffect(() => {
const interval = setInterval(() => {
if (window.b2b?.utils) {
window.b2b.callbacks.addEventListener('on-logout', () => {
formRef.current?.submit();
});
loginToB2b(b2bToken ?? '');
clearInterval(interval);
}
}, 500);
}, [b2bToken]);

return <Form ref={formRef} action={formAction} style={{ display: 'none' }}></Form>;
}

B2BProvider.displayName = 'B2BProvider';
81 changes: 81 additions & 0 deletions core/components/b2b/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { auth } from '~/auth';
import B2bAuth from './auth';

export default async function index() {
const session = await auth()
const environment = process.env.NODE_ENV
return (
<>
{
environment !== 'production' ? (
<>
<script>
{
`
window.B3 = {
setting: {
store_hash: '${process.env.BIGCOMMERCE_STORE_HASH}',
channel_id: ${process.env.BIGCOMMERCE_CHANNEL_ID},
platform: 'catalyst',
}
}
`
}
</script>
<script
type="module"
data-storehash="glzvoziq5k"
data-channelid="1664810"
src="http://localhost:3001/src/main.ts"
></script>
</>
) : (
<>
<script>
{
`
window.b3CheckoutConfig = {
routes: {
dashboard: '/account.php?action=order_status',
},
}
window.B3 = {
setting: {
store_hash: '${process.env.BIGCOMMERCE_STORE_HASH}',
channel_id: ${process.env.BIGCOMMERCE_CHANNEL_ID},
platform: 'catalyst',
},
'dom.checkoutRegisterParentElement': '#checkout-app',
'dom.registerElement':
'[href^="/login.php"], #checkout-customer-login, [href="/login.php"] .navUser-item-loginLabel, #checkout-customer-returning .form-legend-container [href="#"]',
'dom.openB3Checkout': 'checkout-customer-continue',
before_login_goto_page: '/account.php?action=order_status',
checkout_super_clear_session: 'true',
'dom.navUserLoginElement': '.navUser-item.navUser-item--account',
}`
}
</script>
<script
type="module"
crossorigin=""
src={`${process.env.B2B_BUYER_PORTAL_HOST}/index.*.js`}
></script>
<script
nomodule=""
crossorigin=""
src={`${process.env.B2B_BUYER_PORTAL_HOST}/polyfills-legacy.*.js`}
></script>
<script
nomodule=""
crossorigin=""
src={`${process.env.B2B_BUYER_PORTAL_HOST}/index-legacy.*.js`}
></script>
</>
)
}
<B2bAuth b2bToken={session?.b2bToken ?? ''} />
</>
)
}

index.displayName = 'B2B'
19 changes: 18 additions & 1 deletion core/components/header/_actions/logout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,29 @@

import { getLocale } from 'next-intl/server';

import { signOut } from '~/auth';
import { auth, signOut } from '~/auth';
import { client } from '~/client';
import { redirect } from '~/i18n/routing';

export const logout = async () => {
const locale = await getLocale();
const session = await auth()
const payload = {
id: session?.b2bToken,
name: session?.user?.name,
email: session?.user?.email,
}

await client.b2bFetch(
'/api/io/auth/backend',
{
method: 'DELETE',
body: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json',
},
},
);
await signOut({ redirect: false });

redirect({ href: '/login', locale });
Expand Down
Loading
Loading