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 4 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) {
return redirect('/#/orders')
}

return <AccountComponent />;
}

export const runtime = 'edge';
2 changes: 2 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 @@ -100,6 +101,7 @@ export default async function RootLayout({ params, children }: Props) {
<NextIntlClientProvider locale={locale} messages={messages}>
<Providers>{children}</Providers>
</NextIntlClientProvider>
<B2B />
<VercelComponents />
</body>
</html>
Expand Down
84 changes: 79 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,55 @@ 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',
authtoken: process.env.B2B_API_TOKEN || '',
},
},
);

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

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

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

},
}),
],
Expand All @@ -173,12 +227,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 +245,20 @@ declare module 'next-auth/jwt' {
customerAccessToken?: string;
}
}

declare global {
interface Window {
b2b: {
utils: {
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;
getAllowedRoutes: () => any[]
};
};
};
}
}
34 changes: 34 additions & 0 deletions core/components/b2b/auth.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
'use client'
import React, { FC, useEffect } from 'react'

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) {
await window.b2b.utils.user.loginWithB2BStorefrontToken(b2bToken)
}
}

export default function B2BProvider({ b2bToken }: B2BProviderProps) {
useEffect(() => {
const interval = setInterval(() => {
if (window.b2b?.utils) {
loginToB2b(b2bToken ?? '')
clearInterval(interval)
}
}, 500)
}, [])

return null
}

B2BProvider.displayName = 'B2BProvider'

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

export default async function index() {
const session = await auth()
const environment = process.env.NODE_ENV
return (
<>
<Head>
{
environment !== '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>
{
process.env.NODE_ENV !== 'production' ? (
<>
<script
type="module"
data-storehash="glzvoziq5k"
data-channelid="1664810"
src="http://localhost:3001/src/buyerPortal.ts"
></script>
<script>
{
`
window.B3 = {
setting: {
store_hash: '${process.env.BIGCOMMERCE_STORE_HASH}',
channel_id: ${process.env.BIGCOMMERCE_CHANNEL_ID},
platform: 'catalyst',
},
`
}
</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'
20 changes: 19 additions & 1 deletion core/components/header/_actions/logout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,30 @@

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',
authtoken: process.env.B2B_API_TOKEN || '',
},
},
);
await signOut({ redirect: false });

redirect({ href: '/login', locale });
Expand Down
5 changes: 4 additions & 1 deletion core/components/header/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { getLocale, getTranslations } from 'next-intl/server';
import { ReactNode, Suspense } from 'react';

import { LayoutQuery } from '~/app/[locale]/(default)/query';
import { getSessionCustomerAccessToken } from '~/auth';
import { auth, getSessionCustomerAccessToken } from '~/auth';
import { client } from '~/client';
import { readFragment } from '~/client/graphql';
import { revalidate } from '~/client/revalidate-target';
Expand All @@ -28,6 +28,7 @@ export const Header = async ({ cart }: Props) => {
const locale = await getLocale();
const t = await getTranslations('Components.Header');
const customerAccessToken = await getSessionCustomerAccessToken();
const session = await auth()

const { data: response } = await client.fetch({
document: LayoutQuery,
Expand Down Expand Up @@ -57,6 +58,8 @@ export const Header = async ({ cart }: Props) => {

return (
<ComponentsHeader
b2bToken={session?.b2bToken}
accountLabel={t('Account.account')}
account={
customerAccessToken ? (
<Dropdown
Expand Down
18 changes: 18 additions & 0 deletions core/components/link/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,24 @@ export const Link = forwardRef<ComponentRef<'a'>, Props>(
setPrefetched();
};

// if an href contains a hash route
if (typeof href === 'string' && href.includes('#')) {
return (
<button
className={cn(
'hover:text-primary focus-visible:outline-none focus-visible:ring-4 focus-visible:ring-primary/20',
className,
)}
onClick={(e) => {
e.preventDefault()
window?.b2b?.utils?.openPage('', href.slice(3));
}}
>
{children}
</button>
);
}

return (
<NavLink
className={cn(
Expand Down
Loading
Loading