Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

fix: sync project password unlock state

Blue Mouse2c2233a01747
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index 0667202a2..64063a15a 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -275,6 +275,7 @@ const ViewProjectContent = () => {
allowedToManage,
liveVisitors,
isPasswordRequired,
+ isCheckingStoredPassword,
submitPassword,
} = useCurrentProject()
const projectPassword = useProjectPassword(id)
@@ -1344,7 +1345,7 @@ const ViewProjectContent = () => {
<ClientOnly>
{() => (
<PasswordRequiredModal
- isOpen={isPasswordRequired}
+ isOpen={isPasswordRequired && !isCheckingStoredPassword}
onSubmit={submitPassword}
/>
)}
diff --git a/web/app/pages/Project/View/utils/cache.ts b/web/app/pages/Project/View/utils/cache.ts
index 8bd44b7e0..ce728616a 100644
--- a/web/app/pages/Project/View/utils/cache.ts
+++ b/web/app/pages/Project/View/utils/cache.ts
@@ -1,7 +1,9 @@
-import { LS_PROJECTS_PROTECTED_KEY } from '~/lib/constants'
+import { LS_PROJECTS_PROTECTED_KEY, isBrowser } from '~/lib/constants'
import { type Project } from '~/lib/models/Project'
import { getItemJSON, setItem } from '~/utils/localstorage'
+export const PROJECT_PASSWORD_UPDATED_EVENT = 'swx-project-password-updated'
+
const getAllProjectPasswords = () =>
getItemJSON(LS_PROJECTS_PROTECTED_KEY) || {}
@@ -13,4 +15,12 @@ export const setProjectPassword = (id: Project['id'], password: string) => {
[id]: password,
}),
)
+
+ if (isBrowser) {
+ window.dispatchEvent(
+ new CustomEvent(PROJECT_PASSWORD_UPDATED_EVENT, {
+ detail: { id, password },
+ }),
+ )
+ }
}
diff --git a/web/app/providers/CurrentProjectProvider.tsx b/web/app/providers/CurrentProjectProvider.tsx
index b9ace247e..26f5ae0d6 100644
--- a/web/app/providers/CurrentProjectProvider.tsx
+++ b/web/app/providers/CurrentProjectProvider.tsx
@@ -3,7 +3,6 @@ import {
useCallback,
useContext,
useEffect,
- useMemo,
useRef,
useState,
} from 'react'
@@ -13,6 +12,7 @@ import {
useSearchParams,
useFetcher,
useLoaderData,
+ useRevalidator,
} from 'react-router'
import { toast } from 'sonner'
@@ -22,6 +22,7 @@ import {
LS_PROJECTS_PROTECTED_KEY,
Period,
TimeBucket,
+ isBrowser,
} from '~/lib/constants'
import { type Project } from '~/lib/models/Project'
import type {
@@ -31,7 +32,10 @@ import type {
import { getItemJSON } from '~/utils/localstorage'
import routes from '~/utils/routes'
-import { setProjectPassword } from '../pages/Project/View/utils/cache'
+import {
+ PROJECT_PASSWORD_UPDATED_EVENT,
+ setProjectPassword,
+} from '../pages/Project/View/utils/cache'
import { CHART_METRICS_MAPPING } from '../pages/Project/View/ViewProject.helpers'
interface CurrentProjectContextType {
@@ -44,6 +48,7 @@ interface CurrentProjectContextType {
liveVisitors: number
updateLiveVisitors: () => Promise<void>
isPasswordRequired: boolean
+ isCheckingStoredPassword: boolean
submitPassword: (
password: string,
) => Promise<{ success: boolean; error?: string }>
@@ -60,21 +65,57 @@ interface CurrentProjectProviderProps {
export const useProjectPassword = (id?: string) => {
const [searchParams] = useSearchParams()
-
- const projectPassword = useMemo(
- () =>
- searchParams.get('password') ||
- getItemJSON(LS_PROJECTS_PROTECTED_KEY)?.[id || ''] ||
- '',
- [id, searchParams],
+ const [cachedPassword, setCachedPassword] = useState(
+ () => getItemJSON(LS_PROJECTS_PROTECTED_KEY)?.[id || ''] || '',
)
- return projectPassword
+ useEffect(() => {
+ setCachedPassword(getItemJSON(LS_PROJECTS_PROTECTED_KEY)?.[id || ''] || '')
+ }, [id])
+
+ useEffect(() => {
+ if (!isBrowser) {
+ return
+ }
+
+ const handlePasswordUpdated = (
+ event: CustomEvent<{ id: string; password: string }>,
+ ) => {
+ if (event.detail.id === id) {
+ setCachedPassword(event.detail.password || '')
+ }
+ }
+
+ const handleStorage = (event: StorageEvent) => {
+ if (event.key === LS_PROJECTS_PROTECTED_KEY) {
+ setCachedPassword(
+ getItemJSON(LS_PROJECTS_PROTECTED_KEY)?.[id || ''] || '',
+ )
+ }
+ }
+
+ window.addEventListener(
+ PROJECT_PASSWORD_UPDATED_EVENT,
+ handlePasswordUpdated as EventListener,
+ )
+ window.addEventListener('storage', handleStorage)
+
+ return () => {
+ window.removeEventListener(
+ PROJECT_PASSWORD_UPDATED_EVENT,
+ handlePasswordUpdated as EventListener,
+ )
+ window.removeEventListener('storage', handleStorage)
+ }
+ }, [id])
+
+ return searchParams.get('password') || cachedPassword
}
const useProject = (id: string) => {
const { t } = useTranslation('common')
const navigate = useNavigate()
+ const revalidator = useRevalidator()
const loaderData = useLoaderData<ProjectLoaderData>()
const storedPassword = useProjectPassword(id)
@@ -85,6 +126,9 @@ const useProject = (id: string) => {
const [isPasswordRequired, setIsPasswordRequired] = useState(
() => loaderData?.isPasswordRequired || false,
)
+ const [isCheckingStoredPassword, setIsCheckingStoredPassword] = useState(
+ () => Boolean(loaderData?.isPasswordRequired && storedPassword),
+ )
const passwordFetcher = useFetcher<ProjectViewActionData>()
const lastHandledFetcherData = useRef<ProjectViewActionData | null>(null)
@@ -111,17 +155,25 @@ const useProject = (id: string) => {
useEffect(() => {
if (
loaderData?.isPasswordRequired &&
+ isPasswordRequired &&
storedPassword &&
!hasTriedStoredPassword.current &&
passwordFetcher.state === 'idle'
) {
hasTriedStoredPassword.current = true
+ setIsCheckingStoredPassword(true)
passwordFetcher.submit(
{ intent: 'get-project', password: storedPassword },
{ method: 'POST', action: `/projects/${id}` },
)
}
- }, [loaderData?.isPasswordRequired, storedPassword, id, passwordFetcher])
+ }, [
+ loaderData?.isPasswordRequired,
+ isPasswordRequired,
+ storedPassword,
+ id,
+ passwordFetcher,
+ ])
// Handle password fetcher response
useEffect(() => {
@@ -135,12 +187,15 @@ const useProject = (id: string) => {
const result = passwordFetcher.data.data as Project
setProject(result)
setIsPasswordRequired(false)
+ setIsCheckingStoredPassword(false)
if (lastSubmittedPasswordRef.current) {
setProjectPassword(id, lastSubmittedPasswordRef.current)
lastSubmittedPasswordRef.current = null
}
+ revalidator.revalidate()
+
if (passwordResolverRef.current) {
passwordResolverRef.current({ success: true })
passwordResolverRef.current = null
@@ -148,6 +203,8 @@ const useProject = (id: string) => {
} else if (passwordFetcher.data.error) {
toast.error(t('apiNotifications.incorrectPassword'))
+ setIsPasswordRequired(true)
+ setIsCheckingStoredPassword(false)
lastSubmittedPasswordRef.current = null
if (passwordResolverRef.current) {
passwordResolverRef.current({
@@ -157,7 +214,7 @@ const useProject = (id: string) => {
passwordResolverRef.current = null
}
}
- }, [passwordFetcher.state, passwordFetcher.data, t, id])
+ }, [passwordFetcher.state, passwordFetcher.data, t, id, revalidator])
const submitPassword = useCallback(
async (password: string): Promise<{ success: boolean; error?: string }> => {
@@ -183,7 +240,13 @@ const useProject = (id: string) => {
})
}, [])
- return { project, mergeProject, isPasswordRequired, submitPassword }
+ return {
+ project,
+ mergeProject,
+ isPasswordRequired,
+ isCheckingStoredPassword,
+ submitPassword,
+ }
}
type ProjectPreferences = {
@@ -248,8 +311,13 @@ export const CurrentProjectProvider = ({
children,
id,
}: CurrentProjectProviderProps) => {
- const { project, mergeProject, isPasswordRequired, submitPassword } =
- useProject(id)
+ const {
+ project,
+ mergeProject,
+ isPasswordRequired,
+ isCheckingStoredPassword,
+ submitPassword,
+ } = useProject(id)
const { preferences, updatePreferences } = useProjectPreferences()
const { liveVisitors, updateLiveVisitors } = useLiveVisitors(project)
@@ -265,6 +333,7 @@ export const CurrentProjectProvider = ({
liveVisitors,
updateLiveVisitors,
isPasswordRequired,
+ isCheckingStoredPassword,
submitPassword,
}}
>
diff --git a/web/app/routes/projects.$id.tsx b/web/app/routes/projects.$id.tsx
index aff1f4095..c777d194e 100644
--- a/web/app/routes/projects.$id.tsx
+++ b/web/app/routes/projects.$id.tsx
@@ -650,6 +650,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
'submit-ai-chat-feedback',
])
+ const getPassword = () =>
+ formData.get('password')?.toString() ||
+ getProjectPasswordCookie(request, projectId || '') ||
+ ''
+
if (!intent || (!publicIntents.has(intent) && !hasAuthTokens(request))) {
redirectIfNotAuthenticated(request)
}
@@ -946,7 +951,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
// Annotations
case 'get-annotations': {
- const password = formData.get('password')?.toString() || ''
+ const password = getPassword()
const result = await serverFetch(
request,
@@ -1041,7 +1046,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
// Project Views
case 'get-project-views': {
- const password = formData.get('password')?.toString() || ''
+ const password = getPassword()
const result = await serverFetch(request, `project/${projectId}/views`, {
method: 'GET',
@@ -2074,7 +2079,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
// Funnels (getters)
case 'get-funnels': {
- const password = formData.get('password')?.toString() || ''
+ const password = getPassword()
const result = await serverFetch(
request,
@@ -2104,7 +2109,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const toDate = formData.get('to')?.toString() || ''
const tz = formData.get('timezone')?.toString() || ''
const funnelId = formData.get('funnelId')?.toString() || ''
- const password = formData.get('password')?.toString() || ''
+ const password = getPassword()
const params = new URLSearchParams({ pid: projectId || '' })
if (period) params.append('period', period)
@@ -2203,7 +2208,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
// Filters
case 'get-filters': {
const filterType = formData.get('type')?.toString() || ''
- const password = formData.get('password')?.toString() || ''
+ const password = getPassword()
const result = await serverFetch(
request,
@@ -2229,7 +2234,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
case 'get-errors-filters': {
const filterType = formData.get('type')?.toString() || ''
- const password = formData.get('password')?.toString() || ''
+ const password = getPassword()
const result = await serverFetch(
request,
@@ -2256,7 +2261,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
case 'get-version-filters': {
const dataType = formData.get('dataType')?.toString() || 'traffic'
const column = formData.get('column')?.toString() || 'br'
- const password = formData.get('password')?.toString() || ''
+ const password = getPassword()
const result = await serverFetch(
request,
@@ -2308,7 +2313,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
// Project data
case 'get-project': {
- const password = formData.get('password')?.toString() || ''
+ const password = getPassword()
const result = await serverFetch(request, `project/${projectId}`, {
method: 'GET',
@@ -2322,14 +2327,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
)
}
+ const cookies = [...result.cookies]
+ if (password) {
+ cookies.push(createProjectPasswordCookie(projectId || '', password))
+ }
+
return data<ProjectViewActionData>(
{ intent, success: true, data: result.data },
- { headers: createHeadersWithCookies(result.cookies) },
+ { headers: createHeadersWithCookies(cookies) },
)
}
case 'check-password': {
- const password = formData.get('password')?.toString() || ''
+ const password = getPassword()
const result = await serverFetch<boolean>(
request,
@@ -2347,9 +2357,14 @@ export async function action({ request, params }: ActionFunctionArgs) {
)
}
+ const cookies = [...result.cookies]
+ if (password && result.data) {
+ cookies.push(createProjectPasswordCookie(projectId || '', password))
+ }
+
return data<ProjectViewActionData>(
{ intent, success: true, data: result.data },
- { headers: createHeadersWithCookies(result.cookies) },
+ { headers: createHeadersWithCookies(cookies) },
)
}