Skip to content

Commit

Permalink
Add authentication header to UI requests in prod mode
Browse files Browse the repository at this point in the history
  • Loading branch information
chriswilty committed Mar 6, 2024
1 parent 9fbe7a4 commit 504774e
Show file tree
Hide file tree
Showing 9 changed files with 45 additions and 47 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ describe('HandbookSystemRole component tests', () => {
{ level: LEVEL_NAMES.LEVEL_2, systemRole: level2SystemRole },
{ level: LEVEL_NAMES.LEVEL_3, systemRole: level3SystemRole },
];
const emptySystemRoles: LevelSystemRole[] = [];

test('renders no system roles and instead renders locked boxes when no levels complete', () => {
const numLevelsCompleted = 0;
Expand Down Expand Up @@ -135,7 +134,7 @@ describe('HandbookSystemRole component tests', () => {
render(
<HandbookSystemRole
numCompletedLevels={numLevelsCompleted}
systemRoles={emptySystemRoles}
systemRoles={[]}
/>
);

Expand Down
30 changes: 28 additions & 2 deletions frontend/src/service/backendService.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { fetchAuthSession } from '@aws-amplify/auth';

function getBackendUrl(): string {
const url = import.meta.env.VITE_BACKEND_URL;
if (!url) throw new Error('VITE_BACKEND_URL env variable not set');
Expand All @@ -8,8 +10,32 @@ function makeUrl(path: string): URL {
return new URL(path, getBackendUrl());
}

async function sendRequest(path: string, options: RequestInit) {
return fetch(makeUrl(path), { ...options, credentials: 'include' });
type RequestOptions<T> = Pick<RequestInit, 'method' | 'signal'> & {
body?: T;
};

async function sendRequest<T>(path: string, options: RequestOptions<T> = {}) {
const { method = 'GET', body, signal } = options;
// No auth in dev mode
const auth: Record<string, string> = import.meta.env.MODE === 'production' ? {
Authorization: (await fetchAuthSession()).tokens?.accessToken.toString() ?? ''
} : {};

// Body is always JSON, if present
const contentType: Record<string, string> = body ? {
'Content-Type': 'application/json'
} : {};

return fetch(makeUrl(path), {
method,
body: body && JSON.stringify(body),
signal,
credentials: 'include',
headers: {
...auth,
...contentType,
}
});
}

export { getBackendUrl, sendRequest };
24 changes: 8 additions & 16 deletions frontend/src/service/chatService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,22 +15,17 @@ const PATH = 'openai/';
async function clearChat(level: number) {
const response = await sendRequest(`${PATH}clear`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ level }),
body: { level },
});
return response.status === 200;
}

async function sendMessage(message: string, currentLevel: LEVEL_NAMES) {
const response = await sendRequest(`${PATH}chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message, currentLevel }),
body: { message, currentLevel },
});
const data = (await response.json()) as ChatResponse;
return data;
return (await response.json()) as ChatResponse;
}

function makeChatMessageFromDTO(chatMessageDTO: ChatMessageDTO): ChatMessage {
Expand Down Expand Up @@ -69,8 +64,7 @@ function getChatMessagesFromDTOResponse(chatMessageDTOs: ChatMessageDTO[]) {
async function setGptModel(model: string): Promise<boolean> {
const response = await sendRequest(`${PATH}model`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model }),
body: { model },
});
return response.status === 200;
}
Expand All @@ -81,14 +75,13 @@ async function configureGptModel(
): Promise<boolean> {
const response = await sendRequest(`${PATH}model/configure`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ configId, value }),
body: { configId, value },
});
return response.status === 200;
}

async function getGptModel(): Promise<ChatModel> {
const response = await sendRequest(`${PATH}model`, { method: 'GET' });
const response = await sendRequest(`${PATH}model`);
return (await response.json()) as ChatModel;
}

Expand All @@ -99,12 +92,11 @@ async function addInfoMessageToChatHistory(
) {
const response = await sendRequest(`${PATH}addInfoToHistory`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
body: {
infoMessage: message,
chatMessageType,
level,
}),
},
});
return response.status === 200;
}
Expand Down
15 changes: 3 additions & 12 deletions frontend/src/service/defenceService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,7 @@ async function toggleDefence(
const requestPath = isActive ? 'deactivate' : 'activate';
const response = await sendRequest(`${PATH}${requestPath}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ defenceId, level }),
body: { defenceId, level },
});
return response.status === 200;
}
Expand All @@ -55,10 +52,7 @@ async function configureDefence(
): Promise<boolean> {
const response = await sendRequest(`${PATH}configure`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ defenceId, config, level }),
body: { defenceId, config, level },
});
return response.status === 200;
}
Expand All @@ -69,10 +63,7 @@ async function resetDefenceConfig(
): Promise<DefenceResetResponse> {
const response = await sendRequest(`${PATH}resetConfig`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ defenceId, configId }),
body: { defenceId, configId },
});
return (await response.json()) as DefenceResetResponse;
}
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/service/documentService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import { getBackendUrl, sendRequest } from './backendService';

const PATH = 'documents';

async function getDocumentMetas(signal?: AbortSignal): Promise<DocumentMeta[]> {
const response = await sendRequest(PATH, { method: 'GET', signal });
async function getDocumentMetas(signal: AbortSignal): Promise<DocumentMeta[]> {
const response = await sendRequest(PATH, { signal });
let documentMetas = (await response.json()) as DocumentMeta[];
documentMetas = documentMetas.map((documentMeta) => {
return {
Expand Down
5 changes: 1 addition & 4 deletions frontend/src/service/emailService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,7 @@ const PATH = 'email/';
async function clearEmails(level: number): Promise<boolean> {
const response = await sendRequest(`${PATH}clear`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ level }),
body: { level },
});
return response.status === 200;
}
Expand Down
4 changes: 1 addition & 3 deletions frontend/src/service/levelService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@ import { getDefencesFromDTOs } from './defenceService';
const PATH = 'level';

async function loadLevel(level: number) {
const response = await sendRequest(`${PATH}?level=${level}`, {
method: 'GET',
});
const response = await sendRequest(`${PATH}?level=${level}`);
const { defences, emails, chatHistory } =
(await response.json()) as LoadLevelResponse;

Expand Down
3 changes: 0 additions & 3 deletions frontend/src/service/resetService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@ const PATH = 'reset';
async function resetAllLevelProgress(): Promise<boolean> {
const response = await sendRequest(PATH, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
return response.status === 200;
}
Expand Down
4 changes: 1 addition & 3 deletions frontend/src/service/startService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@ import { getDefencesFromDTOs } from './defenceService';
const PATH = 'start/';

async function start(level: number) {
const response = await sendRequest(`${PATH}?level=${level}`, {
method: 'GET',
});
const response = await sendRequest(`${PATH}?level=${level}`);
const { availableModels, defences, emails, chatHistory, systemRoles } =
(await response.json()) as StartReponse;

Expand Down

0 comments on commit 504774e

Please sign in to comment.