Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(auth): add redirect support for authentication flows (#1358)

Corentin Thomasset47010b6487bb
diff --git a/apps/papra-client/src/modules/auth/auth.constants.ts b/apps/papra-client/src/modules/auth/auth.constants.ts
index c040d4d6..aeac27be 100644
--- a/apps/papra-client/src/modules/auth/auth.constants.ts
+++ b/apps/papra-client/src/modules/auth/auth.constants.ts
@@ -13,4 +13,9 @@ export const ssoProviders = [
export const authPagesPaths = {
emailVerification: '/email-verification',
+ login: '/login',
+ register: '/register',
+ resetPassword: '/reset-password',
+ requestPasswordReset: '/request-password-reset',
+ emailValidationRequired: '/email-validation-required',
};
diff --git a/apps/papra-client/src/modules/auth/auth.services.ts b/apps/papra-client/src/modules/auth/auth.services.ts
index ecf360f9..6743aeb8 100644
--- a/apps/papra-client/src/modules/auth/auth.services.ts
+++ b/apps/papra-client/src/modules/auth/auth.services.ts
@@ -7,6 +7,7 @@ import { buildTimeConfig, isDemoMode } from '../config/config';
import { queryClient } from '../shared/query/query-client';
import { trackingServices } from '../tracking/tracking.services';
import { createDemoAuthClient } from './auth.demo.services';
+import { buildUrl } from '@corentinth/chisels';
export function createAuthClient() {
const client = createBetterAuthClient({
@@ -49,18 +50,25 @@ export const {
export async function authWithProvider({
provider,
config,
+ redirectPath,
}: {
provider: SsoProviderConfig;
config: Config;
+ redirectPath?: string;
}) {
const isCustomProvider = config.auth.providers.customs.some(
({ providerId }) => providerId === provider.key,
);
+ const oauthCallbackUrl = buildUrl({
+ baseUrl: config.baseUrl,
+ path: redirectPath,
+ });
+
if (isCustomProvider) {
const { error } = await signIn.oauth2({
providerId: provider.key,
- callbackURL: config.baseUrl,
+ callbackURL: oauthCallbackUrl,
});
if (error) {
@@ -72,7 +80,7 @@ export async function authWithProvider({
const { error } = await signIn.social({
provider: provider.key as 'github' | 'google',
- callbackURL: config.baseUrl,
+ callbackURL: oauthCallbackUrl,
});
if (error) {
diff --git a/apps/papra-client/src/modules/auth/composables/use-auth-redirect.composable.ts b/apps/papra-client/src/modules/auth/composables/use-auth-redirect.composable.ts
new file mode 100644
index 00000000..114360da
--- /dev/null
+++ b/apps/papra-client/src/modules/auth/composables/use-auth-redirect.composable.ts
@@ -0,0 +1,23 @@
+import { buildPathWithRedirect, parseRedirectPath } from '@/modules/navigation/redirect';
+import { asSingleParam } from '@/modules/shared/utils/query-params';
+import { useSearchParams } from '@solidjs/router';
+import { authPagesPaths } from '../auth.constants';
+
+export function useAuthRedirect() {
+ const [searchParams] = useSearchParams();
+
+ const getRedirectPath = () => parseRedirectPath(asSingleParam(searchParams.redirect));
+ const getPostAuthRedirect = () => getRedirectPath() ?? '/';
+
+ const getPathWithRedirect = (path: string) =>
+ buildPathWithRedirect({ path, redirectPath: getRedirectPath() });
+
+ return {
+ getRedirectPath,
+ getPostAuthRedirect,
+
+ getPathWithRedirect,
+ getLoginPathWithRedirect: () => getPathWithRedirect(authPagesPaths.login),
+ getRegisterPathWithRedirect: () => getPathWithRedirect(authPagesPaths.register),
+ };
+}
diff --git a/apps/papra-client/src/modules/auth/middleware/protected-page.middleware.tsx b/apps/papra-client/src/modules/auth/middleware/protected-page.middleware.tsx
index 383ecf99..2c1b7814 100644
--- a/apps/papra-client/src/modules/auth/middleware/protected-page.middleware.tsx
+++ b/apps/papra-client/src/modules/auth/middleware/protected-page.middleware.tsx
@@ -1,15 +1,17 @@
import type { ParentComponent } from 'solid-js';
import { Navigate } from '@solidjs/router';
import { Match, Switch } from 'solid-js';
+import { useAuthRedirect } from '../composables/use-auth-redirect.composable';
import { useSession } from '../composables/use-session.composable';
export const PublicOnlyPage: ParentComponent = (props) => {
const { getIsAuthenticated, sessionQuery } = useSession();
+ const { getPostAuthRedirect } = useAuthRedirect();
return (
<Switch>
<Match when={!sessionQuery.isLoading && getIsAuthenticated()}>
- <Navigate href="/" />
+ <Navigate href={getPostAuthRedirect()} />
</Match>
<Match when={!sessionQuery.isLoading && !getIsAuthenticated()}>{props.children}</Match>
</Switch>
diff --git a/apps/papra-client/src/modules/auth/pages/email-verification.page.tsx b/apps/papra-client/src/modules/auth/pages/email-verification.page.tsx
index b505f21f..4814dde6 100644
--- a/apps/papra-client/src/modules/auth/pages/email-verification.page.tsx
+++ b/apps/papra-client/src/modules/auth/pages/email-verification.page.tsx
@@ -3,10 +3,12 @@ import { A, useSearchParams } from '@solidjs/router';
import { useI18n } from '@/modules/i18n/i18n.provider';
import { Button } from '@/modules/ui/components/button';
import { AuthLayout } from '../../ui/layouts/auth-layout.component';
+import { useAuthRedirect } from '../composables/use-auth-redirect.composable';
export const EmailVerificationPage: Component = () => {
const { t } = useI18n();
const [searchParams] = useSearchParams();
+ const { getLoginPathWithRedirect } = useAuthRedirect();
const getHasError = () => Boolean(searchParams.error);
@@ -23,7 +25,7 @@ export const EmailVerificationPage: Component = () => {
{t('auth.email-verification.error.description')}
</p>
- <Button as={A} href="/login" class="gap-2" variant="secondary">
+ <Button as={A} href={getLoginPathWithRedirect()} class="gap-2" variant="secondary">
<div class="i-tabler-arrow-left size-4" />
{t('auth.email-verification.error.back')}
</Button>
@@ -37,7 +39,7 @@ export const EmailVerificationPage: Component = () => {
{t('auth.email-verification.success.description')}
</p>
- <Button as={A} href="/login" class="gap-2">
+ <Button as={A} href={getLoginPathWithRedirect()} class="gap-2">
{t('auth.email-verification.success.login')}
<div class="i-tabler-arrow-right size-4" />
</Button>
diff --git a/apps/papra-client/src/modules/auth/pages/login.page.tsx b/apps/papra-client/src/modules/auth/pages/login.page.tsx
index b9ed7958..045cc494 100644
--- a/apps/papra-client/src/modules/auth/pages/login.page.tsx
+++ b/apps/papra-client/src/modules/auth/pages/login.page.tsx
@@ -22,10 +22,12 @@ import { AuthLegalLinks } from '../components/legal-links.component';
import { NoAuthProviderWarning } from '../components/no-auth-provider';
import { SsoProviderButton } from '../components/sso-provider-button.component';
import { TotpField } from '../components/verify-otp.component';
+import { useAuthRedirect } from '../composables/use-auth-redirect.composable';
const TotpVerificationForm: Component = () => {
const navigate = useNavigate();
const { t } = useI18n();
+ const { getPostAuthRedirect } = useAuthRedirect();
const [trustDevice, setTrustDevice] = createSignal(false);
const [totpCode, setTotpCode] = createSignal('');
@@ -39,7 +41,7 @@ const TotpVerificationForm: Component = () => {
}
},
onSuccess: () => {
- navigate('/');
+ navigate(getPostAuthRedirect());
},
}));
@@ -79,6 +81,7 @@ const TotpVerificationForm: Component = () => {
const BackupCodeVerificationForm: Component = () => {
const navigate = useNavigate();
const { t } = useI18n();
+ const { getPostAuthRedirect } = useAuthRedirect();
const [trustDevice, setTrustDevice] = createSignal(false);
const { form, Form, Field } = createForm({
@@ -93,7 +96,7 @@ const BackupCodeVerificationForm: Component = () => {
throw new Error(error.message);
}
- navigate('/');
+ navigate(getPostAuthRedirect());
},
schema: v.object({
code: v.pipe(v.string(), v.nonEmpty(t('auth.login.two-factor.code.required'))),
@@ -194,6 +197,7 @@ export const EmailLoginForm: Component<{ onTwoFactorRequired: () => void }> = (p
const { config } = useConfig();
const { t } = useI18n();
const { createI18nApiError } = useI18nApiErrors({ t });
+ const { getPathWithRedirect } = useAuthRedirect();
const { form, Form, Field } = createForm({
onSubmit: async ({ email, password, rememberMe }) => {
@@ -201,8 +205,10 @@ export const EmailLoginForm: Component<{ onTwoFactorRequired: () => void }> = (p
email,
password,
rememberMe,
- // This URL is where the user will be redirected after email verification
- callbackURL: buildUrl({ baseUrl: config.baseUrl, path: authPagesPaths.emailVerification }),
+ callbackURL: buildUrl({
+ baseUrl: config.baseUrl,
+ path: getPathWithRedirect(authPagesPaths.emailVerification),
+ }),
});
if (loginResult && 'twoFactorRedirect' in loginResult && loginResult.twoFactorRedirect) {
@@ -211,7 +217,7 @@ export const EmailLoginForm: Component<{ onTwoFactorRequired: () => void }> = (p
}
if (isEmailVerificationRequiredError({ error })) {
- navigate('/email-validation-required');
+ navigate(getPathWithRedirect(authPagesPaths.emailValidationRequired));
}
if (error) {
@@ -289,7 +295,12 @@ export const EmailLoginForm: Component<{ onTwoFactorRequired: () => void }> = (p
</Field>
<Show when={config.auth.isPasswordResetEnabled}>
- <Button variant="link" as={A} class="inline p-0! h-auto" href="/request-password-reset">
+ <Button
+ variant="link"
+ as={A}
+ class="inline p-0! h-auto"
+ href={getPathWithRedirect(authPagesPaths.requestPasswordReset)}
+ >
{t('auth.login.form.forgot-password.label')}
</Button>
</Show>
@@ -307,12 +318,13 @@ export const EmailLoginForm: Component<{ onTwoFactorRequired: () => void }> = (p
export const LoginPage: Component = () => {
const { config } = useConfig();
const { t } = useI18n();
+ const { getRedirectPath, getRegisterPathWithRedirect } = useAuthRedirect();
const [getShowEmailLoginForm, setShowEmailLoginForm] = createSignal(false);
const [showTwoFactorForm, setShowTwoFactorForm] = createSignal(false);
const loginWithProvider = async (provider: SsoProviderConfig) => {
- await authWithProvider({ provider, config });
+ await authWithProvider({ provider, config, redirectPath: getRedirectPath() });
};
const getHasSsoProviders = () => getEnabledSsoProviderConfigs({ config }).length > 0;
@@ -369,7 +381,12 @@ export const LoginPage: Component = () => {
<Show when={config.auth.isRegistrationEnabled}>
<p class="text-muted-foreground mt-4">
{t('auth.login.no-account')}{' '}
- <Button variant="link" as={A} class="inline px-0" href="/register">
+ <Button
+ variant="link"
+ as={A}
+ class="inline px-0"
+ href={getRegisterPathWithRedirect()}
+ >
{t('auth.login.register')}
</Button>
</p>
diff --git a/apps/papra-client/src/modules/auth/pages/register.page.tsx b/apps/papra-client/src/modules/auth/pages/register.page.tsx
index 3bf4861e..5c3bde54 100644
--- a/apps/papra-client/src/modules/auth/pages/register.page.tsx
+++ b/apps/papra-client/src/modules/auth/pages/register.page.tsx
@@ -18,12 +18,14 @@ import { authWithProvider, signUp } from '../auth.services';
import { AuthLegalLinks } from '../components/legal-links.component';
import { NoAuthProviderWarning } from '../components/no-auth-provider';
import { SsoProviderButton } from '../components/sso-provider-button.component';
+import { useAuthRedirect } from '../composables/use-auth-redirect.composable';
export const EmailRegisterForm: Component = () => {
const { config } = useConfig();
const navigate = useNavigate();
const { t } = useI18n();
const { createI18nApiError } = useI18nApiErrors({ t });
+ const { getPostAuthRedirect, getPathWithRedirect } = useAuthRedirect();
const { form, Form, Field } = createForm({
onSubmit: async ({ email, password, name }) => {
@@ -31,8 +33,10 @@ export const EmailRegisterForm: Component = () => {
email,
password,
name,
- // This URL is where the user will be redirected after email verification
- callbackURL: buildUrl({ baseUrl: config.baseUrl, path: authPagesPaths.emailVerification }),
+ callbackURL: buildUrl({
+ baseUrl: config.baseUrl,
+ path: getPathWithRedirect(authPagesPaths.emailVerification),
+ }),
});
if (error) {
@@ -40,11 +44,11 @@ export const EmailRegisterForm: Component = () => {
}
if (config.auth.isEmailVerificationRequired) {
- navigate('/email-validation-required');
+ navigate(getPathWithRedirect(authPagesPaths.emailValidationRequired));
return;
}
- navigate('/');
+ navigate(getPostAuthRedirect());
},
schema: v.object({
email: v.pipe(
@@ -134,6 +138,7 @@ export const EmailRegisterForm: Component = () => {
export const RegisterPage: Component = () => {
const { config } = useConfig();
const { t } = useI18n();
+ const { getRedirectPath, getLoginPathWithRedirect } = useAuthRedirect();
if (!config.auth.isRegistrationEnabled) {
return (
@@ -147,7 +152,7 @@ export const RegisterPage: Component = () => {
<p class="text-muted-foreground mt-4">
{t('auth.register.have-account')}{' '}
- <Button variant="link" as={A} class="inline px-0" href="/login">
+ <Button variant="link" as={A} class="inline px-0" href={getLoginPathWithRedirect()}>
{t('auth.register.login')}
</Button>
</p>
@@ -160,7 +165,7 @@ export const RegisterPage: Component = () => {
const [getShowEmailRegister, setShowEmailRegister] = createSignal(false);
const registerWithProvider = async (provider: SsoProviderConfig) => {
- await authWithProvider({ provider, config });
+ await authWithProvider({ provider, config, redirectPath: getRedirectPath() });
};
const getHasSsoProviders = () => getEnabledSsoProviderConfigs({ config }).length > 0;
@@ -212,7 +217,7 @@ export const RegisterPage: Component = () => {
<p class="text-muted-foreground mt-4">
{t('auth.register.have-account')}{' '}
- <Button variant="link" as={A} class="inline px-0" href="/login">
+ <Button variant="link" as={A} class="inline px-0" href={getLoginPathWithRedirect()}>
{t('auth.register.login')}
</Button>
</p>
diff --git a/apps/papra-client/src/modules/auth/pages/request-password-reset.page.tsx b/apps/papra-client/src/modules/auth/pages/request-password-reset.page.tsx
index 18d7e6ce..81483556 100644
--- a/apps/papra-client/src/modules/auth/pages/request-password-reset.page.tsx
+++ b/apps/papra-client/src/modules/auth/pages/request-password-reset.page.tsx
@@ -11,6 +11,8 @@ import { TextField, TextFieldLabel, TextFieldRoot } from '@/modules/ui/component
import { AuthLayout } from '../../ui/layouts/auth-layout.component';
import { requestPasswordReset } from '../auth.services';
import { OpenEmailProvider } from '../components/open-email-provider.component';
+import { authPagesPaths } from '../auth.constants';
+import { useAuthRedirect } from '../composables/use-auth-redirect.composable';
export const ResetPasswordForm: Component<{
onSubmit: (args: { email: string }) => Promise<void>;
@@ -63,6 +65,7 @@ export const ResetPasswordForm: Component<{
export const RequestPasswordResetPage: Component = () => {
const [getHasPasswordResetBeenRequested, setHasPasswordResetBeenRequested] = createSignal(false);
const [getEmail, setEmail] = createSignal<string | undefined>(undefined);
+ const { getLoginPathWithRedirect, getPathWithRedirect } = useAuthRedirect();
const { t } = useI18n();
const { config } = useConfig();
@@ -70,7 +73,7 @@ export const RequestPasswordResetPage: Component = () => {
onMount(() => {
if (!config.auth.isPasswordResetEnabled || !config.auth.providers.email.isEnabled) {
- navigate('/login');
+ navigate(getLoginPathWithRedirect());
}
});
@@ -78,7 +81,7 @@ export const RequestPasswordResetPage: Component = () => {
const { error } = await requestPasswordReset({
email,
redirectTo: buildUrl({
- path: '/reset-password',
+ path: getPathWithRedirect(authPagesPaths.resetPassword),
baseUrl: config.baseUrl,
}),
});
@@ -117,7 +120,7 @@ export const RequestPasswordResetPage: Component = () => {
<Button
as={A}
- href="/login"
+ href={getLoginPathWithRedirect()}
class="w-full"
variant={getHasPasswordResetBeenRequested() ? 'default' : 'ghost'}
>
diff --git a/apps/papra-client/src/modules/auth/pages/reset-password.page.tsx b/apps/papra-client/src/modules/auth/pages/reset-password.page.tsx
index 6144c952..06327ff8 100644
--- a/apps/papra-client/src/modules/auth/pages/reset-password.page.tsx
+++ b/apps/papra-client/src/modules/auth/pages/reset-password.page.tsx
@@ -9,6 +9,8 @@ import { Button } from '@/modules/ui/components/button';
import { TextField, TextFieldLabel, TextFieldRoot } from '@/modules/ui/components/textfield';
import { AuthLayout } from '../../ui/layouts/auth-layout.component';
import { resetPassword } from '../auth.services';
+import { authPagesPaths } from '../auth.constants';
+import { useAuthRedirect } from '../composables/use-auth-redirect.composable';
export const ResetPasswordForm: Component<{
onSubmit: (args: { newPassword: string }) => Promise<void>;
@@ -62,11 +64,12 @@ export const ResetPasswordPage: Component = () => {
const [getHasPasswordBeenReset, setHasPasswordBeenReset] = createSignal(false);
const [searchParams] = useSearchParams();
const token = searchParams.token;
+ const { getLoginPathWithRedirect } = useAuthRedirect();
const { t } = useI18n();
if (!token || typeof token !== 'string') {
- return <Navigate href="/login" />;
+ return <Navigate href={authPagesPaths.login} />;
}
const { config } = useConfig();
@@ -74,7 +77,7 @@ export const ResetPasswordPage: Component = () => {
onMount(() => {
if (!config.auth.isPasswordResetEnabled || !config.auth.providers.email.isEnabled) {
- navigate('/login');
+ navigate(getLoginPathWithRedirect());
}
});
@@ -101,7 +104,7 @@ export const ResetPasswordPage: Component = () => {
<>
<div class="text-muted-foreground mt-1 mb-4">{t('auth.reset-password.reset')}</div>
- <Button as={A} href="/login" class="w-full">
+ <Button as={A} href={getLoginPathWithRedirect()} class="w-full">
{t('auth.reset-password.back-to-login')}
<div class="i-tabler-login-2 ml-2 size-4" />
</Button>
diff --git a/apps/papra-client/src/modules/navigation/navigation.constants.ts b/apps/papra-client/src/modules/navigation/navigation.constants.ts
new file mode 100644
index 00000000..4781ef3e
--- /dev/null
+++ b/apps/papra-client/src/modules/navigation/navigation.constants.ts
@@ -0,0 +1,3 @@
+import { authPagesPaths } from '../auth/auth.constants';
+
+export const PUBLIC_ONLY_PAGES_PATHS = Object.values(authPagesPaths);
diff --git a/apps/papra-client/src/modules/navigation/redirect.test.ts b/apps/papra-client/src/modules/navigation/redirect.test.ts
new file mode 100644
index 00000000..b09c52ee
--- /dev/null
+++ b/apps/papra-client/src/modules/navigation/redirect.test.ts
@@ -0,0 +1,87 @@
+import { describe, test, expect } from 'vitest';
+import { buildPathWithRedirect, parseRedirectPath } from './redirect';
+
+describe('redirect', () => {
+ describe('parseRedirectPath', () => {
+ test('valid paths are preserved, including their query and hash', () => {
+ expect(parseRedirectPath('/dashboard')).to.eql('/dashboard');
+ expect(parseRedirectPath('/dashboard?foo=bar#section')).to.eql('/dashboard?foo=bar#section');
+ expect(
+ parseRedirectPath('/organizations/org_abc?search=report.pdf+draft&sort=created_at'),
+ ).to.eql('/organizations/org_abc?search=report.pdf+draft&sort=created_at');
+ });
+
+ test('paths that do not start with a single slash are invalid', () => {
+ expect(parseRedirectPath('dashboard')).to.eql(undefined);
+ expect(parseRedirectPath('https://evil.com')).to.eql(undefined);
+ expect(parseRedirectPath('//dashboard')).to.eql(undefined);
+ });
+
+ test('paths whose dot segments resolve to a protocol-relative url are invalid', () => {
+ expect(parseRedirectPath('/.//evil.com')).to.eql(undefined);
+ expect(parseRedirectPath('/..//evil.com')).to.eql(undefined);
+ });
+
+ test('paths with disallowed characters in the pathname are invalid', () => {
+ expect(parseRedirectPath('/foo//bar')).to.eql(undefined);
+ expect(parseRedirectPath('/foo<>bar')).to.eql(undefined);
+ expect(parseRedirectPath('/evil.com')).to.eql(undefined);
+ });
+
+ test('dot segments, backslashes and trailing control characters are normalized away', () => {
+ expect(parseRedirectPath('/foo/./bar')).to.eql('/foo/bar');
+ expect(parseRedirectPath('/../../bar')).to.eql('/bar');
+ expect(parseRedirectPath('/foo\\bar')).to.eql('/foo/bar');
+ expect(parseRedirectPath('/foo\0')).to.eql('/foo');
+ });
+
+ test('empty path returns undefined', () => {
+ expect(parseRedirectPath('')).to.eql(undefined);
+ expect(parseRedirectPath(' ')).to.eql(undefined);
+ expect(parseRedirectPath(' \n ')).to.eql(undefined);
+ expect(parseRedirectPath(' \t ')).to.eql(undefined);
+ expect(parseRedirectPath(' \n\t ')).to.eql(undefined);
+
+ expect(parseRedirectPath('/')).to.eql(undefined);
+ expect(parseRedirectPath(' / ')).to.eql(undefined);
+ });
+
+ test('public only routes and arbitrary subpaths are invalid', () => {
+ expect(parseRedirectPath('/login')).to.eql(undefined);
+ expect(parseRedirectPath('/login/')).to.eql(undefined);
+ expect(parseRedirectPath('/login/foobar')).to.eql(undefined);
+ });
+ });
+
+ describe('buildPathWithRedirect', () => {
+ test('a valid redirect path is added as an encoded redirect query param', () => {
+ expect(buildPathWithRedirect({ path: '/login', redirectPath: '/dashboard' })).to.eql(
+ '/login?redirect=%2Fdashboard',
+ );
+ expect(
+ buildPathWithRedirect({ path: '/login', redirectPath: '/dashboard?foo=bar#section' }),
+ ).to.eql('/login?redirect=%2Fdashboard%3Ffoo%3Dbar%23section');
+ });
+
+ test('the query and hash of the base path are preserved', () => {
+ expect(buildPathWithRedirect({ path: '/login?foo=bar', redirectPath: '/dashboard' })).to.eql(
+ '/login?foo=bar&redirect=%2Fdashboard',
+ );
+ expect(buildPathWithRedirect({ path: '/login#section', redirectPath: '/dashboard' })).to.eql(
+ '/login?redirect=%2Fdashboard#section',
+ );
+ });
+
+ test('when the redirect path is missing or invalid, the path is returned unchanged', () => {
+ expect(buildPathWithRedirect({ path: '/login' })).to.eql('/login');
+ expect(buildPathWithRedirect({ path: '/login', redirectPath: undefined })).to.eql('/login');
+ expect(buildPathWithRedirect({ path: '/login', redirectPath: 'https://evil.com' })).to.eql(
+ '/login',
+ );
+ expect(buildPathWithRedirect({ path: '/login', redirectPath: '//evil.com' })).to.eql(
+ '/login',
+ );
+ expect(buildPathWithRedirect({ path: '/login', redirectPath: '/register' })).to.eql('/login');
+ });
+ });
+});
diff --git a/apps/papra-client/src/modules/navigation/redirect.ts b/apps/papra-client/src/modules/navigation/redirect.ts
new file mode 100644
index 00000000..0c4be8cd
--- /dev/null
+++ b/apps/papra-client/src/modules/navigation/redirect.ts
@@ -0,0 +1,70 @@
+import { safelySync } from '@corentinth/chisels';
+import { PUBLIC_ONLY_PAGES_PATHS } from './navigation.constants';
+
+const DUMMY_ORIGIN = 'https://sandbox.internal';
+
+const ALLOWED_PATHNAME_CHARACTERS_REGEX = /^[a-zA-Z0-9\-_/]*$/;
+
+export function parseRedirectPath(rawPath: string | undefined): string | undefined {
+ const path = rawPath?.trim();
+
+ if (!path) {
+ return undefined;
+ }
+
+ if (!path.startsWith('/') || path.startsWith('//') || path.startsWith('/\\')) {
+ return undefined;
+ }
+
+ const [url, urlParsingError] = safelySync(() => new URL(path, DUMMY_ORIGIN));
+
+ if (urlParsingError) {
+ return undefined;
+ }
+
+ // Ensure nothing shady is going on with the URL
+ if (url.origin !== DUMMY_ORIGIN || url.username !== '' || url.password !== '') {
+ return undefined;
+ }
+
+ const { pathname, search, hash } = url;
+
+ if (pathname === '/' || pathname.includes('//')) {
+ return undefined;
+ }
+
+ if (!ALLOWED_PATHNAME_CHARACTERS_REGEX.test(pathname)) {
+ return undefined;
+ }
+
+ // Ensure the redirection is not targeting a public-only page (like login or register)
+ const isPublicAuthPage = PUBLIC_ONLY_PAGES_PATHS.some(
+ (publicPath) => pathname === publicPath || pathname.startsWith(`${publicPath}/`),
+ );
+
+ if (isPublicAuthPage) {
+ return undefined;
+ }
+
+ return `${pathname}${search}${hash}`;
+}
+
+export function buildPathWithRedirect({
+ path,
+ redirectPath: rawRedirectPath,
+}: {
+ path: string;
+ redirectPath?: string;
+}): string {
+ const redirectPath = parseRedirectPath(rawRedirectPath);
+
+ if (!redirectPath) {
+ return path;
+ }
+
+ // In order to preserve queries and hashes
+ const url = new URL(path, DUMMY_ORIGIN);
+ url.searchParams.set('redirect', redirectPath);
+
+ return url.pathname + url.search + url.hash;
+}
diff --git a/apps/papra-client/src/modules/shared/http/api-client.ts b/apps/papra-client/src/modules/shared/http/api-client.ts
index 847cfda5..27935afb 100644
--- a/apps/papra-client/src/modules/shared/http/api-client.ts
+++ b/apps/papra-client/src/modules/shared/http/api-client.ts
@@ -3,6 +3,8 @@ import { safely } from '@corentinth/chisels';
import { buildTimeConfig } from '@/modules/config/config';
import { httpClient } from './http-client';
import { isHttpErrorWithStatusCode } from './http-errors';
+import { buildPathWithRedirect } from '@/modules/navigation/redirect';
+import { authPagesPaths } from '@/modules/auth/auth.constants';
export async function apiClient<T, R extends ResponseType = 'json'>({
path,
@@ -20,7 +22,12 @@ export async function apiClient<T, R extends ResponseType = 'json'>({
const [response, error] = await safely(httpClient<T, R>(requestConfig));
if (isHttpErrorWithStatusCode({ error, statusCode: 401 })) {
- window.location.href = '/login';
+ const currentPath = `${window.location.pathname}${window.location.search}${window.location.hash}`;
+
+ window.location.href = buildPathWithRedirect({
+ path: authPagesPaths.login,
+ redirectPath: currentPath,
+ });
}
if (error) {
diff --git a/apps/papra-client/src/modules/users/components/user-settings.component.tsx b/apps/papra-client/src/modules/users/components/user-settings.component.tsx
index 9ad5a7f6..f38990ee 100644
--- a/apps/papra-client/src/modules/users/components/user-settings.component.tsx
+++ b/apps/papra-client/src/modules/users/components/user-settings.component.tsx
@@ -18,6 +18,7 @@ import {
DropdownMenuTrigger,
} from '@/modules/ui/components/dropdown-menu';
import { LanguageSwitcher } from '@/modules/ui/layouts/sidenav.layout';
+import { authPagesPaths } from '@/modules/auth/auth.constants';
export const UserSettingsDropdown: Component<{ class?: string }> = (props) => {
const { getPendingInvitationsCount } = usePendingInvitationsCount();
@@ -93,7 +94,7 @@ export const UserSettingsDropdown: Component<{ class?: string }> = (props) => {
<DropdownMenuItem
onClick={async () => {
await signOut();
- navigate('/login');
+ navigate(authPagesPaths.login);
}}
class="flex items-center gap-2 cursor-pointer"
>
diff --git a/apps/papra-client/src/modules/users/pages/user-settings.page.tsx b/apps/papra-client/src/modules/users/pages/user-settings.page.tsx
index d4455081..674dd45c 100644
--- a/apps/papra-client/src/modules/users/pages/user-settings.page.tsx
+++ b/apps/papra-client/src/modules/users/pages/user-settings.page.tsx
@@ -20,6 +20,7 @@ import { TwoFactorCard } from '../components/two-factor-card';
import { useUpdateCurrentUser } from '../users.composables';
import { nameSchema } from '../users.schemas';
import { fetchCurrentUser } from '../users.services';
+import { authPagesPaths } from '@/modules/auth/auth.constants';
const LogoutCard: Component = () => {
const [getIsLoading, setIsLoading] = createSignal(false);
@@ -29,7 +30,7 @@ const LogoutCard: Component = () => {
const handleLogout = async () => {
setIsLoading(true);
await signOut();
- navigate('/login');
+ navigate(authPagesPaths.login);
};
return (
diff --git a/apps/papra-client/src/routes.tsx b/apps/papra-client/src/routes.tsx
index d1f4b4a5..a93fbf97 100644
--- a/apps/papra-client/src/routes.tsx
+++ b/apps/papra-client/src/routes.tsx
@@ -272,23 +272,23 @@ export const routes: RouteDefinition[] = [
],
},
{
- path: '/login',
+ path: authPagesPaths.login,
component: () => <PublicOnlyPage children={<LoginPage />} />,
},
{
- path: '/register',
+ path: authPagesPaths.register,
component: () => <PublicOnlyPage children={<RegisterPage />} />,
},
{
- path: '/reset-password',
+ path: authPagesPaths.resetPassword,
component: () => <PublicOnlyPage children={<ResetPasswordPage />} />,
},
{
- path: '/request-password-reset',
+ path: authPagesPaths.requestPasswordReset,
component: () => <PublicOnlyPage children={<RequestPasswordResetPage />} />,
},
{
- path: '/email-validation-required',
+ path: authPagesPaths.emailValidationRequired,
component: () => <PublicOnlyPage children={<EmailValidationRequiredPage />} />,
},
{