Skip to content

Commit fc45b22

Browse files
committed
merge new amp util into existing access token util
1 parent e4425c3 commit fc45b22

File tree

6 files changed

+98
-98
lines changed

6 files changed

+98
-98
lines changed

frontend/src/__tests__/middleware.test.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,12 @@
22
* @jest-environment node
33
*/
44
import { NextRequest } from 'next/server';
5-
import { getAccessTokenServer } from '@utils/amplify-utils';
5+
import { getSessionServer } from '@utils/amplify-utils';
66
import { middleware } from '../middleware';
77

88
jest.mock('@utils/amplify-utils');
99

10-
const getTokenMock = jest.mocked(getAccessTokenServer);
10+
const getTokenMock = jest.mocked(getSessionServer);
1111

1212
function getCsp(response: Response) {
1313
const csp = response.headers.get('Content-Security-Policy');
@@ -46,7 +46,7 @@ describe('middleware function', () => {
4646
});
4747

4848
it('if request path is protected, and access token is obtained, respond with CSP', async () => {
49-
getTokenMock.mockResolvedValueOnce('token');
49+
getTokenMock.mockResolvedValueOnce({ accessToken: 'token', sub: 'sub' });
5050

5151
const url = new URL('https://url.com/message-templates');
5252
const request = new NextRequest(url);

frontend/src/__tests__/utils/amplify-utils.test.ts

Lines changed: 10 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,7 @@
33
*/
44
import { sign } from 'jsonwebtoken';
55
import { fetchAuthSession } from 'aws-amplify/auth/server';
6-
import {
7-
getAccessTokenServer,
8-
getSessionId,
9-
getSubServer,
10-
} from '../../utils/amplify-utils';
6+
import { getSessionServer, getSessionId } from '../../utils/amplify-utils';
117

128
jest.mock('aws-amplify/auth/server');
139
jest.mock('@aws-amplify/adapter-nextjs/api');
@@ -23,65 +19,38 @@ jest.mock('@/amplify_outputs.json', () => ({
2319
const fetchAuthSessionMock = jest.mocked(fetchAuthSession);
2420

2521
describe('amplify-utils', () => {
26-
test('getAccessTokenServer - should return the auth token', async () => {
22+
test('getSessionServer - should return the auth token and sub', async () => {
2723
fetchAuthSessionMock.mockResolvedValueOnce({
2824
tokens: {
2925
accessToken: {
3026
toString: () => 'mockToken',
3127
payload: {},
3228
},
3329
},
34-
});
35-
36-
const result = await getAccessTokenServer();
37-
38-
expect(result).toEqual('mockToken');
39-
});
40-
41-
test('getAccessTokenServer - should return undefined when no auth session', async () => {
42-
fetchAuthSessionMock.mockResolvedValueOnce({});
43-
44-
const result = await getAccessTokenServer();
45-
46-
expect(result).toBeUndefined();
47-
});
48-
49-
test('getAccessTokenServer - should return undefined an error occurs', async () => {
50-
fetchAuthSessionMock.mockImplementationOnce(() => {
51-
throw new Error('JWT Expired');
52-
});
53-
54-
const result = await getAccessTokenServer();
55-
56-
expect(result).toBeUndefined();
57-
});
58-
59-
test('getSubServer - should return the user subject', async () => {
60-
fetchAuthSessionMock.mockResolvedValueOnce({
6130
userSub: 'sub',
6231
});
6332

64-
const result = await getSubServer();
33+
const result = await getSessionServer();
6534

66-
expect(result).toEqual('sub');
35+
expect(result).toEqual({ accessToken: 'mockToken', sub: 'sub' });
6736
});
6837

69-
test('getSubServer - should return undefined when no auth session', async () => {
38+
test('getSessionServer - should return undefined properties when no auth session', async () => {
7039
fetchAuthSessionMock.mockResolvedValueOnce({});
7140

72-
const result = await getSubServer();
41+
const result = await getSessionServer();
7342

74-
expect(result).toBeUndefined();
43+
expect(result).toEqual({ accessToken: undefined, sub: undefined });
7544
});
7645

77-
test('getSubServer - should return undefined an error occurs', async () => {
46+
test('getSessionServer - should return undefined properties if an error occurs', async () => {
7847
fetchAuthSessionMock.mockImplementationOnce(() => {
7948
throw new Error('JWT Expired');
8049
});
8150

82-
const result = await getSubServer();
51+
const result = await getSessionServer();
8352

84-
expect(result).toBeUndefined();
53+
expect(result).toEqual({ accessToken: undefined, sub: undefined });
8554
});
8655

8756
describe('getSessionId', () => {

frontend/src/__tests__/utils/form-actions.test.ts

Lines changed: 38 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,20 +16,23 @@ import {
1616
setTemplateToSubmitted,
1717
requestTemplateProof,
1818
} from '@utils/form-actions';
19-
import { getAccessTokenServer } from '@utils/amplify-utils';
19+
import { getSessionServer } from '@utils/amplify-utils';
2020
import { TemplateDto } from 'nhs-notify-backend-client';
2121
import { templateClient } from 'nhs-notify-backend-client/src/template-api-client';
2222

2323
const mockedTemplateClient = jest.mocked(templateClient);
24-
const authIdTokenServerMock = jest.mocked(getAccessTokenServer);
24+
const authIdTokenServerMock = jest.mocked(getSessionServer);
2525

2626
jest.mock('@utils/amplify-utils');
2727
jest.mock('nhs-notify-backend-client/src/template-api-client');
2828

2929
describe('form-actions', () => {
3030
beforeEach(() => {
3131
jest.resetAllMocks();
32-
authIdTokenServerMock.mockResolvedValueOnce('token');
32+
authIdTokenServerMock.mockResolvedValueOnce({
33+
accessToken: 'token',
34+
sub: 'sub',
35+
});
3336
});
3437

3538
test('createTemplate', async () => {
@@ -89,7 +92,10 @@ describe('form-actions', () => {
8992

9093
test('createTemplate - should throw error when no token', async () => {
9194
authIdTokenServerMock.mockReset();
92-
authIdTokenServerMock.mockResolvedValueOnce(undefined);
95+
authIdTokenServerMock.mockResolvedValueOnce({
96+
accessToken: undefined,
97+
sub: undefined,
98+
});
9399

94100
const createTemplateInput: CreateUpdateNHSAppTemplate = {
95101
templateType: 'NHS_APP',
@@ -249,7 +255,10 @@ describe('form-actions', () => {
249255

250256
test('createLetterTemplate - should throw error when no token', async () => {
251257
authIdTokenServerMock.mockReset();
252-
authIdTokenServerMock.mockResolvedValueOnce(undefined);
258+
authIdTokenServerMock.mockResolvedValueOnce({
259+
accessToken: undefined,
260+
sub: undefined,
261+
});
253262

254263
const createLetterTemplateInput: CreateLetterTemplate = {
255264
templateType: 'LETTER',
@@ -337,7 +346,10 @@ describe('form-actions', () => {
337346

338347
test('saveTemplate - should throw error when no token', async () => {
339348
authIdTokenServerMock.mockReset();
340-
authIdTokenServerMock.mockResolvedValueOnce(undefined);
349+
authIdTokenServerMock.mockResolvedValueOnce({
350+
accessToken: undefined,
351+
sub: undefined,
352+
});
341353

342354
const updateTemplateInput: NHSAppTemplate = {
343355
id: 'id',
@@ -400,7 +412,10 @@ describe('form-actions', () => {
400412

401413
test('getTemplate - should throw error when no token', async () => {
402414
authIdTokenServerMock.mockReset();
403-
authIdTokenServerMock.mockResolvedValueOnce(undefined);
415+
authIdTokenServerMock.mockResolvedValueOnce({
416+
accessToken: undefined,
417+
sub: undefined,
418+
});
404419

405420
await expect(getTemplate('id')).rejects.toThrow(
406421
'Failed to get access token'
@@ -445,7 +460,10 @@ describe('form-actions', () => {
445460

446461
test('getTemplates - should throw error when no token', async () => {
447462
authIdTokenServerMock.mockReset();
448-
authIdTokenServerMock.mockResolvedValueOnce(undefined);
463+
authIdTokenServerMock.mockResolvedValueOnce({
464+
accessToken: undefined,
465+
sub: undefined,
466+
});
449467

450468
await expect(getTemplates()).rejects.toThrow('Failed to get access token');
451469
});
@@ -533,7 +551,10 @@ describe('form-actions', () => {
533551

534552
test('submitTemplate - should throw error when no token', async () => {
535553
authIdTokenServerMock.mockReset();
536-
authIdTokenServerMock.mockResolvedValueOnce(undefined);
554+
authIdTokenServerMock.mockResolvedValueOnce({
555+
accessToken: undefined,
556+
sub: undefined,
557+
});
537558

538559
await expect(setTemplateToSubmitted('id')).rejects.toThrow(
539560
'Failed to get access token'
@@ -577,7 +598,10 @@ describe('form-actions', () => {
577598

578599
test('deleteTemplate - should throw error when no token', async () => {
579600
authIdTokenServerMock.mockReset();
580-
authIdTokenServerMock.mockResolvedValueOnce(undefined);
601+
authIdTokenServerMock.mockResolvedValueOnce({
602+
accessToken: undefined,
603+
sub: undefined,
604+
});
581605

582606
await expect(setTemplateToDeleted('id')).rejects.toThrow(
583607
'Failed to get access token'
@@ -639,7 +663,10 @@ describe('form-actions', () => {
639663

640664
test('requestTemplateProof - should throw error when no token', async () => {
641665
authIdTokenServerMock.mockReset();
642-
authIdTokenServerMock.mockResolvedValueOnce(undefined);
666+
authIdTokenServerMock.mockResolvedValueOnce({
667+
accessToken: undefined,
668+
sub: undefined,
669+
});
643670

644671
await expect(requestTemplateProof('id')).rejects.toThrow(
645672
'Failed to get access token'

frontend/src/middleware.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { NextResponse, type NextRequest } from 'next/server';
2-
import { getAccessTokenServer } from '@utils/amplify-utils';
2+
import { getSessionServer } from '@utils/amplify-utils';
33
import { getBasePath } from '@utils/get-base-path';
44

55
const protectedPaths = [
@@ -95,9 +95,9 @@ export async function middleware(request: NextRequest) {
9595
return new NextResponse('Page not found', { status: 404 });
9696
}
9797

98-
const token = await getAccessTokenServer({ forceRefresh: true });
98+
const { accessToken } = await getSessionServer({ forceRefresh: true });
9999

100-
if (!token) {
100+
if (!accessToken) {
101101
const redirectResponse = NextResponse.redirect(
102102
new URL(
103103
`/auth?redirect=${encodeURIComponent(

frontend/src/utils/amplify-utils.ts

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -14,21 +14,24 @@ export const { runWithAmplifyServerContext } = createServerRunner({
1414
config,
1515
});
1616

17-
export async function getAccessTokenServer(
17+
export async function getSessionServer(
1818
options: FetchAuthSessionOptions = {}
19-
): Promise<string | undefined> {
19+
): Promise<{ accessToken: string | undefined; sub: string | undefined }> {
2020
const session = await runWithAmplifyServerContext({
2121
nextServerContext: { cookies },
2222
operation: (ctx) => fetchAuthSession(ctx, options),
2323
}).catch(() => {
2424
// no-op
2525
});
2626

27-
return session?.tokens?.accessToken?.toString();
27+
return {
28+
accessToken: session?.tokens?.accessToken?.toString(),
29+
sub: session?.userSub,
30+
};
2831
}
2932

3033
export const getSessionId = async () => {
31-
const accessToken = await getAccessTokenServer();
34+
const { accessToken } = await getSessionServer();
3235

3336
if (!accessToken) {
3437
return;
@@ -44,14 +47,3 @@ export const getSessionId = async () => {
4447

4548
return sessionId.toString();
4649
};
47-
48-
export async function getSubServer(): Promise<string | undefined> {
49-
const session = await runWithAmplifyServerContext({
50-
nextServerContext: { cookies },
51-
operation: (ctx) => fetchAuthSession(ctx),
52-
}).catch(() => {
53-
// no-op
54-
});
55-
56-
return session?.userSub;
57-
}

0 commit comments

Comments
 (0)