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

Updates notification unsubscribe logic (Gets data from Notification table instead of JWT) #45

Merged
merged 9 commits into from
Oct 26, 2023
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
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
import '@testing-library/jest-dom';
import { AxiosError } from 'axios';
import { decryptSignedApiKey } from '../../../src/service/api-key-service';
import { NewsletterSubscriptionService } from '../../../src/service/newsletter/newsletter-subscription-service';
import { getServerSideProps } from '../../../pages/unsubscribe/[jwt]';
import { TokenExpiredError } from 'jsonwebtoken';
import { getServerSideProps } from '../../../pages/unsubscribe/[id]';
import { SubscriptionService } from '../../../src/service/subscription-service';
import { deleteSaveSearch } from '../../../src/service/saved_search_service';
import { getUnsubscribeReferenceFromId } from '../../../src/service/unsubscribe.service';

jest.mock('../../../pages/service-error/index.page', () => ({
default: () => <p>ServiceErrorPage</p>,
}));
jest.mock('../../../src/service/api-key-service', () => ({
decryptSignedApiKey: jest.fn(),
}));
jest.mock('../../../src/utils/encryption', () => ({
decrypt: jest.fn(),
}));
Expand All @@ -29,6 +25,13 @@ jest.mock('../../../src/service/subscription-service', () => ({
getInstance: jest.fn(),
},
}));
jest.mock('../../../src/service/unsubscribe.service', () => ({
getUnsubscribeReferenceFromId: jest.fn(),
removeUnsubscribeReference: jest.fn(),
getTypeFromNotificationIds: jest.requireActual(
'../../../src/service/unsubscribe.service',
).getTypeFromNotificationIds,
}));
jest.mock('../../../src/service/saved_search_service');

const newsletterSubscriptionServiceSpy = ({ throwsError }) =>
Expand Down Expand Up @@ -67,20 +70,15 @@ const mockSavedSearch = ({ throwsError }) => {
});
};

const getContext = ({ jwt }) => ({
query: {
jwt,
},
});

describe('getServerSideProps()', () => {
beforeEach(jest.clearAllMocks);

it('should return error when jwt has expired', async () => {
decryptSignedApiKey.mockImplementation(() => {
throw new TokenExpiredError();
});
const context = getContext({ jwt: 'invalid-jwt' });
it('should return error when the token is invalid ', async () => {
getUnsubscribeReferenceFromId.mockReturnValue(
new AxiosError('Internal server error'),
);

const context = getContext({ id: 'invalid-id' });
const response = await getServerSideProps(context);

expect(response).toEqual({
Expand All @@ -99,17 +97,14 @@ describe('getServerSideProps()', () => {
${'GRANT_SUBSCRIPTION'} | ${grantSubscriptionSpy} | ${false}
${'SAVED_SEARCH'} | ${mockSavedSearch} | ${false}
`(
'should return correct props when jwt is valid and $type mock service is called with throwsError: $mockServiceThrowsError',
'should return correct props when id is valid and $type mock service is called with throwsError: $mockServiceThrowsError',
async ({ type, mockServiceFunction, mockServiceThrowsError }) => {
decryptSignedApiKey.mockReturnValue({
id: 'some-id',
type,
emailAddress: 'some-email',
});
getUnsubscribeReferenceFromId.mockReturnValue(
getMockUnsubscribeReferenceData(type),
);
const context = getContext({ jwt: 'valid.jwt.token' });
mockServiceFunction({ throwsError: mockServiceThrowsError });
const response = await getServerSideProps(context);

expect(response).toEqual({
props: {
error: mockServiceThrowsError,
Expand All @@ -118,3 +113,34 @@ describe('getServerSideProps()', () => {
},
);
});

const getContext = ({ id }) => ({
query: {
id,
},
});

const TEST_USER_DATA_MAP = {
NEWSLETTER: {
newsletterId: 'some-newsletter-id',
subscriptionId: null,
savedSearchId: null,
},
GRANT_SUBSCRIPTION: {
newsletterId: null,
subscriptionId: 'some-subscription-id',
savedSearchId: null,
},
SAVED_SEARCH: {
newsletterId: null,
subscriptionId: null,
savedSearchId: 'some-saved-search-id',
},
};

const getMockUnsubscribeReferenceData = (type) => ({
user: {
encryptedEmailAddress: 'some-email',
},
...TEST_USER_DATA_MAP[type],
});
2 changes: 1 addition & 1 deletion __tests__/service/subscription_service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ describe('subscription manager delete Subscription By ID', () => {

expect(instance.delete).toHaveBeenNthCalledWith(
1,
'users/fake%40fake.com/grants/12345678',
'users/fake%40fake.com/grants/12345678?unsubscribeReference=undefined',
);
expect(result).toBe(true);
});
Expand Down
99 changes: 71 additions & 28 deletions pages/unsubscribe/[jwt].tsx → pages/unsubscribe/[id].tsx
Original file line number Diff line number Diff line change
@@ -1,78 +1,108 @@
import Head from 'next/head';
import Link from 'next/link';
import Layout from '../../src/components/partials/Layout';
import { decryptSignedApiKey } from '../../src/service/api-key-service';
import { SubscriptionService } from '../../src/service/subscription-service';
import { decrypt } from '../../src/utils/encryption';
import { NewsletterSubscriptionService } from '../../src/service/newsletter/newsletter-subscription-service';
import { NewsletterType } from '../../src/types/newsletter';
import { deleteSaveSearch } from '../../src/service/saved_search_service';
import ServiceErrorPage from '../service-error/index.page';
import {
getTypeFromNotificationIds,
getUnsubscribeReferenceFromId,
} from '../../src/service/unsubscribe.service';

export async function getServerSideProps({ query: { jwt = '' } = {} }) {
export async function getServerSideProps({ query: { id = '' } = {} }) {
let emailAddress: string,
type: keyof typeof UNSUBSCRIBE_HANDLER_MAP,
id: NotificationKey;
notificationId: NotificationKey,
notificationType: keyof typeof UNSUBSCRIBE_HANDLER_MAP;
try {
const decodedJwt = decryptSignedApiKey(jwt);
type = decodedJwt.type;
id = decodedJwt.id;
emailAddress = await decrypt(decodedJwt.emailAddress);
await handleUnsubscribe(type, id, emailAddress);
const {
user: { encryptedEmailAddress },
subscriptionId,
newsletterId,
savedSearchId,
} = await getUnsubscribeReferenceFromId(id as string);

notificationType = getTypeFromNotificationIds({
subscriptionId,
newsletterId,
savedSearchId,
});
emailAddress = await decrypt(encryptedEmailAddress);
notificationId = subscriptionId ?? newsletterId ?? savedSearchId;

await handleUnsubscribe(notificationType, notificationId, emailAddress, id);

return { props: { error: false } };
} catch (error: unknown) {
return handleServerSideError(error, { type, emailAddress, id });
return handleServerSideError(error, {
id,
emailAddress,
notificationId,
notificationType,
});
}
}

const handleServerSideError = (
error: unknown,
{
type,
id,
notificationId,
emailAddress,
}: {
type: keyof typeof UNSUBSCRIBE_HANDLER_MAP;
id: NotificationKey;
emailAddress: string;
},
notificationType,
}: HandleServerSideErrorProps,
) => {
if (!type || !id || !emailAddress) {
console.error('Failed to decrypt jwt. Error: ' + JSON.stringify(error));
if (!notificationId || !emailAddress) {
console.error(
`Failed to get user from notification with type: ${notificationType}, id: ${id}. Error: ${JSON.stringify(
error,
)}`,
);
} else {
console.error(
`Failed to unsubscribe from notification type: ${type}, id: ${id}, with email: ${emailAddress}. Error: ${JSON.stringify(
`Failed to unsubscribe from notification id: ${notificationId}, with email: ${emailAddress}. Error: ${JSON.stringify(
error,
)}`,
);
}

return { props: { error: true } };
};

const grantSubscriptionHandler = async (
id: NotificationKey,
emailAddress: string,
unsubscribeReferenceId: string,
) => {
const subscriptionService = SubscriptionService.getInstance();

return subscriptionService.deleteSubscriptionByEmailAndGrantId(
emailAddress,
id as string,
unsubscribeReferenceId,
);
};

const newsletterHandler = async (id: NotificationKey, emailAddress: string) => {
const newsletterHandler = async (
id: NotificationKey,
emailAddress: string,
unsubscribeReferenceId: string,
) => {
const newsletterSubscriptionService =
NewsletterSubscriptionService.getInstance();

return newsletterSubscriptionService.unsubscribeFromNewsletter(
emailAddress,
id as NewsletterType,
unsubscribeReferenceId,
);
};

const savedSearchHandler = async (id: NotificationKey, emailAddress: string) =>
deleteSaveSearch(id as number, emailAddress);
const savedSearchHandler = async (
id: NotificationKey,
emailAddress: string,
unsubscribeReferenceId: string,
) => deleteSaveSearch(id as number, emailAddress, unsubscribeReferenceId);

const UNSUBSCRIBE_HANDLER_MAP = {
GRANT_SUBSCRIPTION: grantSubscriptionHandler,
Expand All @@ -82,11 +112,15 @@ const UNSUBSCRIBE_HANDLER_MAP = {

const handleUnsubscribe = async (
type: keyof typeof UNSUBSCRIBE_HANDLER_MAP,
id: NotificationKey,
notificationKey: NotificationKey,
emailAddress: string,
) => UNSUBSCRIBE_HANDLER_MAP[type](id, emailAddress);

type NotificationKey = string | NewsletterType | number;
unsubscribeReferenceId: string,
) =>
UNSUBSCRIBE_HANDLER_MAP[type](
notificationKey,
emailAddress,
unsubscribeReferenceId,
);

const Unsubscribe = (props: undefined | { error: boolean }) => {
if (props.error) {
Expand Down Expand Up @@ -138,4 +172,13 @@ const Unsubscribe = (props: undefined | { error: boolean }) => {
);
};

type NotificationKey = string | NewsletterType | number;

type HandleServerSideErrorProps = {
id: string;
notificationId: NotificationKey;
notificationType: keyof typeof UNSUBSCRIBE_HANDLER_MAP;
emailAddress: string;
};

export default Unsubscribe;
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ describe('newsletter-subscription-service', () => {
);

expect(axiosInstance.delete).toHaveBeenCalledWith(
`/users/${email}/types/${NewsletterType.NEW_GRANTS}`,
`/users/${email}/types/${NewsletterType.NEW_GRANTS}?unsubscribeReference=undefined`,
);
});
});
Expand Down
3 changes: 2 additions & 1 deletion src/service/newsletter/newsletter-subscription-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,10 @@ export class NewsletterSubscriptionService {
async unsubscribeFromNewsletter(
plaintextEmail: string,
type: NewsletterType,
unsubscribeReferenceId?: string,
): Promise<void> {
return await NewsletterSubscriptionService.client.delete(
`/users/${plaintextEmail}/types/${type}`,
`/users/${plaintextEmail}/types/${type}?unsubscribeReference=${unsubscribeReferenceId}`,
);
}
}
2 changes: 1 addition & 1 deletion src/service/saved_search_service.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ describe('delete', () => {

expect(axios).toHaveBeenCalledWith({
method: 'post',
url: `${process.env.BACKEND_HOST}/saved-searches/${saveSearchId}/delete`,
url: `${process.env.BACKEND_HOST}/saved-searches/${saveSearchId}/delete?unsubscribeReference=undefined`,
data: {
email,
},
Expand Down
8 changes: 6 additions & 2 deletions src/service/saved_search_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,14 @@ export async function updateStatus(
return response.data;
}

export async function deleteSaveSearch(savedSearchId: number, email: string) {
export async function deleteSaveSearch(
savedSearchId: number,
email: string,
unsubscribeReferenceId: string,
) {
const response = await axios({
method: 'post',
url: `${process.env.BACKEND_HOST}/saved-searches/${savedSearchId}/delete`,
url: `${process.env.BACKEND_HOST}/saved-searches/${savedSearchId}/delete?unsubscribeReference=${unsubscribeReferenceId}`,
data: {
email,
},
Expand Down
9 changes: 6 additions & 3 deletions src/service/subscription-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,14 @@ export class SubscriptionService {
async deleteSubscriptionByEmailAndGrantId(
emailAddress: string,
grantId: string,
): Promise<Response> {
const endpoint: string = `${
unsubscribeReference?: string,
) {
const endpoint = `${
SubscriptionService.endpoint.emailParam + encodeURIComponent(emailAddress)
}/${SubscriptionService.endpoint.grantIdParam + grantId}`;
const result = await SubscriptionService.client.delete(endpoint);
const result = await SubscriptionService.client.delete(
endpoint + '?unsubscribeReference=' + unsubscribeReference,
);
return result.data;
}
}
Loading