Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(auth): added email / password support (#77)

Corentin THOMASSETc8cae4842eff
diff --git a/apps/papra-client/src/modules/auth/auth.models.ts b/apps/papra-client/src/modules/auth/auth.models.ts
new file mode 100644
index 00000000..b005bf45
--- /dev/null
+++ b/apps/papra-client/src/modules/auth/auth.models.ts
@@ -0,0 +1,7 @@
+import { get } from 'lodash-es';
+
+export function isAuthErrorWithCode({ error, code }: { error: unknown; code: string }) {
+ return get(error, 'code') === code;
+}
+
+export const isEmailVerificationRequiredError = ({ error }: { error: unknown }) => isAuthErrorWithCode({ error, code: 'EMAIL_NOT_VERIFIED' });
diff --git a/apps/papra-client/src/modules/auth/auth.services.ts b/apps/papra-client/src/modules/auth/auth.services.ts
index 7959ea0e..5a05f0e4 100644
--- a/apps/papra-client/src/modules/auth/auth.services.ts
+++ b/apps/papra-client/src/modules/auth/auth.services.ts
@@ -5,7 +5,11 @@ import { createDemoAuthClient } from './auth.demo.services';
export const {
useSession,
signIn,
+ signUp,
signOut,
+ forgetPassword,
+ resetPassword,
+ sendVerificationEmail,
} = config.isDemoMode
? createDemoAuthClient()
: createAuthClient({
diff --git a/apps/papra-client/src/modules/auth/magic-link/magic-link.models.ts b/apps/papra-client/src/modules/auth/components/open-email-provider.component.tsx
similarity index 88%
rename from apps/papra-client/src/modules/auth/magic-link/magic-link.models.ts
rename to apps/papra-client/src/modules/auth/components/open-email-provider.component.tsx
index 6ae960b1..0c95532d 100644
--- a/apps/papra-client/src/modules/auth/magic-link/magic-link.models.ts
+++ b/apps/papra-client/src/modules/auth/components/open-email-provider.component.tsx
@@ -1,3 +1,7 @@
+import { cn } from '@/modules/shared/style/cn';
+import { Button } from '@/modules/ui/components/button';
+import { type Component, type ComponentProps, splitProps } from 'solid-js';
+
const providers = [
{
name: 'Gmail',
@@ -239,3 +243,22 @@ export function getEmailProvider({ email }: { email?: string }) {
return { provider };
}
+
+export const OpenEmailProvider: Component<{ email?: string } & ComponentProps<typeof Button>> = (props) => {
+ const [local, rest] = splitProps(props, ['email', 'class']);
+
+ const { provider } = getEmailProvider({ email: local.email });
+
+ if (!provider) {
+ return null;
+ }
+
+ return (
+ <Button as="a" href={provider.url} target="_blank" rel="noopener noreferrer" class={cn('w-full', local.class)} {...rest}>
+ <div class="i-tabler-external-link mr-2 size-4" />
+ Open
+ {' '}
+ {provider.name}
+ </Button>
+ );
+};
diff --git a/apps/papra-client/src/modules/auth/components/sso-provider-button.component.tsx b/apps/papra-client/src/modules/auth/components/sso-provider-button.component.tsx
index 9b7072d4..abe0fc10 100644
--- a/apps/papra-client/src/modules/auth/components/sso-provider-button.component.tsx
+++ b/apps/papra-client/src/modules/auth/components/sso-provider-button.component.tsx
@@ -13,7 +13,7 @@ export const SsoProviderButton: Component<{ name: string; icon: string; onClick:
return (
<Button variant="secondary" class="block w-full flex items-center justify-center" onClick={navigateToProvider} disabled={getIsLoading()}>
- <span class={cn(`mr-2 text-lg inline-block`, getIsLoading() ? 'i-tabler-loader-2 animate-spin' : props.icon)} />
+ <span class={cn(`mr-2 size-4.5 inline-block`, getIsLoading() ? 'i-tabler-loader-2 animate-spin' : props.icon)} />
{props.label}
</Button>
);
diff --git a/apps/papra-client/src/modules/auth/pages/email-validation-required.page.tsx b/apps/papra-client/src/modules/auth/pages/email-validation-required.page.tsx
new file mode 100644
index 00000000..bfee605b
--- /dev/null
+++ b/apps/papra-client/src/modules/auth/pages/email-validation-required.page.tsx
@@ -0,0 +1,21 @@
+import type { Component } from 'solid-js';
+import { AuthLayout } from '../components/auth-layout.component';
+
+export const EmailValidationRequiredPage: Component = () => {
+ return (
+ <AuthLayout>
+ <div class="flex items-center justify-center min-h-screen p-6 pb-18">
+ <div class="max-w-sm w-full">
+ <div class="i-tabler-mail size-12 text-primary mb-2" />
+
+ <h1 class="text-xl font-bold">
+ Verify your email
+ </h1>
+ <p class="text-muted-foreground mt-1 mb-4">
+ A verification email has been sent to your email address. Please verify your email address by clicking the link in the email.
+ </p>
+ </div>
+ </div>
+ </AuthLayout>
+ );
+};
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 49c0e4f4..0755cf53 100644
--- a/apps/papra-client/src/modules/auth/pages/login.page.tsx
+++ b/apps/papra-client/src/modules/auth/pages/login.page.tsx
@@ -1,19 +1,29 @@
+import { config } from '@/modules/config/config';
import { createForm } from '@/modules/shared/form/form';
import { createVitrineUrl } from '@/modules/shared/utils/urls';
import { Button } from '@/modules/ui/components/button';
+import { Checkbox, CheckboxControl, CheckboxLabel } from '@/modules/ui/components/checkbox';
+import { Separator } from '@/modules/ui/components/separator';
import { TextField, TextFieldLabel, TextFieldRoot } from '@/modules/ui/components/textfield';
-import { A } from '@solidjs/router';
-import { type Component, For } from 'solid-js';
+import { A, useNavigate } from '@solidjs/router';
+import { type Component, createSignal, For } from 'solid-js';
import * as v from 'valibot';
import { ssoProviders } from '../auth.constants';
+import { isEmailVerificationRequiredError } from '../auth.models';
import { signIn } from '../auth.services';
import { AuthLayout } from '../components/auth-layout.component';
import { SsoProviderButton } from '../components/sso-provider-button.component';
export const EmailLoginForm: Component = () => {
+ const navigate = useNavigate();
+
const { form, Form, Field } = createForm({
- onSubmit: async ({ email, password }) => {
- const { error } = await signIn.email({ email, password });
+ onSubmit: async ({ email, password, rememberMe }) => {
+ const { error } = await signIn.email({ email, password, rememberMe, callbackURL: config.baseUrl });
+
+ if (isEmailVerificationRequiredError({ error })) {
+ navigate('/email-validation-required');
+ }
if (error) {
throw error;
@@ -30,8 +40,11 @@ export const EmailLoginForm: Component = () => {
v.string('Password is required'),
v.nonEmpty('Please enter your password'),
),
+ rememberMe: v.boolean(),
}),
-
+ initialValues: {
+ rememberMe: true,
+ },
});
return (
@@ -50,12 +63,30 @@ export const EmailLoginForm: Component = () => {
{(field, inputProps) => (
<TextFieldRoot class="flex flex-col gap-1 mb-4">
<TextFieldLabel for="password">Password</TextFieldLabel>
- <TextField type="password" id="password" placeholder="Your password" {...inputProps} autoFocus value={field.value} aria-invalid={Boolean(field.error)} />
+
+ <TextField type="password" id="password" placeholder="Your password" {...inputProps} value={field.value} aria-invalid={Boolean(field.error)} />
{field.error && <div class="text-red-500 text-sm">{field.error}</div>}
</TextFieldRoot>
)}
</Field>
+ <div class="flex justify-between items-center mb-4">
+ <Field name="rememberMe" type="boolean">
+ {(field, inputProps) => (
+ <Checkbox class="flex items-center gap-2" defaultChecked={field.value}>
+ <CheckboxControl inputProps={inputProps} />
+ <CheckboxLabel class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
+ Remember me
+ </CheckboxLabel>
+ </Checkbox>
+ )}
+ </Field>
+
+ <Button variant="link" as={A} class="inline p-0! h-auto" href="/request-password-reset">
+ Forgot password?
+ </Button>
+ </div>
+
<Button type="submit" class="w-full">Login</Button>
<div class="text-red-500 text-sm mt-4">{form.response.message}</div>
@@ -65,6 +96,8 @@ export const EmailLoginForm: Component = () => {
};
export const LoginPage: Component = () => {
+ const [getShowEmailLogin, setShowEmailLogin] = createSignal(false);
+
const loginWithProvider = async (provider: typeof ssoProviders[number]) => {
await signIn.social({ provider: provider.key });
};
@@ -80,9 +113,16 @@ export const LoginPage: Component = () => {
Enter your email or use social login to access your Papra account.
</p>
- {/* <EmailLoginForm />
+ {getShowEmailLogin()
+ ? <EmailLoginForm />
+ : (
+ <Button onClick={() => setShowEmailLogin(true)} class="w-full">
+ <div class="i-tabler-mail mr-2 size-4.5" />
+ Login with email
+ </Button>
+ )}
- <Separator class="my-4" /> */}
+ <Separator class="my-4" />
<For each={ssoProviders}>
{provider => (
diff --git a/apps/papra-client/src/modules/auth/pages/register.page.tsx b/apps/papra-client/src/modules/auth/pages/register.page.tsx
new file mode 100644
index 00000000..7559a7dd
--- /dev/null
+++ b/apps/papra-client/src/modules/auth/pages/register.page.tsx
@@ -0,0 +1,143 @@
+import { config } from '@/modules/config/config';
+import { createForm } from '@/modules/shared/form/form';
+import { createVitrineUrl } from '@/modules/shared/utils/urls';
+import { Button } from '@/modules/ui/components/button';
+import { Separator } from '@/modules/ui/components/separator';
+import { TextField, TextFieldLabel, TextFieldRoot } from '@/modules/ui/components/textfield';
+import { A } from '@solidjs/router';
+import { type Component, createSignal, For } from 'solid-js';
+import * as v from 'valibot';
+import { ssoProviders } from '../auth.constants';
+import { signIn, signUp } from '../auth.services';
+import { AuthLayout } from '../components/auth-layout.component';
+import { SsoProviderButton } from '../components/sso-provider-button.component';
+
+export const EmailRegisterForm: Component = () => {
+ const { form, Form, Field } = createForm({
+ onSubmit: async ({ email, password, name }) => {
+ const { error } = await signUp.email({ email, password, name, callbackURL: config.baseUrl });
+
+ if (error) {
+ throw error;
+ }
+ },
+ schema: v.object({
+ email: v.pipe(
+ v.string(),
+ v.trim(),
+ v.nonEmpty('Please enter an email address'),
+ v.email('This is not a valid email address'),
+ ),
+ password: v.pipe(
+ v.string('Password is required'),
+ v.nonEmpty('Please enter a password'),
+ v.minLength(8, 'Password must be at least 8 characters'),
+ v.maxLength(128, 'Password must be at most 128 characters'),
+ ),
+ name: v.pipe(
+ v.string('Name is required'),
+ v.nonEmpty('Please enter a name'),
+ v.maxLength(64, 'Name must be at most 64 characters'),
+ ),
+ }),
+ });
+
+ return (
+ <Form>
+ <Field name="email">
+ {(field, inputProps) => (
+ <TextFieldRoot class="flex flex-col gap-1 mb-4">
+ <TextFieldLabel for="email">Email</TextFieldLabel>
+ <TextField type="email" id="email" placeholder="Eg. [email protected]" {...inputProps} autoFocus value={field.value} aria-invalid={Boolean(field.error)} />
+ {field.error && <div class="text-red-500 text-sm">{field.error}</div>}
+ </TextFieldRoot>
+ )}
+ </Field>
+
+ <Field name="name">
+ {(field, inputProps) => (
+ <TextFieldRoot class="flex flex-col gap-1 mb-4">
+ <TextFieldLabel for="name">Your full name</TextFieldLabel>
+ <TextField type="text" id="name" placeholder="Eg. Ada Lovelace" {...inputProps} value={field.value} aria-invalid={Boolean(field.error)} />
+ {field.error && <div class="text-red-500 text-sm">{field.error}</div>}
+ </TextFieldRoot>
+ )}
+ </Field>
+
+ <Field name="password">
+ {(field, inputProps) => (
+ <TextFieldRoot class="flex flex-col gap-1 mb-4">
+ <TextFieldLabel for="password">Password</TextFieldLabel>
+
+ <TextField type="password" id="password" placeholder="Your password" {...inputProps} value={field.value} aria-invalid={Boolean(field.error)} />
+ {field.error && <div class="text-red-500 text-sm">{field.error}</div>}
+ </TextFieldRoot>
+ )}
+ </Field>
+
+ <Button type="submit" class="w-full">Register</Button>
+
+ <div class="text-red-500 text-sm mt-4">{form.response.message}</div>
+
+ </Form>
+ );
+};
+
+export const RegisterPage: Component = () => {
+ const [getShowEmailRegister, setShowEmailRegister] = createSignal(false);
+
+ const loginWithProvider = async (provider: typeof ssoProviders[number]) => {
+ await signIn.social({ provider: provider.key });
+ };
+
+ return (
+ <AuthLayout>
+ <div class="flex items-center justify-center min-h-screen p-6 pb-18">
+ <div class="max-w-sm w-full">
+ <h1 class="text-xl font-bold">
+ Register to Papra
+ </h1>
+ <p class="text-muted-foreground mt-1 mb-4">
+ Enter your email or use social login to create your Papra account.
+ </p>
+
+ {getShowEmailRegister()
+ ? <EmailRegisterForm />
+ : (
+ <Button onClick={() => setShowEmailRegister(true)} class="w-full">
+ <div class="i-tabler-mail mr-2 size-4.5" />
+ Register with email
+ </Button>
+ )}
+
+ <Separator class="my-4" />
+
+ <For each={ssoProviders}>
+ {provider => (
+ <SsoProviderButton name={provider.name} icon={provider.icon} onClick={() => loginWithProvider(provider)} label={`Register with ${provider.name}`} />
+ )}
+ </For>
+
+ <p class="text-muted-foreground mt-4">
+ Already have an account?
+ {' '}
+ <Button variant="link" as={A} class="inline px-0" href="/login">
+ Login
+ </Button>
+ </p>
+
+ <p class="text-muted-foreground mt-2">
+ By continuing, you acknowledge that you understand and agree to the
+ {' '}
+ <Button variant="link" as={A} class="inline px-0" href={createVitrineUrl({ path: 'terms-of-service' })}>Terms of Service</Button>
+ {' '}
+ and
+ {' '}
+ <Button variant="link" as={A} class="inline px-0" href={createVitrineUrl({ path: 'privacy-policy' })}>Privacy Policy</Button>
+ .
+ </p>
+ </div>
+ </div>
+ </AuthLayout>
+ );
+};
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
new file mode 100644
index 00000000..08f07ceb
--- /dev/null
+++ b/apps/papra-client/src/modules/auth/pages/request-password-reset.page.tsx
@@ -0,0 +1,105 @@
+import { config } from '@/modules/config/config';
+import { createForm } from '@/modules/shared/form/form';
+import { Button } from '@/modules/ui/components/button';
+import { TextField, TextFieldLabel, TextFieldRoot } from '@/modules/ui/components/textfield';
+import { buildUrl } from '@corentinth/chisels';
+import { A } from '@solidjs/router';
+import { type Component, createSignal } from 'solid-js';
+import * as v from 'valibot';
+import { forgetPassword } from '../auth.services';
+import { AuthLayout } from '../components/auth-layout.component';
+import { OpenEmailProvider } from '../components/open-email-provider.component';
+
+export const ResetPasswordForm: Component<{ onSubmit: (args: { email: string }) => Promise<void> }> = (props) => {
+ const { form, Form, Field } = createForm({
+ onSubmit: props.onSubmit,
+ schema: v.object({
+ email: v.pipe(
+ v.string(),
+ v.trim(),
+ v.nonEmpty('Please enter your email address'),
+ v.email('This is not a valid email address'),
+ ),
+ }),
+ });
+
+ return (
+ <Form>
+ <Field name="email">
+ {(field, inputProps) => (
+ <TextFieldRoot class="flex flex-col gap-1 mb-4">
+ <TextFieldLabel for="email">Email</TextFieldLabel>
+ <TextField type="email" id="email" placeholder="Eg. [email protected]" {...inputProps} autoFocus value={field.value} aria-invalid={Boolean(field.error)} />
+ {field.error && <div class="text-red-500 text-sm">{field.error}</div>}
+ </TextFieldRoot>
+ )}
+ </Field>
+
+ <Button type="submit" class="w-full">
+ Request password reset
+ </Button>
+
+ <div class="text-red-500 text-sm mt-2">{form.response.message}</div>
+
+ </Form>
+ );
+};
+
+export const RequestPasswordResetPage: Component = () => {
+ const [getHasPasswordResetBeenRequested, setHasPasswordResetBeenRequested] = createSignal(false);
+ const [getEmail, setEmail] = createSignal<string | undefined>(undefined);
+
+ const onPasswordResetRequested = async ({ email }: { email: string }) => {
+ const { error } = await forgetPassword({
+ email,
+ redirectTo: buildUrl({
+ path: '/reset-password',
+ baseUrl: config.baseUrl,
+ }),
+ });
+
+ if (error) {
+ throw error;
+ }
+
+ setEmail(email);
+ setHasPasswordResetBeenRequested(true);
+ };
+
+ return (
+ <AuthLayout>
+ <div class="flex items-center justify-center min-h-screen p-6 pb-18">
+ <div class="max-w-sm w-full">
+ <h1 class="text-xl font-bold">
+ Reset your password
+ </h1>
+
+ {getHasPasswordResetBeenRequested()
+ ? (
+ <>
+ <div class="text-muted-foreground mt-1 mb-4">
+ If an account exists for this email, we've sent you an email to reset your password.
+ </div>
+
+ <OpenEmailProvider email={getEmail()} variant="secondary" class="w-full mb-4" />
+ </>
+ )
+ : (
+ <>
+ <p class="text-muted-foreground mt-1 mb-4">
+ Enter your email to reset your password.
+ </p>
+
+ <ResetPasswordForm onSubmit={onPasswordResetRequested} />
+ </>
+ )}
+
+ <Button as={A} href="/login" class="w-full" variant={getHasPasswordResetBeenRequested() ? 'default' : 'ghost'}>
+ <div class="i-tabler-arrow-left mr-2 size-4" />
+ Back to login
+ </Button>
+ </div>
+ </div>
+ </AuthLayout>
+ );
+};
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
new file mode 100644
index 00000000..5c100603
--- /dev/null
+++ b/apps/papra-client/src/modules/auth/pages/reset-password.page.tsx
@@ -0,0 +1,102 @@
+import { createForm } from '@/modules/shared/form/form';
+import { Button } from '@/modules/ui/components/button';
+import { TextField, TextFieldLabel, TextFieldRoot } from '@/modules/ui/components/textfield';
+import { A, Navigate, useSearchParams } from '@solidjs/router';
+import { type Component, createSignal } from 'solid-js';
+import * as v from 'valibot';
+import { resetPassword } from '../auth.services';
+import { AuthLayout } from '../components/auth-layout.component';
+
+export const ResetPasswordForm: Component<{ onSubmit: (args: { newPassword: string }) => Promise<void> }> = (props) => {
+ const { form, Form, Field } = createForm({
+ onSubmit: props.onSubmit,
+ schema: v.object({
+ newPassword: v.pipe(
+ v.string(),
+ v.nonEmpty('Please enter your new password'),
+ v.minLength(8, 'Password must be at least 8 characters long'),
+ v.maxLength(128, 'Password must be at most 128 characters long'),
+ ),
+ }),
+ });
+
+ return (
+ <Form>
+ <Field name="newPassword">
+ {(field, inputProps) => (
+ <TextFieldRoot class="flex flex-col gap-1 mb-4">
+ <TextFieldLabel for="newPassword">New password</TextFieldLabel>
+ <TextField type="password" id="newPassword" placeholder="Your new password" {...inputProps} autoFocus value={field.value} aria-invalid={Boolean(field.error)} />
+ {field.error && <div class="text-red-500 text-sm">{field.error}</div>}
+ </TextFieldRoot>
+ )}
+ </Field>
+
+ <Button type="submit" class="w-full">
+ Reset password
+ </Button>
+
+ <div class="text-red-500 text-sm mt-2">{form.response.message}</div>
+
+ </Form>
+ );
+};
+
+export const ResetPasswordPage: Component = () => {
+ const [getHasPasswordBeenReset, setHasPasswordBeenReset] = createSignal(false);
+ const [searchParams] = useSearchParams();
+ const token = searchParams.token;
+
+ if (!token || typeof token !== 'string') {
+ return <Navigate href="/login" />;
+ }
+
+ const onPasswordResetRequested = async ({ newPassword }: { newPassword: string }) => {
+ const { error } = await resetPassword({
+ newPassword,
+ token,
+ });
+
+ if (error) {
+ throw error;
+ }
+
+ setHasPasswordBeenReset(true);
+ };
+
+ return (
+ <AuthLayout>
+ <div class="flex items-center justify-center min-h-screen p-6 pb-18">
+ <div class="max-w-sm w-full">
+ <h1 class="text-xl font-bold">
+ Reset your password
+ </h1>
+
+ {getHasPasswordBeenReset()
+ ? (
+ <>
+ <div class="text-muted-foreground mt-1 mb-4">
+ Your password has been reset.
+ </div>
+
+ <Button as={A} href="/login" class="w-full">
+ Go to login
+ <div class="i-tabler-login-2 ml-2 size-4" />
+ </Button>
+ </>
+ )
+ : (
+ <>
+ <p class="text-muted-foreground mt-1 mb-4">
+ Enter your new password.
+ </p>
+
+ <ResetPasswordForm onSubmit={onPasswordResetRequested} />
+ </>
+ )}
+
+ </div>
+ </div>
+ </AuthLayout>
+ );
+};
diff --git a/apps/papra-client/src/modules/config/config.ts b/apps/papra-client/src/modules/config/config.ts
index 8cf7cda2..e58343ad 100644
--- a/apps/papra-client/src/modules/config/config.ts
+++ b/apps/papra-client/src/modules/config/config.ts
@@ -1,5 +1,6 @@
export const config = {
papraVersion: import.meta.env.VITE_PAPRA_VERSION,
+ baseUrl: (import.meta.env.VITE_BASE_URL ?? window.location.origin) as string,
baseApiUrl: (import.meta.env.VITE_BASE_API_URL ?? window.location.origin) as string,
vitrineBaseUrl: (import.meta.env.VITE_VITRINE_BASE_URL ?? 'http://localhost:3000/') as string,
isRegistrationEnabled: import.meta.env.VITE_IS_REGISTRATION_ENABLED !== 'false',
diff --git a/apps/papra-client/src/modules/ui/components/checkbox.tsx b/apps/papra-client/src/modules/ui/components/checkbox.tsx
new file mode 100644
index 00000000..aefb1660
--- /dev/null
+++ b/apps/papra-client/src/modules/ui/components/checkbox.tsx
@@ -0,0 +1,51 @@
+import type { CheckboxControlProps } from '@kobalte/core/checkbox';
+import type { PolymorphicProps } from '@kobalte/core/polymorphic';
+import type { JSX, ValidComponent, VoidProps } from 'solid-js';
+import { cn } from '@/modules/shared/style/cn';
+import { Checkbox as CheckboxPrimitive } from '@kobalte/core/checkbox';
+import { splitProps } from 'solid-js';
+
+export const CheckboxLabel = CheckboxPrimitive.Label;
+export const Checkbox = CheckboxPrimitive;
+export const CheckboxErrorMessage = CheckboxPrimitive.ErrorMessage;
+export const CheckboxDescription = CheckboxPrimitive.Description;
+
+type checkboxControlProps<T extends ValidComponent = 'div'> = VoidProps<CheckboxControlProps<T> & { class?: string; inputProps?: JSX.InputHTMLAttributes<HTMLInputElement> }>;
+
+export function CheckboxControl<T extends ValidComponent = 'div'>(props: PolymorphicProps<T, checkboxControlProps<T>>) {
+ const [local, rest] = splitProps(
+ props,
+ ['class', 'children', 'inputProps'],
+ );
+
+ return (
+ <>
+ <CheckboxPrimitive.Input class="[&:focus-visible+div]:(outline-none ring-1.5 ring-ring ring-offset-2 ring-offset-background)" {...local.inputProps} />
+ <CheckboxPrimitive.Control
+ class={cn(
+ 'h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:(outline-none ring-1.5 ring-ring) data-[disabled]:(cursor-not-allowed opacity-50) data-[checked]:(bg-primary text-primary-foreground) transition-shadow',
+ local.class,
+ )}
+ {...rest as any}
+ >
+ <CheckboxPrimitive.Indicator class="flex items-center justify-center text-current">
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 24 24"
+ class="h-4 w-4"
+ >
+ <path
+ fill="none"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ d="m5 12l5 5L20 7"
+ />
+ <title>Checkbox</title>
+ </svg>
+ </CheckboxPrimitive.Indicator>
+ </CheckboxPrimitive.Control>
+ </>
+ );
+}
diff --git a/apps/papra-client/src/routes.tsx b/apps/papra-client/src/routes.tsx
index 485d5ce8..d5b49bce 100644
--- a/apps/papra-client/src/routes.tsx
+++ b/apps/papra-client/src/routes.tsx
@@ -2,8 +2,11 @@ import { Navigate, type RouteDefinition, useParams } from '@solidjs/router';
import { createQuery } from '@tanstack/solid-query';
import { Match, Show, Suspense, Switch } from 'solid-js';
import { createProtectedPage } from './modules/auth/middleware/protected-page.middleware';
-import { GenericAuthPage } from './modules/auth/pages/generic-auth.page';
+import { EmailValidationRequiredPage } from './modules/auth/pages/email-validation-required.page';
import { LoginPage } from './modules/auth/pages/login.page';
+import { RegisterPage } from './modules/auth/pages/register.page';
+import { RequestPasswordResetPage } from './modules/auth/pages/request-password-reset.page';
+import { ResetPasswordPage } from './modules/auth/pages/reset-password.page';
import { DeletedDocumentsPage } from './modules/documents/pages/deleted-documents.page';
import { DocumentPage } from './modules/documents/pages/document.page';
import { DocumentsPage } from './modules/documents/pages/documents.page';
@@ -132,7 +135,19 @@ export const routes: RouteDefinition[] = [
},
{
path: '/register',
- component: createProtectedPage({ authType: 'public-only', component: () => <GenericAuthPage type="register" /> }),
+ component: createProtectedPage({ authType: 'public-only', component: RegisterPage }),
+ },
+ {
+ path: '/reset-password',
+ component: createProtectedPage({ authType: 'public-only', component: ResetPasswordPage }),
+ },
+ {
+ path: '/request-password-reset',
+ component: createProtectedPage({ authType: 'public-only', component: RequestPasswordResetPage }),
+ },
+ {
+ path: '/email-validation-required',
+ component: createProtectedPage({ authType: 'public-only', component: EmailValidationRequiredPage }),
},
{
path: '*404',
diff --git a/apps/papra-server/src/index.ts b/apps/papra-server/src/index.ts
index 3ca12264..9c913a6f 100644
--- a/apps/papra-server/src/index.ts
+++ b/apps/papra-server/src/index.ts
@@ -1,5 +1,6 @@
import process, { env } from 'node:process';
import { serve } from '@hono/node-server';
+import { getAuth } from './modules/app/auth/auth.services';
import { setupDatabase } from './modules/app/database/database';
import { createServer } from './modules/app/server';
import { parseConfig } from './modules/config/config';
@@ -8,10 +9,10 @@ import { createLogger } from './modules/shared/logger/logger';
const logger = createLogger({ namespace: 'app-server' });
const { config } = parseConfig({ env });
-
const { db } = setupDatabase(config.database);
+const { auth } = getAuth({ db, config });
-const { app } = createServer({ config, db });
+const { app } = createServer({ config, db, auth });
const server = serve(
{
diff --git a/apps/papra-server/src/modules/app/auth/auth.config.ts b/apps/papra-server/src/modules/app/auth/auth.config.ts
index 70741e6c..5a523a26 100644
--- a/apps/papra-server/src/modules/app/auth/auth.config.ts
+++ b/apps/papra-server/src/modules/app/auth/auth.config.ts
@@ -19,6 +19,28 @@ export const authConfig = {
default: 'true',
env: 'AUTH_IS_REGISTRATION_ENABLED',
},
+ isPasswordResetEnabled: {
+ doc: 'Whether password reset is enabled',
+ schema: z
+ .string()
+ .trim()
+ .toLowerCase()
+ .transform(x => x === 'true')
+ .pipe(z.boolean()),
+ default: 'true',
+ env: 'AUTH_IS_PASSWORD_RESET_ENABLED',
+ },
+ isEmailVerificationRequired: {
+ doc: 'Whether email verification is required',
+ schema: z
+ .string()
+ .trim()
+ .toLowerCase()
+ .transform(x => x === 'true')
+ .pipe(z.boolean()),
+ default: 'true',
+ env: 'AUTH_IS_EMAIL_VERIFICATION_REQUIRED',
+ },
providers: {
github: {
clientId: {
diff --git a/apps/papra-server/src/modules/app/auth/auth.emails.services.ts b/apps/papra-server/src/modules/app/auth/auth.emails.services.ts
new file mode 100644
index 00000000..12e0bc33
--- /dev/null
+++ b/apps/papra-server/src/modules/app/auth/auth.emails.services.ts
@@ -0,0 +1,11 @@
+import type { User } from 'better-auth';
+
+export async function sendVerificationEmail({ user, url, token }: { user: User; url: string; token: string }) {
+ // eslint-disable-next-line no-console
+ console.log('sendVerificationEmail', { user, url, token });
+}
+
+export async function sendPasswordResetEmail({ user, url, token }: { user: User; url: string; token: string }) {
+ // eslint-disable-next-line no-console
+ console.log('sendPasswordResetEmail', { user, url, token });
+}
diff --git a/apps/papra-server/src/modules/app/auth/auth.services.ts b/apps/papra-server/src/modules/app/auth/auth.services.ts
index c60b9597..1f8c80c1 100644
--- a/apps/papra-server/src/modules/app/auth/auth.services.ts
+++ b/apps/papra-server/src/modules/app/auth/auth.services.ts
@@ -5,6 +5,7 @@ import { drizzleAdapter } from 'better-auth/adapters/drizzle';
import { APIError } from 'better-auth/api';
import { createLogger } from '../../shared/logger/logger';
import { usersTable } from '../../users/users.table';
+import { sendPasswordResetEmail, sendVerificationEmail } from './auth.emails.services';
import { accountsTable, sessionsTable, verificationsTable } from './auth.tables';
export type Auth = ReturnType<typeof getAuth>['auth'];
@@ -29,7 +30,10 @@ export function getAuth({ db, config }: { db: Database; config: Config }) {
},
emailAndPassword: {
enabled: true,
- requireEmailVerification: true,
+ requireEmailVerification: config.auth.isEmailVerificationRequired,
+ sendResetPassword: config.auth.isPasswordResetEnabled
+ ? sendPasswordResetEmail
+ : undefined,
},
appName: 'Papra',
account: {
@@ -38,10 +42,7 @@ export function getAuth({ db, config }: { db: Database; config: Config }) {
},
},
emailVerification: {
- sendVerificationEmail: async ({ user, url, token }) => {
- // eslint-disable-next-line no-console
- console.log('sendVerificationEmail', { user, url, token });
- },
+ sendVerificationEmail,
},
database: drizzleAdapter(
diff --git a/apps/papra-server/src/modules/app/database/database.middleware.ts b/apps/papra-server/src/modules/app/database/database.middleware.ts
deleted file mode 100644
index ef53acca..00000000
--- a/apps/papra-server/src/modules/app/database/database.middleware.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import type { ServerInstanceGenerics } from '../server.types';
-import type { Database } from './database.types';
-import { createMiddleware } from 'hono/factory';
-
-export function createDatabaseMiddleware({ db }: { db: Database }) {
- return createMiddleware<ServerInstanceGenerics>(async (context, next) => {
- context.set('db', db);
-
- await next();
- });
-}
diff --git a/apps/papra-server/src/modules/app/middlewares/config.middleware.ts b/apps/papra-server/src/modules/app/middlewares/config.middleware.ts
deleted file mode 100644
index 9b4283d0..00000000
--- a/apps/papra-server/src/modules/app/middlewares/config.middleware.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import type { Config } from '../../config/config.types';
-import { createMiddleware } from 'hono/factory';
-
-export function createConfigMiddleware({ config }: { config: Config }) {
- return createMiddleware(async (context, next) => {
- context.set('config', config);
- return next();
- });
-}
diff --git a/apps/papra-server/src/modules/app/server.routes.ts b/apps/papra-server/src/modules/app/server.routes.ts
index c5604f43..706a1f02 100644
--- a/apps/papra-server/src/modules/app/server.routes.ts
+++ b/apps/papra-server/src/modules/app/server.routes.ts
@@ -5,8 +5,6 @@ import { registerUsersPrivateRoutes } from '../users/users.routes';
import { createUnauthorizedError } from './auth/auth.errors';
import { getSession } from './auth/auth.models';
import { registerAuthRoutes } from './auth/auth.routes';
-// import { jwtValidationMiddleware } from './auth/middlewares/auth.middleware';
-// import { impersonationMiddleware } from './auth/middlewares/impersonation.middleware';
import { registerHealthCheckRoutes } from './health-check/health-check.routes';
export function registerRoutes({ app }: { app: ServerInstance }) {
@@ -21,9 +19,6 @@ function registerPublicRoutes({ app }: { app: ServerInstance }) {
}
function registerPrivateRoutes({ app }: { app: ServerInstance }) {
- // app.use(jwtValidationMiddleware);
- // app.use(impersonationMiddleware);
-
app.use(async (context, next) => {
const { session } = getSession({ context });
diff --git a/apps/papra-server/src/modules/app/server.ts b/apps/papra-server/src/modules/app/server.ts
index fd67a817..9695bc81 100644
--- a/apps/papra-server/src/modules/app/server.ts
+++ b/apps/papra-server/src/modules/app/server.ts
@@ -1,26 +1,41 @@
import type { Config } from '../config/config.types';
+import type { Auth } from './auth/auth.services';
import type { Database } from './database/database.types';
import type { ServerInstanceGenerics } from './server.types';
import { Hono } from 'hono';
import { secureHeaders } from 'hono/secure-headers';
import { parseConfig } from '../config/config';
-import { createDatabaseMiddleware } from './database/database.middleware';
+import { getAuth } from './auth/auth.services';
import { registerAssetsMiddleware } from './middlewares/assets.middleware';
-import { createConfigMiddleware } from './middlewares/config.middleware';
import { corsMiddleware } from './middlewares/cors.middleware';
import { registerErrorMiddleware } from './middlewares/errors.middleware';
import { loggerMiddleware } from './middlewares/logger.middleware';
import { timeoutMiddleware } from './middlewares/timeout.middleware';
import { registerRoutes } from './server.routes';
-export function createServer({ config = parseConfig().config, db }: { config?: Config; db: Database }) {
+export function createServer({
+ db,
+ config = parseConfig().config,
+ auth = getAuth({ config, db }).auth,
+}: {
+ db: Database;
+ config?: Config;
+ auth?: Auth;
+}) {
const app = new Hono<ServerInstanceGenerics>({ strict: true });
app.use(loggerMiddleware);
- app.use(createConfigMiddleware({ config }));
+
+ app.use((context, next) => {
+ context.set('config', config);
+ context.set('db', db);
+ context.set('auth', auth);
+
+ return next();
+ });
+
app.use(corsMiddleware);
app.use(timeoutMiddleware);
- app.use(createDatabaseMiddleware({ db }));
app.use(secureHeaders());
registerAssetsMiddleware({ app });
diff --git a/apps/papra-server/src/modules/app/server.types.ts b/apps/papra-server/src/modules/app/server.types.ts
index d4204793..76536482 100644
--- a/apps/papra-server/src/modules/app/server.types.ts
+++ b/apps/papra-server/src/modules/app/server.types.ts
@@ -1,14 +1,15 @@
import type { Context as BaseContext, Hono } from 'hono';
import type { Config } from '../config/config.types';
-import type { getAuth } from './auth/auth.services';
+import type { Auth } from './auth/auth.services';
import type { Database } from './database/database.types';
export type ServerInstanceGenerics = {
Variables: {
config: Config;
db: Database;
- user: ReturnType<typeof getAuth>['auth']['$Infer']['Session']['user'] | null;
- session: ReturnType<typeof getAuth>['auth']['$Infer']['Session']['session'] | null;
+ auth: Auth;
+ user: Auth['$Infer']['Session']['user'] | null;
+ session: Auth['$Infer']['Session']['session'] | null;
};
};