Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Remove usage session cookie (#798)

sarayourfrienda1eb4a7398db
diff --git a/package.json b/package.json
index 12c3efb46..3d7b9a2eb 100644
--- a/package.json
+++ b/package.json
@@ -92,6 +92,7 @@
"@testing-library/user-event": "^13.2.1",
"@testing-library/vue": "^5.8.2",
"@types/jest": "^26.0.22",
+ "@types/uuid": "^8.3.4",
"@vue/test-utils": "^1.1.3",
"autoprefixer": "^10.4.0",
"babel-jest": "^26.6.3",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 273f6d905..2fbbb378e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -23,6 +23,7 @@ specifiers:
'@testing-library/user-event': ^13.2.1
'@testing-library/vue': ^5.8.2
'@types/jest': ^26.0.22
+ '@types/uuid': ^8.3.4
'@vue/test-utils': ^1.1.3
autoprefixer: ^10.4.0
axios: ^0.21.2
@@ -135,6 +136,7 @@ devDependencies:
'@testing-library/user-event': 13.5.0
'@testing-library/vue': 5.8.2
'@types/jest': 26.0.24
+ '@types/uuid': 8.3.4
'@vue/test-utils': 1.3.0
autoprefixer: [email protected]
babel-jest: 26.6.3
@@ -5825,6 +5827,10 @@ packages:
resolution: {integrity: sha512-PBjIUxZHOuj0R15/xuwJYjFi+KZdNFrehocChv4g5hu6aFroHue8m0lBP0POdK2nKzbw0cgV1mws8+V/JAcEkQ==}
dev: true
+ /@types/uuid/8.3.4:
+ resolution: {integrity: sha512-c/I8ZRb51j+pYGAu5CrFMRxqZ2ke4y2grEBO5AUjgSkSk+qT2Ea+OdWElz/OiMf5MNpn2b17kuVBwZLQJXzihw==}
+ dev: true
+
/@types/webpack-bundle-analyzer/3.9.3:
resolution: {integrity: sha512-l/vaDMWGcXiMB3CbczpyICivLTB07/JNtn1xebsRXE9tPaUDEHgX3x7YP6jfznG5TOu7I4w0Qx1tZz61znmPmg==}
dependencies:
diff --git a/src/data/api-service.js b/src/data/api-service.js
index 0536cf857..86989d57e 100644
--- a/src/data/api-service.js
+++ b/src/data/api-service.js
@@ -3,6 +3,11 @@ import { warn } from '~/utils/warn'
const DEFAULT_REQUEST_TIMEOUT = 30000
+/**
+ * @param {boolean} errorCondition
+ * @param {string} message
+ * @param {import('axios').AxiosRequestConfig} config
+ */
const validateRequest = (errorCondition, message, config) => {
if (errorCondition) {
warn(
@@ -12,6 +17,10 @@ Please check the url: ${config.baseURL}${config.url}`
}
}
+/**
+ *
+ * @param {string} [baseUrl]
+ */
export const createApiService = (baseUrl = process.env.apiUrl) => {
const client = axios.create({
baseURL: baseUrl,
@@ -19,12 +28,12 @@ export const createApiService = (baseUrl = process.env.apiUrl) => {
})
client.interceptors.request.use(function (config) {
validateRequest(
- !config.url.endsWith('/'),
+ !config.url?.endsWith('/'),
'API request urls should have a trailing slash',
config
)
validateRequest(
- config.url.includes('//'),
+ config.url?.includes('//') ?? false,
'API request urls should not have two slashes',
config
)
@@ -47,41 +56,45 @@ export const createApiService = (baseUrl = process.env.apiUrl) => {
return {
/**
+ * @template [T=unknown]
* @param {string} resource The endpoint of the resource
- * @param {import('axios').AxiosRequestConfig} params Url parameter object
- * @returns {Promise<import('axios').AxiosResponse<any>>} response The API response object
+ * @param {import('axios').AxiosRequestConfig['params']} params Url parameter object
+ * @returns {Promise<import('axios').AxiosResponse<T>>} response The API response object
*/
query(resource, params) {
return client.get(resource, { params })
},
/**
+ * @template [T=unknown]
* @param {string} resource The endpoint of the resource
* @param {string} slug The sub-endpoint of the resource
- * @returns {Promise<import('axios').AxiosResponse<any>>} Response The API response object
+ * @returns {Promise<import('axios').AxiosResponse<T>>} Response The API response object
*/
get(resource, slug) {
return client.get(`${resource}/${slug}/`)
},
/**
+ * @template [T=unknown]
* @param {string} resource The endpoint of the resource
- * @param {import('axios').AxiosRequestConfig} params Url parameter object
- * @returns {Promise<import('axios').AxiosResponse<any>>} Response The API response object
+ * @param {Parameters<typeof client['post']>[1]} data Url parameter object
+ * @returns {Promise<import('axios').AxiosResponse<T>>} Response The API response object
*/
- post(resource, params) {
- return client.post(resource, params)
+ post(resource, data) {
+ return client.post(resource, data)
},
/**
+ * @template [T=unknown]
* @param {string} resource The endpoint of the resource
* @param {string} slug The sub-endpoint of the resource
- * @param {import('axios').AxiosRequestConfig} params Url parameter object
+ * @param {Parameters<typeof client['put']>[1]} data Url parameter object
* @param {import('axios').AxiosRequestConfig['headers']} headers Headers object
- * @returns {Promise<import('axios').AxiosResponse<any>>} Response The API response object
+ * @returns {Promise<import('axios').AxiosResponse<T>>} Response The API response object
*/
- update(resource, slug, params, headers) {
- return client.put(`${resource}/${slug}`, params, { headers })
+ update(resource, slug, data, headers) {
+ return client.put(`${resource}/${slug}`, data, { headers })
},
/**
diff --git a/src/data/usage-data-service.js b/src/data/usage-data-service.js
index 43b36aba2..071ad556a 100644
--- a/src/data/usage-data-service.js
+++ b/src/data/usage-data-service.js
@@ -4,17 +4,35 @@ const baseUrl = process.env.apiUrl
// Analytics API is available at `http://api.openverse.engineering/analytics/`
// and not `http://api.openverse.engineering/v1/analytics
-const ApiService = createApiService(baseUrl.replace('/v1', ''))
+const ApiService = createApiService(baseUrl?.replace('/v1', ''))
+
+/** @typedef {'search_event' | 'result_click_event' | 'detail_page_event' | 'search_rating_event'} SearchEventName */
const UsageDataService = {
- post(endpoint, params) {
- return ApiService.post(`analytics/${endpoint}`, params)
+ /**
+ * @param {SearchEventName} endpoint
+ * @param {Parameters<typeof ApiService['post']>[1]} data
+ */
+ post(endpoint, data) {
+ return ApiService.post(`analytics/${endpoint}`, data)
},
+ /**
+ * @param {object} props
+ * @param {string} props.query
+ * @param {string} props.sessionId
+ */
sendSearchQueryEvent({ query, sessionId }) {
return this.post('search_event', { query, session_uuid: sessionId })
},
+ /**
+ * @param {object} props
+ * @param {string} props.query
+ * @param {unknown} props.resultRank
+ * @param {string} props.resultUuid
+ * @param {string} props.sessionId
+ */
sendResultClickedEvent({ query, resultRank, resultUuid, sessionId }) {
return this.post('result_click_event', {
query,
@@ -24,6 +42,11 @@ const UsageDataService = {
})
},
+ /**
+ * @param {object} props
+ * @param {string} props.eventType
+ * @param {string} props.resultUuid
+ */
sendDetailPageEvent({ eventType, resultUuid }) {
return this.post('detail_page_event', {
event_type: eventType,
@@ -31,6 +54,11 @@ const UsageDataService = {
})
},
+ /**
+ * @param {object} props
+ * @param {string} props.query
+ * @param {boolean} props.relevant
+ */
sendSearchRatingEvent({ query, relevant }) {
return this.post('search_rating_event', { query, relevant })
},
diff --git a/src/store/user.js b/src/store/user.js
index cfcc8500a..0aec058a8 100644
--- a/src/store/user.js
+++ b/src/store/user.js
@@ -1,5 +1,18 @@
-import SessionId from '~/utils/session-id'
+import { v4 as uuidv4 } from 'uuid'
+/**
+ * @typedef UserState
+ * @property {string | undefined} usageSessionId
+ */
+
+/**
+ * @returns {UserState}
+ */
export const state = () => ({
- usageSessionId: SessionId('usageSessionId'),
+ /**
+ * Default to `undefined` on the client and let client side
+ * SSR state hydration pull the SSR generated ID into the client.
+ * This way we avoid generating any spurious IDs on the client.
+ */
+ usageSessionId: process.server ? uuidv4() : undefined,
})
diff --git a/src/utils/session-id.js b/src/utils/session-id.js
deleted file mode 100644
index 2aee73a24..000000000
--- a/src/utils/session-id.js
+++ /dev/null
@@ -1,46 +0,0 @@
-import { v4 as uuidv4 } from 'uuid'
-import Cookie from 'js-cookie'
-
-const COOKIE_EXPIRY_DAYS = 7
-const COOKIE_PREFIX = 'openverse_'
-
-const generateSessionId = () => uuidv4()
-
-/**
- * Store a session in in a cookie for usage analytics. By default
- * it expires when a user closes the browser. If hasExpirationDate is set to
- * true, the cookie will last for 7 days, which is determined by
- * `COOKIE_EXPIRY_DAYS`.
- * @param {string} cookieName - The name of the cookie
- * @param {string} sessionId - randomly generated uuid
- * @param {boolean} hasExpirationDate - Whether the cookie should expire when user closes the browser
- */
-const saveSessionIdInCookie = (cookieName, sessionId, hasExpirationDate) => {
- if (hasExpirationDate) {
- Cookie.set(`${COOKIE_PREFIX}${cookieName}`, sessionId, {
- expires: COOKIE_EXPIRY_DAYS,
- secure: true,
- sameSite: 'None',
- })
- } else {
- Cookie.set(cookieName, sessionId)
- }
-}
-
-/**
- * Retrieves saved session Id or creates a new one.
- * @param {string} cookieName - The name of the cookie
- * @param {boolean} [hasExpirationDate=false] Whether the cookie should expire when user closes the browser
- */
-const SessionId = (cookieName, hasExpirationDate = false) => {
- let sessionId = Cookie.get(`${COOKIE_PREFIX}${cookieName}`)
-
- if (!sessionId) {
- sessionId = generateSessionId()
- saveSessionIdInCookie(cookieName, sessionId, hasExpirationDate)
- }
-
- return sessionId
-}
-
-export default SessionId
diff --git a/test/unit/specs/store/user.spec.js b/test/unit/specs/store/user.spec.js
new file mode 100644
index 000000000..0a4aba516
--- /dev/null
+++ b/test/unit/specs/store/user.spec.js
@@ -0,0 +1,28 @@
+import * as user from '~/store/user'
+import { v4 as uuidv4 } from 'uuid'
+
+jest.mock('uuid', () => ({ v4: jest.fn() }))
+
+describe('user store', () => {
+ beforeEach(() => {
+ process.server = false
+ process.client = false
+ })
+
+ afterAll(() => {
+ // avoid polluting other tests that might be affected by these flags
+ delete process.server
+ delete process.client
+ })
+
+ it('should generate a new usageSessionId when on server', () => {
+ uuidv4.mockReturnValue('abcd-1234')
+ process.server = true
+ expect(user.state().usageSessionId).toEqual('abcd-1234')
+ })
+
+ it('should not generate a new usageSessionId when on client', () => {
+ process.client = true
+ expect(user.state().usageSessionId).toBeUndefined()
+ })
+})
diff --git a/tsconfig.json b/tsconfig.json
index 532aead71..1669feb71 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -36,7 +36,11 @@
"src/composables/use-event-listener-outside.js",
"src/composables/use-active-audio.js",
"src/composables/use-get-locale-formatted-number.js",
+ "src/data/api-service.js",
+ "src/data/usage-data-service.js",
+ "src/store/user.js",
"src/utils/key-codes.js",
- "src/utils/local.js"
+ "src/utils/local.js",
+ "src/utils/warn.js"
]
}