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!

project password required - display as a modal, not a separate page

Blue Mousedec7c7309d89
diff --git a/web/app/pages/Project/ProjectProtectedPassword/index.tsx b/web/app/pages/Project/ProjectProtectedPassword/index.tsx
deleted file mode 100644
index b637dd305..000000000
--- a/web/app/pages/Project/ProjectProtectedPassword/index.tsx
+++ /dev/null
@@ -1,162 +0,0 @@
-import _isEmpty from 'lodash/isEmpty'
-import _keys from 'lodash/keys'
-import _replace from 'lodash/replace'
-import _size from 'lodash/size'
-import React, { useState, useEffect } from 'react'
-import { useTranslation } from 'react-i18next'
-import { Link, useNavigate, useSearchParams } from 'react-router'
-
-import { checkPassword } from '~/api'
-import Footer from '~/components/Footer'
-import Header from '~/components/Header'
-import { useRequiredParams } from '~/hooks/useRequiredParams'
-import Button from '~/ui/Button'
-import Input from '~/ui/Input'
-import routes from '~/utils/routes'
-
-import { setProjectPassword } from '../View/utils/cache'
-
-interface ProjectProtectedPasswordForm {
- password: string
-}
-
-const MAX_PASSWORD_LENGTH = 80
-
-const ProjectProtectedPassword = () => {
- const { t } = useTranslation('common')
- const [form, setForm] = useState<ProjectProtectedPasswordForm>({
- password: '',
- })
- const [validated, setValidated] = useState(false)
- const [errors, setErrors] = useState<{
- password?: string
- }>({})
- const { pid } = useRequiredParams<{ pid: string }>()
- const [beenSubmitted, setBeenSubmitted] = useState(false)
- const [isLoading, setIsLoading] = useState(false)
- const navigate = useNavigate()
- const [searchParams] = useSearchParams()
-
- const isEmbedded = searchParams.get('embedded') === 'true'
-
- const validate = () => {
- const allErrors = {} as {
- password?: string
- }
-
- if (_isEmpty(form.password)) {
- allErrors.password = t('apiNotifications.enterPassword')
- }
-
- if (_size(form.password) >= MAX_PASSWORD_LENGTH) {
- allErrors.password = t('auth.common.passwordTooLong', { amount: MAX_PASSWORD_LENGTH })
- }
-
- const valid = _isEmpty(_keys(allErrors))
-
- setErrors(allErrors)
- setValidated(valid)
- }
-
- useEffect(() => {
- // eslint-disable-next-line react-hooks/set-state-in-effect -- Form validation on input change
- validate()
- }, [form]) // eslint-disable-line
-
- const onSubmit = async (data: ProjectProtectedPasswordForm) => {
- if (isLoading) {
- return
- }
-
- setIsLoading(true)
- await checkPassword(pid, data.password)
- .then((result) => {
- if (result) {
- const searchParamsObj = new URLSearchParams()
-
- if (searchParams.has('theme')) {
- searchParamsObj.set('theme', searchParams.get('theme')!)
- }
-
- if (searchParams.has('embedded')) {
- searchParamsObj.set('embedded', searchParams.get('embedded')!)
- }
-
- const searchString = searchParamsObj.toString()
- const search = searchString ? `?${searchString}` : undefined
-
- setProjectPassword(pid, data.password)
- navigate({
- pathname: _replace(routes.project, ':id', pid),
- search,
- })
- return
- }
- setErrors({
- password: t('apiNotifications.incorrectPassword'),
- })
- })
- .catch(console.error)
- .finally(() => {
- setIsLoading(false)
- })
- }
-
- const handleInput = ({ target }: { target: HTMLInputElement }) => {
- const value = target.type === 'checkbox' ? target.checked : target.value
-
- setForm((oldForm) => ({
- ...oldForm,
- [target.name]: value,
- }))
- }
-
- const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
- e.preventDefault()
- e.stopPropagation()
- setBeenSubmitted(true)
-
- if (validated) {
- onSubmit(form)
- }
- }
-
- return (
- <>
- {!isEmbedded ? <Header /> : null}
- <div className='flex min-h-page flex-col bg-gray-50 dark:bg-slate-900'>
- <form className='mx-auto w-full max-w-7xl px-4 py-6 sm:px-6 lg:px-8' onSubmit={handleSubmit}>
- <h2 className='mt-2 text-3xl font-bold text-gray-900 dark:text-gray-50'>{t('titles.passwordProtected')}</h2>
- <Input
- name='password'
- type='password'
- label={t('auth.common.password')}
- value={form.password}
- placeholder={t('auth.common.password')}
- className='mt-4'
- onChange={handleInput}
- error={beenSubmitted ? errors.password : null}
- />
- <div className='mt-5 flex gap-2'>
- <Button
- className='border-indigo-100 dark:border-slate-700/50 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'
- as={Link}
- // @ts-expect-error
- to={routes.main}
- secondary
- regular
- >
- {t('common.cancel')}
- </Button>
- <Button type='submit' loading={isLoading} primary regular>
- {t('common.continue')}
- </Button>
- </div>
- </form>
- </div>
- {!isEmbedded ? <Footer /> : null}
- </>
- )
-}
-
-export default ProjectProtectedPassword
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index 998be0daf..a39401717 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -82,6 +82,7 @@ import AddAViewModal from './components/AddAViewModal'
import { ChartManagerProvider } from './components/ChartManager'
const CaptchaView = lazy(() => import('./components/CaptchaView'))
import LockedDashboard from './components/LockedDashboard'
+import PasswordRequiredModal from './components/PasswordRequiredModal'
import ProjectSidebar, { MobileSidebarTrigger } from './components/ProjectSidebar'
import SearchFilters from './components/SearchFilters'
import { Filter, ProjectView, ProjectViewCustomEvent } from './interfaces/traffic'
@@ -222,7 +223,16 @@ export const useViewProjectContext = () => {
}
const ViewProjectContent = () => {
- const { id, project, preferences, updatePreferences, allowedToManage, liveVisitors } = useCurrentProject()
+ const {
+ id,
+ project,
+ preferences,
+ updatePreferences,
+ allowedToManage,
+ liveVisitors,
+ isPasswordRequired,
+ submitPassword,
+ } = useCurrentProject()
const projectPassword = useProjectPassword(id)
const { theme, setTheme } = useTheme()
@@ -1020,6 +1030,70 @@ const ViewProjectContent = () => {
],
)
+ // Show password modal over a skeleton dashboard when password is required
+ if (isPasswordRequired) {
+ return (
+ <>
+ {!isEmbedded ? <Header /> : null}
+ <div
+ className={cx('flex min-h-screen flex-col bg-gray-50 dark:bg-slate-900', {
+ 'min-h-including-header': !isEmbedded,
+ 'min-h-screen': isEmbedded,
+ })}
+ >
+ <div className='relative flex flex-1'>
+ {/* Real Sidebar */}
+ <ProjectSidebar
+ tabs={tabs}
+ activeTab={activeTab}
+ onTabChange={() => {}}
+ projectId={id}
+ projectName=''
+ dataLoading={false}
+ searchParams={searchParams}
+ allowedToManage={false}
+ className='hidden md:flex'
+ />
+
+ {/* Skeleton Main Content */}
+ <div className='flex flex-1 flex-col px-4 py-2 sm:px-6 lg:px-8'>
+ {/* Skeleton header */}
+ <div className='mb-6 flex items-center justify-between'>
+ <div className='h-8 w-48 animate-pulse rounded bg-gray-200 dark:bg-slate-700' />
+ <div className='flex gap-2'>
+ <div className='h-10 w-24 animate-pulse rounded bg-gray-200 dark:bg-slate-700' />
+ <div className='h-10 w-32 animate-pulse rounded bg-gray-200 dark:bg-slate-700' />
+ </div>
+ </div>
+
+ {/* Skeleton metric cards */}
+ <div className='mb-6 grid grid-cols-2 gap-4 md:grid-cols-4'>
+ {[...Array(4)].map((_, i) => (
+ <div key={i} className='h-24 animate-pulse rounded-lg bg-gray-200 dark:bg-slate-700' />
+ ))}
+ </div>
+
+ {/* Skeleton chart */}
+ <div className='mb-6 h-80 animate-pulse rounded-lg bg-gray-200 dark:bg-slate-700' />
+
+ {/* Skeleton panels */}
+ <div className='grid grid-cols-1 gap-4 md:grid-cols-2'>
+ {[...Array(4)].map((_, i) => (
+ <div key={i} className='h-48 animate-pulse rounded-lg bg-gray-200 dark:bg-slate-700' />
+ ))}
+ </div>
+ </div>
+ </div>
+
+ {!isEmbedded ? <Footer /> : null}
+ </div>
+
+ {/* Password Modal */}
+ <PasswordRequiredModal isOpen={isPasswordRequired} onSubmit={submitPassword} />
+ </>
+ )
+ }
+
if (authLoading || !project) {
return (
<>
diff --git a/web/app/pages/Project/View/components/PasswordRequiredModal.tsx b/web/app/pages/Project/View/components/PasswordRequiredModal.tsx
new file mode 100644
index 000000000..5103ec83c
--- /dev/null
+++ b/web/app/pages/Project/View/components/PasswordRequiredModal.tsx
@@ -0,0 +1,120 @@
+import { LockClosedIcon } from '@heroicons/react/24/outline'
+import _isEmpty from 'lodash/isEmpty'
+import _size from 'lodash/size'
+import { useState, useEffect, useCallback, FormEvent } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Link } from 'react-router'
+
+import Button from '~/ui/Button'
+import Input from '~/ui/Input'
+import Modal from '~/ui/Modal'
+import routes from '~/utils/routes'
+
+const MAX_PASSWORD_LENGTH = 80
+
+interface PasswordRequiredModalProps {
+ isOpen: boolean
+ onSubmit: (password: string) => Promise<{ success: boolean; error?: string }>
+}
+
+const PasswordRequiredModal = ({ isOpen, onSubmit }: PasswordRequiredModalProps) => {
+ const { t } = useTranslation('common')
+ const [password, setPassword] = useState('')
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+
+ // Clear error when password changes
+ useEffect(() => {
+ if (error) {
+ setError(null)
+ }
+ }, [password]) // eslint-disable-line react-hooks/exhaustive-deps
+
+ const validatePassword = useCallback(() => {
+ if (_isEmpty(password)) {
+ return t('apiNotifications.enterPassword')
+ }
+
+ if (_size(password) >= MAX_PASSWORD_LENGTH) {
+ return t('auth.common.passwordTooLong', { amount: MAX_PASSWORD_LENGTH })
+ }
+
+ return null
+ }, [password, t])
+
+ const handleSubmit = async (e: FormEvent) => {
+ e.preventDefault()
+ e.stopPropagation()
+
+ const validationError = validatePassword()
+ if (validationError) {
+ setError(validationError)
+ return
+ }
+
+ if (isLoading) {
+ return
+ }
+
+ setIsLoading(true)
+
+ try {
+ const result = await onSubmit(password)
+
+ if (!result.success && result.error) {
+ setError(result.error)
+ }
+ } finally {
+ setIsLoading(false)
+ }
+ }
+
+ return (
+ <Modal
+ isOpened={isOpen}
+ onClose={() => {}}
+ size='regular'
+ message={
+ <form onSubmit={handleSubmit} className='space-y-4'>
+ <div className='flex flex-col items-center text-center'>
+ <div className='mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-amber-100 dark:bg-amber-900/30'>
+ <LockClosedIcon className='h-6 w-6 text-amber-600 dark:text-amber-400' />
+ </div>
+ <h3 className='mt-4 text-lg font-semibold text-gray-900 dark:text-gray-50'>
+ {t('titles.passwordProtected')}
+ </h3>
+ <p className='mt-2 text-sm text-gray-600 dark:text-gray-400'>{t('project.passwordProtectedHint')}</p>
+ </div>
+
+ <Input
+ name='password'
+ type='password'
+ label={t('auth.common.password')}
+ value={password}
+ placeholder={t('auth.common.password')}
+ onChange={(e) => setPassword(e.target.value)}
+ error={error}
+ />
+
+ <div className='flex flex-col-reverse gap-2 sm:flex-row sm:justify-end'>
+ <Button
+ className='border-indigo-100 dark:border-slate-700/50 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'
+ as={Link}
+ // @ts-expect-error
+ to={routes.main}
+ secondary
+ regular
+ >
+ {t('common.cancel')}
+ </Button>
+ <Button type='submit' loading={isLoading} primary regular>
+ {t('common.continue')}
+ </Button>
+ </div>
+ </form>
+ }
+ />
+ )
+}
+
+export default PasswordRequiredModal
diff --git a/web/app/providers/CurrentProjectProvider.tsx b/web/app/providers/CurrentProjectProvider.tsx
index c1b6179c2..c07c0f451 100644
--- a/web/app/providers/CurrentProjectProvider.tsx
+++ b/web/app/providers/CurrentProjectProvider.tsx
@@ -16,7 +16,7 @@ import { Extension, type Project } from '~/lib/models/Project'
import { getItemJSON, removeItem } from '~/utils/localstorage'
import routes from '~/utils/routes'
-import { getProjectPreferences, setProjectPreferences } from '../pages/Project/View/utils/cache'
+import { getProjectPreferences, setProjectPassword, setProjectPreferences } from '../pages/Project/View/utils/cache'
import { CHART_METRICS_MAPPING } from '../pages/Project/View/ViewProject.helpers'
import { useAuth } from './AuthProvider'
@@ -31,6 +31,8 @@ interface CurrentProjectContextType {
mergeProject: (project: Partial<Project>) => void
liveVisitors: number
updateLiveVisitors: () => Promise<void>
+ isPasswordRequired: boolean
+ submitPassword: (password: string) => Promise<{ success: boolean; error?: string }>
}
const CurrentProjectContext = createContext<CurrentProjectContextType | undefined>(undefined)
@@ -57,6 +59,8 @@ const useProject = (id: string) => {
const { isLoading: authLoading } = useAuth()
const projectPassword = useProjectPassword(id)
const [project, setProject] = useState<Project | null>(null)
+ const [isPasswordRequired, setIsPasswordRequired] = useState(false)
+ const [passwordForRetry, setPasswordForRetry] = useState<string | null>(null)
const [searchParams] = useSearchParams()
@@ -87,10 +91,7 @@ const useProject = (id: string) => {
}
toast.error(t('apiNotifications.incorrectPassword'))
- navigate({
- pathname: _replace(routes.project_protected_password, ':pid', id),
- search: params,
- })
+ setIsPasswordRequired(true)
removeItem(LS_PROJECTS_PROTECTED_KEY)
})
return
@@ -100,22 +101,47 @@ const useProject = (id: string) => {
navigate(routes.dashboard)
}, [id, projectPassword, navigate, t, params])
+ // Function to submit password and retry loading project
+ const submitPassword = useCallback(
+ async (password: string): Promise<{ success: boolean; error?: string }> => {
+ try {
+ const isValid = await checkPassword(id, password)
+
+ if (!isValid) {
+ return { success: false, error: t('apiNotifications.incorrectPassword') }
+ }
+
+ // Password is correct, store it for future use and trigger project reload
+ setProjectPassword(id, password)
+ setPasswordForRetry(password)
+ setIsPasswordRequired(false)
+ return { success: true }
+ } catch (error) {
+ console.error('[ERROR] (submitPassword)', error)
+ return { success: false, error: t('apiNotifications.somethingWentWrong') }
+ }
+ },
+ [id, t],
+ )
+
useEffect(() => {
if (authLoading || project) {
return
}
- getProject(id, projectPassword)
+ // Use passwordForRetry if available, otherwise use stored password
+ const effectivePassword = passwordForRetry || projectPassword
+
+ getProject(id, effectivePassword)
.then((result) => {
if (!result) {
onErrorLoading()
+ return
}
- if (result.isPasswordProtected && !result.role && !projectPassword) {
- navigate({
- pathname: _replace(routes.project_protected_password, ':pid', id),
- search: params,
- })
+ if (result.isPasswordProtected && !result.role && !effectivePassword) {
+ // Show password modal instead of redirecting
+ setIsPasswordRequired(true)
return
}
@@ -125,7 +151,7 @@ const useProject = (id: string) => {
console.error('[ERROR] (getProject)', reason)
onErrorLoading()
})
- }, [authLoading, project, id, projectPassword, navigate, onErrorLoading, params])
+ }, [authLoading, project, id, projectPassword, passwordForRetry, navigate, onErrorLoading, params])
const mergeProject = useCallback((project: Partial<Project>) => {
setProject((prev) => {
@@ -137,7 +163,7 @@ const useProject = (id: string) => {
})
}, [])
- return { project, mergeProject }
+ return { project, mergeProject, isPasswordRequired, submitPassword }
}
export type ProjectPreferences = {
@@ -198,7 +224,7 @@ const useLiveVisitors = (project: Project | null) => {
}
export const CurrentProjectProvider = ({ children, id }: CurrentProjectProviderProps) => {
- const { project, mergeProject } = useProject(id)
+ const { project, mergeProject, isPasswordRequired, submitPassword } = useProject(id)
const { isAuthenticated } = useAuth()
const { preferences, updatePreferences } = useProjectPreferences(id)
const [extensions, setExtensions] = useState<Extension[]>([])
@@ -234,6 +260,8 @@ export const CurrentProjectProvider = ({ children, id }: CurrentProjectProviderP
allowedToManage: project?.role === 'owner' || project?.role === 'admin',
liveVisitors,
updateLiveVisitors,
+ isPasswordRequired,
+ submitPassword,
}}
>
{children}
diff --git a/web/app/utils/routes.ts b/web/app/utils/routes.ts
index b695c78d7..4ed102d78 100644
--- a/web/app/utils/routes.ts
+++ b/web/app/utils/routes.ts
@@ -26,7 +26,6 @@ const routes = Object.freeze({
transfer_reject: '/project/transfer/cancel',
socialised: '/socialised',
gsc_connected: '/gsc-connected',
- project_protected_password: '/projects/:pid/password',
open: '/open',
ref: '/ref/:id',
blog: '/blog',
diff --git a/web/app/utils/server.ts b/web/app/utils/server.ts
index 69f7651e9..7311e2c75 100644
--- a/web/app/utils/server.ts
+++ b/web/app/utils/server.ts
@@ -222,7 +222,7 @@ export const getPageMeta = (t: typeof i18next.t, url?: string, _pathname?: strin
// organisation, project_settings, project titles are set dynamically
- // todo: create_alert, alert_settings, project_protected_password
+ // todo: create_alert, alert_settings
result.prefixLessTitle = result.title
result.title += ` ${TITLE_SUFFIX}`