Skip to content

Commit

Permalink
get rid of session.helper
Browse files Browse the repository at this point in the history
  • Loading branch information
michenly committed May 22, 2024
1 parent 6c8c2b5 commit 29106f2
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 93 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,9 @@ export function cartBuyerIdentityUpdateDefault(
): CartBuyerIdentityUpdateFunction {
return async (buyerIdentity, {response, ...cartOptionalInput}) => {
if (buyerIdentity.companyLocationId && options.customerAccount) {
options.customerAccount.UNSTABLE_setBuyer(
{
companyLocationId: buyerIdentity.companyLocationId,
},
{response},
);
options.customerAccount.UNSTABLE_setBuyer({
companyLocationId: buyerIdentity.companyLocationId,
});
}

const buyer = options.customerAccount
Expand Down
29 changes: 14 additions & 15 deletions packages/hydrogen/src/customer/auth.helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import {
USER_AGENT,
CUSTOMER_API_CLIENT_ID,
CUSTOMER_ACCOUNT_SESSION_KEY,
BUYER_SESSION_KEY,
} from '../constants';
import type {ResponseOption} from './types';
import {setSession, clearSession} from './session.helpers';
import type {ResponseStub} from '@remix-run/server-runtime/dist/single-fetch';

type H2OEvent = Parameters<NonNullable<typeof __H2O_LOG_EVENT>>[0];
Expand Down Expand Up @@ -138,24 +138,23 @@ export async function refreshToken({
debugInfo,
);

await setSession(
session,
CUSTOMER_ACCOUNT_SESSION_KEY,
{
accessToken,
// Store the date in future the token expires, separated by two minutes
expiresAt:
new Date(new Date().getTime() + (expires_in - 120) * 1000).getTime() +
'',
refreshToken: refresh_token,
idToken,
},
response,
);
session.set(CUSTOMER_ACCOUNT_SESSION_KEY, {
accessToken,
// Store the date in future the token expires, separated by two minutes
expiresAt:
new Date(new Date().getTime() + (expires_in - 120) * 1000).getTime() + '',
refreshToken: refresh_token,
idToken,
});

await exchangeForStorefrontCustomerAccessToken({response});
}

export function clearSession(session: HydrogenSession): void {
session.unset(CUSTOMER_ACCOUNT_SESSION_KEY);
session.unset(BUYER_SESSION_KEY);
}

export async function checkExpires({
locks,
expiresAt,
Expand Down
73 changes: 31 additions & 42 deletions packages/hydrogen/src/customer/customer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
USER_AGENT,
} from '../constants';
import {
clearSession,
generateCodeChallenge,
generateCodeVerifier,
generateState,
Expand Down Expand Up @@ -47,7 +48,6 @@ import type {
ResponseOption,
Buyer,
} from './types';
import {setSession, clearSession} from './session.helpers';
import {ResponseStub} from '@remix-run/server-runtime/dist/single-fetch';

const DEFAULT_LOGIN_URL = '/account/login';
Expand Down Expand Up @@ -175,7 +175,7 @@ export function createCustomerAccountClient({
if (!fetchResponse.ok) {
if (fetchResponse.status === 401) {
// clear session because current access token is invalid
await clearSession(session, response);
clearSession(session);
throw authStatusHandler(response);
}

Expand Down Expand Up @@ -291,8 +291,11 @@ export function createCustomerAccountClient({
});
}

async function setBuyer(buyer: Buyer, {response}: ResponseOption) {
await setSession(session, BUYER_SESSION_KEY, buyer, response, false);
function setBuyer(buyer: Buyer) {
session.set(BUYER_SESSION_KEY, {
...session.get(BUYER_SESSION_KEY),
...buyer,
});
}

async function getBuyer(options: ResponseOption) {
Expand Down Expand Up @@ -336,12 +339,9 @@ export function createCustomerAccountClient({
data?.storefrontCustomerAccessTokenCreate?.customerAccessToken;

if (customerAccessToken) {
setBuyer(
{
customerAccessToken,
},
{response},
);
setBuyer({
customerAccessToken,
});
}
}

Expand Down Expand Up @@ -376,21 +376,16 @@ export function createCustomerAccountClient({
const verifier = generateCodeVerifier();
const challenge = await generateCodeChallenge(verifier);

await setSession(
session,
CUSTOMER_ACCOUNT_SESSION_KEY,
{
codeVerifier: verifier,
state,
nonce,
redirectPath:
getRedirectUrl(request.url) ||
getHeader(request, 'Referer') ||
DEFAULT_REDIRECT_PATH,
},
response,
false,
);
session.set(CUSTOMER_ACCOUNT_SESSION_KEY, {
...session.get(CUSTOMER_ACCOUNT_SESSION_KEY),
codeVerifier: verifier,
state,
nonce,
redirectPath:
getRedirectUrl(request.url) ||
getHeader(request, 'Referer') ||
DEFAULT_REDIRECT_PATH,
});

loginUrl.searchParams.append('code_challenge', challenge);
loginUrl.searchParams.append('code_challenge_method', 'S256');
Expand All @@ -417,7 +412,7 @@ export function createCustomerAccountClient({
).toString()
: postLogoutRedirectUri;

await clearSession(session, options.response);
clearSession(session);

options.response.status = 302;
options.response.headers.set('Location', logoutUrl.toString());
Expand All @@ -439,7 +434,7 @@ export function createCustomerAccountClient({
const state = requestUrl.searchParams.get('state');

if (!code || !state) {
await clearSession(session, response);
clearSession(session);

throw new BadRequest(
'Unauthorized',
Expand All @@ -448,7 +443,7 @@ export function createCustomerAccountClient({
}

if (session.get(CUSTOMER_ACCOUNT_SESSION_KEY)?.state !== state) {
await clearSession(session, response);
clearSession(session);

throw new BadRequest(
'Unauthorized',
Expand Down Expand Up @@ -540,20 +535,14 @@ export function createCustomerAccountClient({
CUSTOMER_ACCOUNT_SESSION_KEY,
)?.redirectPath;

await setSession(
session,
CUSTOMER_ACCOUNT_SESSION_KEY,
{
accessToken: customerAccessToken,
expiresAt:
new Date(
new Date().getTime() + (expires_in - 120) * 1000,
).getTime() + '',
refreshToken: refresh_token,
idToken: id_token,
},
response,
);
session.set(CUSTOMER_ACCOUNT_SESSION_KEY, {
accessToken: customerAccessToken,
expiresAt:
new Date(new Date().getTime() + (expires_in - 120) * 1000).getTime() +
'',
refreshToken: refresh_token,
idToken: id_token,
});

await exchangeForStorefrontCustomerAccessToken({response});

Expand Down
28 changes: 0 additions & 28 deletions packages/hydrogen/src/customer/session.helpers.ts

This file was deleted.

4 changes: 2 additions & 2 deletions packages/hydrogen/src/customer/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export type CustomerAccount = {
* */
login: (options: LoginOptions & ResponseOption) => Promise<void>;
/** On successful login, the customer redirects back to your app. This function validates the OAuth response and exchanges the authorization code for an access token and refresh token. It also persists the tokens on your session. This function should be called and returned from the Remix loader configured as the redirect URI within the Customer Account API settings in admin. */
authorize: (options: ResponseOption) => Promise<Response>;
authorize: (options: ResponseOption) => Promise<void>;
/** Returns if the customer is logged in. It also checks if the access token is expired and refreshes it if needed. */
isLoggedIn: (options: ResponseOption) => Promise<boolean>;
/** Check for a not logged in customer and redirect customer to login page. The redirect can be overwritten with `customAuthStatusHandler` option. */
Expand Down Expand Up @@ -127,7 +127,7 @@ export type CustomerAccount = {
> & {errors?: JsonGraphQLError[]}
>;
/** UNSTABLE feature. Set buyer information into session.*/
UNSTABLE_setBuyer: (buyer: Buyer, options: ResponseOption) => Promise<void>;
UNSTABLE_setBuyer: (buyer: Buyer) => void;
/** UNSTABLE feature. Get buyer token and company location id from session.*/
UNSTABLE_getBuyer: (options: ResponseOption) => Promise<Buyer>;
};
Expand Down

0 comments on commit 29106f2

Please sign in to comment.