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

feat: fetching of a secured Algolia key [BB-8083][BACKPORT] #2

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
2 changes: 1 addition & 1 deletion src/components/enterprise-page/EnterprisePage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export default function EnterprisePage({ children, useEnterpriseConfigCache }) {
const { enterpriseSlug } = useParams();
const [enterpriseConfig, fetchError] = useEnterpriseCustomerConfig(enterpriseSlug, useEnterpriseConfigCache);
const config = getConfig();
const [searchClient, searchIndex] = useAlgoliaSearch(config);
const [searchClient, searchIndex] = useAlgoliaSearch(config, config.ALGOLIA_INDEX_NAME);
const user = getAuthenticatedUser();
const { profileImage } = user;

Expand Down
14 changes: 2 additions & 12 deletions src/components/search/Search.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { AppContext } from '@edx/frontend-platform/react';
import { getConfig } from '@edx/frontend-platform/config';
import { SearchHeader, SearchContext } from '@edx/frontend-enterprise-catalog-search';

import algoliasearch from 'algoliasearch/lite';
import { useAlgoliaSearch } from "../../utils/hooks";
import { useDefaultSearchFilters } from './data/hooks';
import {
NUM_RESULTS_PER_PAGE,
Expand Down Expand Up @@ -42,17 +42,7 @@ const Search = () => {
});

const config = getConfig();
const courseIndex = useMemo(
() => {
const client = algoliasearch(
config.ALGOLIA_APP_ID,
config.ALGOLIA_SEARCH_API_KEY,
);
const cIndex = client.initIndex(config.ALGOLIA_INDEX_NAME);
return cIndex;
},
[], // only initialized once
);
const [courseIndex] = useAlgoliaSearch(config, config.ALGOLIA_INDEX_NAME);
const PAGE_TITLE = `${HEADER_TITLE} - ${enterpriseConfig.name}`;

return (
Expand Down
18 changes: 4 additions & 14 deletions src/components/skills-quiz/SkillsQuizStepper.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import React, { useEffect, useState, useContext, useMemo } from 'react';
import {
Button, Stepper, ModalDialog, Container, Form,
} from '@edx/paragon';
import algoliasearch from 'algoliasearch/lite';
import { InstantSearch, Configure } from 'react-instantsearch-dom';
import { getConfig } from '@edx/frontend-platform/config';
import { SearchContext, removeFromRefinementArray, deleteRefinementAction } from '@edx/frontend-enterprise-catalog-search';
Expand All @@ -25,6 +24,7 @@ import SelectJobCard from './SelectJobCard';
import TagCloud from '../TagCloud';
import SkillsCourses from './SkillsCourses';

import { useAlgoliaSearch } from "../../utils/hooks";
import { useDefaultSearchFilters } from '../search/data/hooks';
import { UserSubsidyContext } from '../enterprise-user-subsidy';
import {
Expand All @@ -42,18 +42,8 @@ const SkillsQuizStepper = () => {
const config = getConfig();
const { userId } = getAuthenticatedUser();
const isFirstRender = useIsFirstRender();
const [searchClient, courseIndex, jobIndex] = useMemo(
() => {
const client = algoliasearch(
config.ALGOLIA_APP_ID,
config.ALGOLIA_SEARCH_API_KEY,
);
const cIndex = client.initIndex(config.ALGOLIA_INDEX_NAME);
const jIndex = client.initIndex(config.ALGOLIA_INDEX_NAME_JOBS);
return [client, cIndex, jIndex];
},
[], // only initialized once
);
const [courseIndex] = useAlgoliaSearch(config, config.ALGOLIA_INDEX_NAME);
const [jobSearchClient, jobIndex] = useAlgoliaSearch(config, config.ALGOLIA_INDEX_NAME_JOBS);
const [currentStep, setCurrentStep] = useState(STEP1);
const [isStudentChecked, setIsStudentChecked] = useState(false);
const handleIsStudentCheckedChange = e => setIsStudentChecked(e.target.checked);
Expand Down Expand Up @@ -226,7 +216,7 @@ const SkillsQuizStepper = () => {

<InstantSearch
indexName={config.ALGOLIA_INDEX_NAME_JOBS}
searchClient={searchClient}
searchClient={jobSearchClient}
>
<div className="col col-8 p-0 mt-3">
<CurrentJobDropdown />
Expand Down
2 changes: 2 additions & 0 deletions src/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ initialize({
LICENSE_MANAGER_URL: process.env.LICENSE_MANAGER_URL || null,
ALGOLIA_APP_ID: process.env.ALGOLIA_APP_ID || null,
ALGOLIA_SEARCH_API_KEY: process.env.ALGOLIA_SEARCH_API_KEY || null,
ALGOLIA_SECURED_KEY_ENDPOINT: process.env.ALGOLIA_SECURED_KEY_ENDPOINT ||
`${process.env.LMS_BASE_URL}/enterprise/api/v1/enterprise-customer/algolia_key/`,
ALGOLIA_INDEX_NAME: process.env.ALGOLIA_INDEX_NAME || null,
ALGOLIA_INDEX_NAME_JOBS: process.env.ALGOLIA_INDEX_NAME_JOBS || null,
INTEGRATION_WARNING_DISMISSED_COOKIE_NAME: process.env.INTEGRATION_WARNING_DISMISSED_COOKIE_NAME || null,
Expand Down
17 changes: 17 additions & 0 deletions src/utils/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import moment from 'moment';
import Cookies from 'universal-cookie';
import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth';
import { getConfig } from '@edx/frontend-platform/config';
import { logError } from '@edx/frontend-platform/logging';

export const isCourseEnded = endDate => moment(endDate) < moment();

Expand Down Expand Up @@ -66,6 +67,22 @@ export const loginRefresh = async () => {
}
};

export const fetchAlgoliaSecuredApiKey = async () => {
const config = getConfig();
const httpClient = getAuthenticatedHttpClient();

try {
const response = await httpClient.get(config.ALGOLIA_SECURED_KEY_ENDPOINT);
if (response && response.data) {
return response.data.key;
}
throw new Error('Response does not contain data');
} catch (error) {
logError(error);
return null;
}
};

export const fixedEncodeURIComponent = (str) => encodeURIComponent(str).replace(/[!()*]/g, (c) => `%${ c.charCodeAt(0).toString(16)}`);

export const formatStringAsNumber = (str, radix = 10) => {
Expand Down
36 changes: 31 additions & 5 deletions src/utils/hooks.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import React, { useCallback, useMemo } from 'react';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import algoliasearch from 'algoliasearch';

import { fetchAlgoliaSecuredApiKey } from './common';

export const useRenderContactHelpText = (enterpriseConfig) => {
const renderContactHelpText = useCallback(
(LinkComponent = 'a') => {
Expand All @@ -22,17 +24,41 @@ export const useRenderContactHelpText = (enterpriseConfig) => {
return renderContactHelpText;
};

export const useAlgoliaSearch = (config) => {
let cachedApiKey = null;

export const useAlgoliaSearchApiKey = (config) => {
// If the search API key is not provided in the config,
// fetch it from `ALGOLIA_SECURED_KEY_ENDPOINT`.

const [searchApiKey, setSearchApiKey] = useState(cachedApiKey || config.ALGOLIA_SEARCH_API_KEY);

useEffect(() => {
const fetchApiKey = async () => {
const key = await fetchAlgoliaSecuredApiKey();
cachedApiKey = key;
setSearchApiKey(key);
};

if (!searchApiKey) {
fetchApiKey();
}
}, [searchApiKey]);

return searchApiKey;
}

export const useAlgoliaSearch = (config, indexName) => {
const algoliaSearchApiKey = useAlgoliaSearchApiKey(config);
const [searchClient, searchIndex] = useMemo(
() => {
const client = algoliasearch(
config.ALGOLIA_APP_ID,
config.ALGOLIA_SEARCH_API_KEY,
algoliaSearchApiKey,
);
const index = client.initIndex(config.ALGOLIA_INDEX_NAME);
const index = client.initIndex(indexName || config.ALGOLIA_INDEX_NAME);
return [client, index];
},
[JSON.stringify(config)],
[config.ALGOLIA_APP_ID, config.ALGOLIA_INDEX_NAME, algoliaSearchApiKey, indexName],
);
return [searchClient, searchIndex];
};