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

Retrieve the API Key from the url parameters #416

Merged
merged 4 commits into from
Mar 20, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
44 changes: 43 additions & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ jobs:
with:
start: yarn start:ci
wait-on: 'http://0.0.0.0:3000'
command: yarn cy:run
command: yarn cy:run:test-no-api-key
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you double check that all the tests are being run? I recommend you check the cy:run command inside the package.json, which runs all the tests except some specific ones.

config-file: cypress.config.js
- uses: actions/upload-artifact@v3
if: failure()
Expand Down Expand Up @@ -137,3 +137,45 @@ jobs:
with:
name: cypress-videos
path: cypress/videos
cypress_meilisearch-api-key-query-param:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why didn't you put all of this inside the cypress_meilisearch-api-key above which already makes tests with a running Meilisearch instance + API key?

runs-on: ubuntu-latest
container:
image: cypress/browsers:node16.14.2-slim-chrome100-ff99-edge
options: --user 1001
services:
meilisearch:
image: getmeili/meilisearch:v0.30.5
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you want to update this to v1?

env:
MEILI_MASTER_KEY: 'masterKey'
MEILI_NO_ANALYTICS: 'true'
ports:
- '7700:7700'
steps:
- uses: actions/checkout@v3
- name: Setup node and cache
uses: actions/setup-node@v3
with:
node-version: 16
cache: "yarn"
cache-dependency-path: yarn.lock
- name: Install dependencies
run: yarn
- name: Test
uses: cypress-io/github-action@v4
env:
CYPRESS_host: http://meilisearch:7700
with:
start: yarn start:ci
wait-on: 'http://0.0.0.0:3000'
command: yarn cy:run:test-api-key-required
config-file: cypress.config.js
- uses: actions/upload-artifact@v3
if: failure()
with:
name: cypress-screenshots
path: cypress/screenshots
- uses: actions/upload-artifact@v3
if: failure()
with:
name: cypress-videos
path: cypress/videos
39 changes: 39 additions & 0 deletions cypress/e2e/test-api-key-query-param.cy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/* eslint-disable cypress/no-unnecessary-waiting */
const API_KEY = Cypress.env('apiKey')
const WAITING_TIME = Cypress.env('waitingTime')

describe(`Test API key required with query params`, () => {
before(() => {
cy.deleteAllIndexes()

cy.wait(WAITING_TIME)
cy.createIndex('movies')
cy.wait(WAITING_TIME)
cy.fixture('movies.json').then((movies) => {
cy.addDocuments('movies', movies)
cy.wait(WAITING_TIME)
})
})

beforeEach(() => {
cy.visit(`/?api_key=${API_KEY}`)
})

it('Should display the movies', () => {
cy.get('ul')
.children()
.should(($p) => {
expect($p).to.have.length(20)
})
})

it('Should have the api key written in the modal', () => {
// Test if the query parameter is written in the modal
// meaning it is added in the local storage
cy.get('span').contains('Api Key').parent().click()
cy.get('div[aria-label=settings-api-key]').within(() => {
cy.get('input[name="apiKey"]').should('have.value', API_KEY)
cy.get('button').contains('Go').click()
Copy link
Member

@mdubus mdubus Mar 14, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't really need this last line :)

})
})
})
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@
"cy:open": "cypress open",
"cy:run:test-no-meilisearch": "cypress run --spec '**/*/test-no-meilisearch.cy.js'",
"cy:run:test-api-key-required": "cypress run --spec '**/*/test-api-key-required.cy.js'",
"cy:run:test-api-key-query-param": "cypress run --spec '**/*/test-api-key-query-param.cy.js'",
"cy:run:test-no-api-key": "cypress run --spec '**/*/test-no-api-key-required.cy.js'",
"cy:run": "cypress run --config excludeSpecPattern=['**/*/test-no-meilisearch.cy.js','**/*/test-api-key-required.cy.js']",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Initially I had those commands for those specific tests:

  • cy:run:test-no-meilisearch : tests when there is no Meilisearch instance running
  • cy:run:test-api-key-required : tests that require a Meilisearch instance running + an API key
  • cy:run : tests that require a Meilisearch instance running (without an API key here for simplicity)

I had those 3 because I needed to run 3 different instances in the CI.
I don't really get why you added more commands in the package.json nor more jobs in the CI, but I'm available to discuss it of you want :)

"icons": "npx @svgr/cli --title-prop --no-dimensions --replace-attr-values \"#39486E=currentColor,#959DB3=currentColor\" -d src/components/icons src/components/icons/svg"
},
Expand Down
117 changes: 68 additions & 49 deletions src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import Modal from 'components/Modal'
import OnBoarding from 'components/OnBoarding'
import Results from 'components/Results'
import ApiKeyContext from 'context/ApiKeyContext'
import ClientContext from 'context/ClientContext'
import Typography from 'components/Typography'
import { MeiliSearch as Meilisearch } from 'meilisearch'

Expand Down Expand Up @@ -139,6 +138,13 @@ const App = () => {
}

React.useEffect(() => {
// Check if the API key is present on the url then put it in the local storage
const urlParams = new URLSearchParams(window.location.search)
const apiKeyParam = urlParams.get('api_key')
if (apiKeyParam) {
setApiKey(apiKeyParam)
}

// Check if an API key is required / a masterKey was set
const fetchWithoutApiKey = async () => {
try {
Expand All @@ -158,6 +164,25 @@ const App = () => {
getIndexesList()
}, [])

React.useEffect(() => {
if (apiKey) {
setISClient(
instantMeilisearch(baseUrl, apiKey, {
primaryKey: 'id',
clientAgents,
})
)

setMSClient(
new Meilisearch({
host: baseUrl,
apiKey,
clientAgents,
})
)
}
}, [apiKey])

// Check if a modal asking for API Key should be displayed
React.useEffect(() => {
const shouldDisplayModal = async () => {
Expand All @@ -176,55 +201,49 @@ const App = () => {
getIndexesList()
}, [MSClient, currentIndex?.uid])

const clientContext = React.useMemo(
() => ({ ISClient, MSClient, setISClient, setMSClient }),
[]
)
return (
<ClientContext.Provider value={clientContext}>
<ApiKeyContext.Provider value={{ apiKey, setApiKey }}>
<Wrapper>
<InstantSearch
indexName={currentIndex ? currentIndex.uid : ''}
searchClient={ISClient}
>
<Header
indexes={indexes}
currentIndex={currentIndex}
setCurrentIndex={setCurrentIndex}
requireApiKeyToWork={requireApiKeyToWork}
client={MSClient}
refreshIndexes={getIndexesList}
/>
<Body>
{/* <Sidebar /> */}
<Box
width={928}
m="0 auto"
py={4}
display="flex"
flexDirection="column"
>
{isMeilisearchRunning ? (
<Content currentIndex={currentIndex} />
) : (
<NoMeilisearchRunning />
)}
</Box>
</Body>
</InstantSearch>
<Modal
title={`Enter your admin API key${
requireApiKeyToWork ? '' : ' (optional)'
}`}
dialog={dialog}
ariaLabel="ask-for-api-key"
>
<ApiKeyModalContent closeModal={() => dialog.hide()} />
</Modal>
</Wrapper>
</ApiKeyContext.Provider>
</ClientContext.Provider>
<ApiKeyContext.Provider value={{ apiKey, setApiKey }}>
<Wrapper>
<InstantSearch
indexName={currentIndex ? currentIndex.uid : ''}
searchClient={ISClient}
>
<Header
indexes={indexes}
currentIndex={currentIndex}
setCurrentIndex={setCurrentIndex}
requireApiKeyToWork={requireApiKeyToWork}
client={MSClient}
refreshIndexes={getIndexesList}
/>
<Body>
{/* <Sidebar /> */}
<Box
width={928}
m="0 auto"
py={4}
display="flex"
flexDirection="column"
>
{isMeilisearchRunning ? (
<Content currentIndex={currentIndex} />
) : (
<NoMeilisearchRunning />
)}
</Box>
</Body>
</InstantSearch>
<Modal
title={`Enter your admin API key${
requireApiKeyToWork ? '' : ' (optional)'
}`}
dialog={dialog}
ariaLabel="ask-for-api-key"
>
<ApiKeyModalContent closeModal={() => dialog.hide()} />
</Modal>
</Wrapper>
</ApiKeyContext.Provider>
)
}

Expand Down
5 changes: 0 additions & 5 deletions src/components/ApiKeyModalContent.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import React from 'react'
import styled from 'styled-components'
import { MeiliSearch as Meilisearch } from 'meilisearch'
import { instantMeiliSearch as instantMeilisearch } from '@meilisearch/instant-meilisearch'

import { baseUrl } from 'App'
import Box from 'components/Box'
Expand All @@ -11,7 +10,6 @@ import Link from 'components/Link'
import Typography from 'components/Typography'

import ApiKeyContext from 'context/ApiKeyContext'
import ClientContext from 'context/ClientContext'

import clientAgents from '../version/client-agents'

Expand All @@ -22,7 +20,6 @@ const ErrorMessage = styled(Typography)`
`

const ApiKeyModalContent = ({ closeModal }) => {
const { setISClient, setMSClient } = React.useContext(ClientContext)
const { apiKey, setApiKey } = React.useContext(ApiKeyContext)
const [value, setValue] = React.useState(apiKey || '')
const [error, setError] = React.useState()
Expand All @@ -36,8 +33,6 @@ const ApiKeyModalContent = ({ closeModal }) => {
try {
await clientToTry.getIndexes()
setApiKey(value)
setISClient(instantMeilisearch(baseUrl, value, { clientAgents }))
setMSClient(clientToTry)
closeModal()
setError()
} catch (err) {
Expand Down
13 changes: 0 additions & 13 deletions src/context/ClientContext.js

This file was deleted.