diff --git a/client/src/services/userPreferences.test.ts b/client/src/services/userPreferences.test.ts index 9a8b94e..a7d3949 100644 --- a/client/src/services/userPreferences.test.ts +++ b/client/src/services/userPreferences.test.ts @@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it } from 'vitest' import { getColorSchemePreference, getOwmApiKey, + getOwmApiKeyForActiveUser, getThemePreference, setColorSchemePreference, setOwmApiKey, @@ -33,6 +34,24 @@ describe('userPreferences', () => { expect(getOwmApiKey(USER_ID)).toBe('') }) + it('reads namespaced OWM key via active user id', () => { + setOwmApiKey(USER_ID, 'namespaced-only') + localStorage.setItem('active_userid', USER_ID) + localStorage.removeItem('owm_api_key') + + expect(getOwmApiKeyForActiveUser()).toBe('namespaced-only') + expect(getOwmApiKey()).toBe('namespaced-only') + }) + + it('does not read namespaced OWM key without active user id', () => { + setOwmApiKey(USER_ID, 'namespaced-only') + localStorage.removeItem('active_userid') + localStorage.removeItem('owm_api_key') + + expect(getOwmApiKeyForActiveUser()).toBe('') + expect(getOwmApiKey()).toBe('') + }) + it('writes theme preferences to namespaced keys', () => { setThemePreference(USER_ID, 'ocean') setColorSchemePreference(USER_ID, 'light') diff --git a/client/src/services/userPreferences.ts b/client/src/services/userPreferences.ts index b349f10..fb6d7f3 100644 --- a/client/src/services/userPreferences.ts +++ b/client/src/services/userPreferences.ts @@ -35,7 +35,7 @@ function migrateLegacyPrefs(userId: string): void { } function resolveUserId(userId?: string | null): string | null { - const id = userId ?? getActiveUserId() + const id = (userId?.trim() || getActiveUserId()?.trim()) || null if (!id) return null migrateLegacyPrefs(id) return id @@ -75,6 +75,11 @@ export function getOwmApiKey(userId?: string | null): string { return localStorage.getItem(LEGACY_OWM_KEY) ?? '' } +/** OWM key for the signed-in user (`active_userid`). Prefer this over a bare `getOwmApiKey()` call. */ +export function getOwmApiKeyForActiveUser(): string { + return getOwmApiKey(getActiveUserId()) +} + export function setOwmApiKey(userId: string, value: string): void { migrateLegacyPrefs(userId) const trimmed = value.trim() diff --git a/client/src/services/weather.ts b/client/src/services/weather.ts index 2dc4359..5b18016 100644 --- a/client/src/services/weather.ts +++ b/client/src/services/weather.ts @@ -1,5 +1,5 @@ import { apiFetch } from './api.js' -import { getOwmApiKey } from './userPreferences.js' +import { getOwmApiKeyForActiveUser } from './userPreferences.js' export class WeatherApiError extends Error { code: 'NO_KEY' | 'REQUEST_FAILED' @@ -27,7 +27,7 @@ export async function fetchOpenWeatherCurrent(params: { throw new WeatherApiError('lat/lon or location query required') } - const userKey = getOwmApiKey().trim() + const userKey = getOwmApiKeyForActiveUser().trim() const headers: Record = {} if (userKey) headers['X-OWM-Api-Key'] = userKey