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

[MOB-9899]: Add Auth Checks Before API Calls #463

Merged
merged 15 commits into from
Oct 15, 2024
Merged
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
71 changes: 48 additions & 23 deletions src/authorization/authorization.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import { initialize } from './authorization';
import { initialize, setTypeOfAuthForTestingOnly } from './authorization';
import { baseAxiosRequest } from '../request';
import { getInAppMessages } from '../inapp';
import { track, trackInAppClose } from '../events';
Expand Down Expand Up @@ -41,6 +41,8 @@ describe('API Key Interceptors', () => {
});

beforeEach(() => {
setTypeOfAuthForTestingOnly('userID');

mockRequest.onPost('/users/update').reply(200, {
data: 'something'
});
Expand Down Expand Up @@ -342,6 +344,8 @@ describe('API Key Interceptors', () => {

describe('User Identification', () => {
beforeEach(() => {
setTypeOfAuthForTestingOnly('userID');

/* clear any interceptors already configured */
[
...Array(
Expand All @@ -354,6 +358,7 @@ describe('User Identification', () => {

describe('non-JWT auth', () => {
beforeAll(() => {
(global as any).localStorage = localStorageMock;
mockRequest = new MockAdapter(baseAxiosRequest);

mockRequest.onPost('/users/update').reply(200, {});
Expand All @@ -369,11 +374,16 @@ describe('User Identification', () => {
await setEmail('hello@gmail.com');
logout();

const response = await getInAppMessages({
count: 10,
packageName: 'my-lil-website'
});
expect(response.config.params.email).toBeUndefined();
try {
await getInAppMessages({
count: 10,
packageName: 'my-lil-website'
});
} catch (e) {
expect(e).toStrictEqual(
new Error('Cannot make API request until a user is signed in')
);
}
});

it('logout method removes the userId field from requests', async () => {
Expand All @@ -382,11 +392,16 @@ describe('User Identification', () => {
await setUserID('hello@gmail.com');
logout();

const response = await getInAppMessages({
count: 10,
packageName: 'my-lil-website'
});
expect(response.config.params.userId).toBeUndefined();
try {
await getInAppMessages({
count: 10,
packageName: 'my-lil-website'
});
} catch (e) {
expect(e).toStrictEqual(
new Error('Cannot make API request until a user is signed in')
);
}
});
});

Expand Down Expand Up @@ -693,11 +708,16 @@ describe('User Identification', () => {
await setEmail('hello@gmail.com');
logout();

const response = await getInAppMessages({
count: 10,
packageName: 'my-lil-website'
});
expect(response.config.params.email).toBeUndefined();
try {
await getInAppMessages({
count: 10,
packageName: 'my-lil-website'
});
} catch (e) {
expect(e).toStrictEqual(
new Error('Cannot make API request until a user is signed in')
);
}
});

it('logout method removes the userId field from requests', async () => {
Expand All @@ -707,11 +727,16 @@ describe('User Identification', () => {
await setUserID('hello@gmail.com');
logout();

const response = await getInAppMessages({
count: 10,
packageName: 'my-lil-website'
});
expect(response.config.params.userId).toBeUndefined();
try {
await getInAppMessages({
count: 10,
packageName: 'my-lil-website'
});
} catch (e) {
expect(e).toStrictEqual(
new Error('Cannot make API request until a user is signed in')
);
}
});
});

Expand Down Expand Up @@ -1092,8 +1117,8 @@ describe('User Identification', () => {
.fn()
.mockReturnValue(Promise.resolve(MOCK_JWT_KEY));
const { refreshJwtToken } = initialize('123', mockGenerateJWT);
await refreshJwtToken('hello@gmail.com');

const res = await refreshJwtToken('hello@gmail.com');
console.log({ res });
expect(mockGenerateJWT).toHaveBeenCalledTimes(1);
jest.advanceTimersByTime(60000 * 4.1);
expect(mockGenerateJWT).toHaveBeenCalledTimes(2);
Expand Down
7 changes: 6 additions & 1 deletion src/authorization/authorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ const MAX_TIMEOUT = ONE_DAY;
doesn't _need_ to support email-signed JWTs if they don't want and purely want to issue the
tokens by user ID.
*/
export let typeOfAuth: null | 'email' | 'userID' = null;
export type TypeOfAuth = null | 'email' | 'userID'
export let typeOfAuth: TypeOfAuth = null;
/* this will be the literal user ID or email they choose to auth with */
let authIdentifier: null | string = null;
let userInterceptor: number | null = null;
Expand Down Expand Up @@ -912,3 +913,7 @@ export function initializeWithConfig(initializeParams: InitializeParams) {
? initialize(authToken, generateJWT)
: initialize(authToken);
}

export function setTypeOfAuthForTestingOnly(authType: TypeOfAuth) {
typeOfAuth = authType
}
4 changes: 4 additions & 0 deletions src/commerce/commerce.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,14 @@ import { baseAxiosRequest } from '../request';
import { trackPurchase, updateCart } from './commerce';
// import { SDK_VERSION, WEB_PLATFORM } from '../constants';
import { createClientError } from '../utils/testUtils';
import { setTypeOfAuthForTestingOnly } from '../authorization';

const mockRequest = new MockAdapter(baseAxiosRequest);

describe('Users Requests', () => {
beforeEach(() => {
setTypeOfAuthForTestingOnly('email');
});
it('should set params and return the correct payload for updateCart', async () => {
mockRequest.onPost('/commerce/updateCart').reply(200, {
msg: 'hello'
Expand Down
11 changes: 11 additions & 0 deletions src/commerce/commerce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { IterableResponse } from '../types';
import { updateCartSchema, trackPurchaseSchema } from './commerce.schema';
import { AnonymousUserEventManager } from '../anonymousUserTracking/anonymousUserEventManager';
import { canTrackAnonUser } from '../utils/commonFunctions';
import { typeOfAuth } from '../authorization';

export const updateCart = (payload: UpdateCartRequestParams) => {
/* a customer could potentially send these up if they're not using TypeScript */
Expand All @@ -18,6 +19,11 @@ export const updateCart = (payload: UpdateCartRequestParams) => {
anonymousUserEventManager.trackAnonUpdateCart(payload);
return Promise.reject(INITIALIZE_ERROR);
}

if (typeOfAuth === null) {
return Promise.reject(INITIALIZE_ERROR);
}

return baseIterableRequest<IterableResponse>({
method: 'POST',
url: ENDPOINTS.commerce_update_cart.route,
Expand Down Expand Up @@ -45,6 +51,11 @@ export const trackPurchase = (payload: TrackPurchaseRequestParams) => {
anonymousUserEventManager.trackAnonPurchaseEvent(payload);
return Promise.reject(INITIALIZE_ERROR);
}

if (typeOfAuth === null) {
return Promise.reject(INITIALIZE_ERROR);
}

return baseIterableRequest<IterableResponse>({
method: 'POST',
url: ENDPOINTS.commerce_track_purchase.route,
Expand Down
5 changes: 3 additions & 2 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -306,5 +306,6 @@ export const UPDATECART_ITEM_PREFIX = 'updateCart.updatedShoppingCartItems.';
export const PURCHASE_ITEM_PREFIX = `${PURCHASE_ITEM}.`;

export const MERGE_SUCCESSFULL = 'MERGE_SUCCESSFULL';
export const INITIALIZE_ERROR =
'Iterable SDK must be initialized with an API key and user email/userId before calling SDK methods';
export const INITIALIZE_ERROR = new Error(
'Iterable SDK must be initialized with an API key and user email/userId before calling SDK methods'
);
7 changes: 6 additions & 1 deletion src/embedded/embeddedManager.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { IterableEmbeddedManager } from './embeddedManager';
import { setTypeOfAuthForTestingOnly } from '../authorization';

// Mock the baseIterableRequest function
jest.mock('../request', () => ({
Expand All @@ -11,6 +12,9 @@ jest.mock('..', () => ({
}));

describe('EmbeddedManager', () => {
beforeEach(() => {
setTypeOfAuthForTestingOnly('email');
});
const appPackageName = 'my-website';
describe('syncMessages', () => {
it('should call syncMessages and callback', async () => {
Expand All @@ -28,7 +32,8 @@ describe('EmbeddedManager', () => {
const embeddedManager = new IterableEmbeddedManager(appPackageName);

async function mockTest() {
return new Promise(function (resolve, reject) {
return new Promise((resolve, reject) => {
// eslint-disable-next-line prefer-promise-reject-errors
reject('Invalid API Key');
});
}
Expand Down
16 changes: 13 additions & 3 deletions src/embedded/embeddedManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,15 @@ import {
import { IterableResponse } from '../types';
import { EmbeddedMessagingProcessor } from './embeddedMessageProcessor';
import { ErrorMessage } from './consts';
import { SDK_VERSION, WEB_PLATFORM, ENDPOINTS } from '../constants';
import {
SDK_VERSION,
WEB_PLATFORM,
ENDPOINTS,
INITIALIZE_ERROR
} from '../constants';
import { trackEmbeddedReceived } from '../events/embedded/events';
import { handleEmbeddedClick } from './utils';
import { typeOfAuth } from '../authorization';

export class IterableEmbeddedManager {
public appPackageName: string;
Expand All @@ -27,8 +33,12 @@ export class IterableEmbeddedManager {
callback: () => void,
placementIds?: number[]
) {
await this.retrieveEmbeddedMessages(packageName, placementIds || []);
callback();
if (typeOfAuth !== null) {
await this.retrieveEmbeddedMessages(packageName, placementIds || []);
callback();
} else {
Promise.reject(INITIALIZE_ERROR);
}
}

private async retrieveEmbeddedMessages(
Expand Down
24 changes: 21 additions & 3 deletions src/events/embedded/events.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { WEB_PLATFORM, ENDPOINTS } from '../../constants';
import { WEB_PLATFORM, ENDPOINTS, INITIALIZE_ERROR } from '../../constants';
import { baseIterableRequest } from '../../request';
import {
IterableEmbeddedDismissRequestPayload,
Expand All @@ -12,12 +12,17 @@ import {
embeddedDismissSchema,
embeddedSessionSchema
} from './events.schema';
import { typeOfAuth } from '../../authorization';

export const trackEmbeddedReceived = (
messageId: string,
appPackageName: string
) =>
baseIterableRequest<IterableResponse>({
) => {
if (typeOfAuth === null) {
return Promise.reject(INITIALIZE_ERROR);
}

return baseIterableRequest<IterableResponse>({
method: 'POST',
url: ENDPOINTS.msg_received_event_track.route,
data: {
Expand All @@ -32,12 +37,17 @@ export const trackEmbeddedReceived = (
data: trackEmbeddedSchema
}
});
};

export const trackEmbeddedClick = (
payload: IterableEmbeddedClickRequestPayload
) => {
const { appPackageName, ...rest } = payload;

if (typeOfAuth === null) {
return Promise.reject(INITIALIZE_ERROR);
}

return baseIterableRequest<IterableResponse>({
method: 'POST',
url: ENDPOINTS.msg_click_event_track.route,
Expand All @@ -61,6 +71,10 @@ export const trackEmbeddedDismiss = (
) => {
const { appPackageName, ...rest } = payload;

if (typeOfAuth === null) {
return Promise.reject(INITIALIZE_ERROR);
}

return baseIterableRequest<IterableResponse>({
method: 'POST',
url: ENDPOINTS.msg_dismiss.route,
Expand All @@ -84,6 +98,10 @@ export const trackEmbeddedSession = (
) => {
const { appPackageName, ...rest } = payload;

if (typeOfAuth === null) {
return Promise.reject(INITIALIZE_ERROR);
}

return baseIterableRequest<IterableResponse>({
method: 'POST',
url: ENDPOINTS.msg_session_event_track.route,
Expand Down
Loading
Loading