Skip to content

Commit

Permalink
fix(theme, composable): expired user token issue (#519)
Browse files Browse the repository at this point in the history
- add proper handling of unathorized requests

Co-authored-by: Bartosz Herba <[email protected]>
  • Loading branch information
bartoszherba and bartoszherba authored Jan 31, 2022
1 parent bc4eccb commit 60f6ee6
Show file tree
Hide file tree
Showing 14 changed files with 111 additions and 72 deletions.
6 changes: 3 additions & 3 deletions packages/composables/src/composables/useAddresses/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ RemoveAddressInput> = {

const { data } = await context.$magento.api.getCustomerAddresses();

return data.customer.addresses;
return data?.customer?.addresses ?? [];
},
save: async (context: Context, saveParams) => {
Logger.debug('[Magento] save user address:', saveParams.address);
Expand All @@ -45,7 +45,7 @@ RemoveAddressInput> = {

Logger.debug('[Result]:', { data });

return data.createCustomerAddress;
return data?.createCustomerAddress ?? {};
},
remove: async (context: Context, params) => {
Logger.debug('[Magento] remove user addresses');
Expand All @@ -67,7 +67,7 @@ RemoveAddressInput> = {

Logger.debug('[Result]:', { data });

return data.updateCustomerAddress;
return data?.updateCustomerAddress ?? {};
},
};

Expand Down
6 changes: 3 additions & 3 deletions packages/composables/src/composables/useBilling/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const factoryParams: UseBillingParams<any, any> = {
await context.cart.load({ customQuery });
}

return context.cart.cart.value.billing_address;
return context?.cart?.cart?.value?.billing_address ?? {};
},

// eslint-disable-next-line @typescript-eslint/no-unused-vars
Expand Down Expand Up @@ -79,11 +79,11 @@ const factoryParams: UseBillingParams<any, any> = {
method_code: shippingMethod.method_code,
},
});

/**
* End of GraphQL Workaround
*/

return data.setBillingAddressOnCart.cart.billing_address;
return data?.setBillingAddressOnCart?.cart?.billing_address ?? {};
},
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const factoryParams: UseGetShippingMethodsFactory<ShippingMethod> = {

const hasAddresses = data.customerCart.shipping_addresses.length > 0;

return hasAddresses ? data.customerCart.shipping_addresses[0].available_shipping_methods : [];
return hasAddresses ? data?.customerCart?.shipping_addresses[0]?.available_shipping_methods : [];
},
};

Expand Down
8 changes: 4 additions & 4 deletions packages/composables/src/composables/useReview/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ ProductReviewRatingMetadata> = {

Logger.debug('[Result]:', { data });

return data.products.items;
return data?.products?.items ?? [];
},
addReview: async (context: Context, params: ComposableFunctionArgs<CreateProductReviewInput>) => {
Logger.debug('[Magento] add review params input:', JSON.stringify(params, null, 2));
Expand All @@ -42,7 +42,7 @@ ProductReviewRatingMetadata> = {

Logger.debug('[Result]:', { data });

return data.createProductReview.review;
return data?.createProductReview?.review ?? {};
},
loadReviewMetadata: async (context: Context, params) => {
Logger.debug('[Magento] load review metadata');
Expand All @@ -51,7 +51,7 @@ ProductReviewRatingMetadata> = {

Logger.debug('[Result]:', { data });

return data.productReviewRatingsMetadata.items;
return data?.productReviewRatingsMetadata?.items ?? [];
},
loadCustomerReviews: async (
context: Context,
Expand All @@ -67,7 +67,7 @@ ProductReviewRatingMetadata> = {

Logger.debug('[Result]:', { data });

return data.customer;
return data?.customer ?? {};
},
};

Expand Down
12 changes: 8 additions & 4 deletions packages/composables/src/composables/useUser/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ CustomerCreateInput

Logger.debug('[Result]:', { data });

return data.customer;
return data?.customer ?? {};
} catch {
// eslint-disable-next-line no-void
// @ts-ignore
Expand Down Expand Up @@ -79,11 +79,15 @@ CustomerCreateInput
});
}

const { data } = await context.$magento.api.updateCustomer(userData);

const { data, errors } = await context.$magento.api.updateCustomer(userData);
Logger.debug('[Result]:', { data });

return data.updateCustomerV2.customer;
if (errors) {
throw new Error(errors.map((e) => e.message).join(','));
}

// return data.updateCustomerV2.customer;
return data?.updateCustomerV2?.customer || {};
},
register: async (context: Context, params) => {
const {
Expand Down
9 changes: 4 additions & 5 deletions packages/composables/src/composables/useUserBilling/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const factoryParams: UseUserBillingFactoryParams<any, CustomerAddress> = {

Logger.debug('[Result]:', { data });

return data.createCustomerAddress;
return data?.createCustomerAddress ?? {};
},

deleteAddress: async (context: Context, params?) => {
Expand All @@ -32,7 +32,7 @@ const factoryParams: UseUserBillingFactoryParams<any, CustomerAddress> = {

Logger.debug('[Result]:', { data });

return data.deleteCustomerAddress;
return data?.deleteCustomerAddress ?? {};
},

updateAddress: async (context: Context, params?) => {
Expand All @@ -42,7 +42,7 @@ const factoryParams: UseUserBillingFactoryParams<any, CustomerAddress> = {

Logger.debug('[Result]:', { data });

return data.updateCustomerAddress;
return data?.updateCustomerAddress ?? {};
},

// eslint-disable-next-line @typescript-eslint/no-unused-vars
Expand All @@ -63,9 +63,8 @@ const factoryParams: UseUserBillingFactoryParams<any, CustomerAddress> = {

Logger.debug('[Result]:', { data });

return data.updateCustomerAddress;
return data?.updateCustomerAddress ?? {};
},

};

export default useUserBillingFactory<any, CustomerAddress>(factoryParams);
2 changes: 1 addition & 1 deletion packages/composables/src/composables/useUserOrder/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const factoryParams: UseUserOrderFactoryParams<any, GetOrdersSearchParams> = {

Logger.debug('[Result]:', { data });

return data.customer.orders;
return data?.customer?.orders ?? {};
},
};

Expand Down
8 changes: 4 additions & 4 deletions packages/composables/src/composables/useUserShipping/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,22 +23,22 @@ const factoryParams: UseUserShippingFactoryParams<any, any> = {

Logger.debug('[Result]:', { data });

return data.createCustomerAddress;
return data?.createCustomerAddress ?? {};
},

deleteAddress: async (context: Context, params) => {
Logger.debug('[Magento] delete shipping address', { params });
const { data } = await context.$magento.api.deleteCustomerAddress(params.address.id);

return data.deleteCustomerAddress;
return data?.deleteCustomerAddress ?? {};
},

updateAddress: async (context: Context, params) => {
Logger.debug('[Magento] update shipping address', { params });

const { data } = await context.$magento.api.updateCustomerAddress(transformUserUpdateAddressInput(params));

return data.updateCustomerAddress;
return data?.updateCustomerAddress ?? {};
},

// eslint-disable-next-line @typescript-eslint/no-unused-vars
Expand All @@ -59,7 +59,7 @@ const factoryParams: UseUserShippingFactoryParams<any, any> = {

Logger.debug('[Result]:', { data });

return data.updateCustomerAddress;
return data?.updateCustomerAddress ?? {};
},
};

Expand Down
10 changes: 5 additions & 5 deletions packages/composables/src/composables/useWishlist/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const factoryParams: UseWishlistFactoryParams<any, any, any> = {

Logger.debug('[Result]:', { data });

return data.customer.wishlists;
return data?.customer?.wishlists ?? [];
}

return [];
Expand Down Expand Up @@ -68,7 +68,7 @@ const factoryParams: UseWishlistFactoryParams<any, any, any> = {

Logger.debug('[Result]:', { data });

return data.addProductsToWishlist.wishlist;
return data?.addProductsToWishlist?.wishlist ?? {};
case 'ConfigurableProduct':
const { data: configurableProductData } = await context.$magento.api.addProductToWishList({
id: '0',
Expand All @@ -81,7 +81,7 @@ const factoryParams: UseWishlistFactoryParams<any, any, any> = {

Logger.debug('[Result]:', { data: configurableProductData });

return configurableProductData.addProductsToWishlist.wishlist;
return configurableProductData?.addProductsToWishlist?.wishlist ?? {};
case 'BundleProduct':
const { data: bundleProductData } = await context.$magento.api.addProductToWishList({
id: '0',
Expand All @@ -94,7 +94,7 @@ const factoryParams: UseWishlistFactoryParams<any, any, any> = {

Logger.debug('[Result]:', { data: bundleProductData });

return bundleProductData.addProductsToWishlist.wishlist;
return bundleProductData?.addProductsToWishlist?.wishlist ?? {};
default:
// todo implement other options
// @ts-ignore
Expand All @@ -117,7 +117,7 @@ const factoryParams: UseWishlistFactoryParams<any, any, any> = {

Logger.debug('[Result]:', { data });

return data.removeProductsFromWishlist.wishlist;
return data?.removeProductsFromWishlist?.wishlist ?? {};
},
clear: async ({ currentWishlist }) => ({}),
isInWishlist: (context, params) => {
Expand Down
3 changes: 1 addition & 2 deletions packages/theme/composables/useUiNotification/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { computed, reactive, useContext} from '@nuxtjs/composition-api';
import { computed, reactive, useContext } from '@nuxtjs/composition-api';
import cookieNames from '~/enums/cookieNameEnum';

interface UiNotification {
Expand Down Expand Up @@ -56,7 +56,6 @@ const useUiNotification = () => {
}
};


if (cookieMessage) {
send(cookieMessage);
}
Expand Down
6 changes: 4 additions & 2 deletions packages/theme/pages/MyAccount/MyProfile.vue
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ extend('min', {
extend('password', {
message: invalidPasswordMsg,
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
validate: (value) => customerPasswordRegExp.test(value),
});
Expand Down Expand Up @@ -84,8 +85,9 @@ export default defineComponent({
const formHandler = async (fn, onComplete, onError) => {
await fn();
if (error.value.changePassword !== null) {
onError(error.value.changePassword);
const actionErr = error.value.changePassword || error.value.updateUser;
if (actionErr) {
onError(actionErr);
} else {
onComplete();
}
Expand Down
40 changes: 29 additions & 11 deletions packages/theme/plugins/__tests__/token-expired.spec.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
import tokenExpiredPlugin from '../token-expired';
import cookieNames from '~/enums/cookieNameEnum';

const callbackResponse = {
const errRes = {
data: {
message: 'The current customer isn\'t authorized.',
errors: [
{
extensions: {
category: 'graphql-authorization',
},
},
],
},
};

const validRes = {
data: {
errors: [],
},
};

const appMock = {
const appMockFactory = (callbackResponse) => ({
$vsf: {
$magento: {
client: {
Expand All @@ -26,29 +37,34 @@ const appMock = {
remove: jest.fn(),
set: jest.fn(),
},
router: {
go: jest.fn(),
},
localePath: (t) => t,
i18n: {
t: (t) => t,
},
};

const redirectMock = jest.fn();
});

describe('Token Expired plugin', () => {
beforeEach(() => {
jest.resetAllMocks();
});

it('should work only when the current customer is not authorized', async () => {
it('should be executed only if there is the "graphql-authorization" error', async () => {
const appMock = appMockFactory(validRes);

// eslint-disable-next-line @typescript-eslint/await-thenable
await tokenExpiredPlugin({ app: appMock, redirect: redirectMock });
await tokenExpiredPlugin({ app: appMock });

expect(redirectMock).toHaveBeenCalledWith('/');
expect(appMock.router.go).toHaveBeenCalledTimes(0);
});

it('should set message cookie', async () => {
const appMock = appMockFactory(errRes);

// eslint-disable-next-line @typescript-eslint/await-thenable
await tokenExpiredPlugin({ app: appMock, redirect: redirectMock });
await tokenExpiredPlugin({ app: appMock });

const messageMock = {
icon: null,
Expand All @@ -62,8 +78,10 @@ describe('Token Expired plugin', () => {
});

it('should clear customer token and clear cart id', async () => {
const appMock = appMockFactory(errRes);

// eslint-disable-next-line @typescript-eslint/await-thenable
await tokenExpiredPlugin({ app: appMock, redirect: redirectMock });
await tokenExpiredPlugin({ app: appMock });

expect(appMock.$cookies.remove).toHaveBeenCalledTimes(2);
expect(appMock.$cookies.remove).toHaveBeenCalledWith(cookieNames.customerCookieName);
Expand Down
27 changes: 0 additions & 27 deletions packages/theme/plugins/token-expired.js

This file was deleted.

Loading

0 comments on commit 60f6ee6

Please sign in to comment.