1
0
mirror of https://github.com/pocket-id/pocket-id.git synced 2026-03-24 03:55:06 +00:00

feat: add support for email verification (#1223)

This commit is contained in:
Elias Schneider
2026-01-11 12:31:26 +01:00
committed by GitHub
parent e955118a6f
commit 1e7442f5df
60 changed files with 1452 additions and 700 deletions

View File

@@ -0,0 +1,79 @@
<script lang="ts">
import { page } from '$app/state';
import * as Alert from '$lib/components/ui/alert';
import { Button } from '$lib/components/ui/button';
import { m } from '$lib/paraglide/messages';
import UserService from '$lib/services/user-service';
import appConfigStore from '$lib/stores/application-configuration-store';
import userStore from '$lib/stores/user-store';
import { axiosErrorToast } from '$lib/utils/error-util';
import { LucideAlertTriangle, LucideCheckCircle2, LucideCircleX } from '@lucide/svelte';
import { onMount } from 'svelte';
import { toast } from 'svelte-sonner';
import { get } from 'svelte/store';
const userService = new UserService();
let emailVerificationState = $state(page.url.searchParams.get('emailVerificationState'));
async function sendEmailVerification() {
await userService
.sendEmailVerification()
.then(() => {
toast.success(m.email_verification_sent());
})
.catch(axiosErrorToast);
}
function onDismiss() {
const url = new URL(page.url);
url.searchParams.delete('emailVerificationState');
history.replaceState(null, '', url.toString());
emailVerificationState = null;
}
onMount(() => {
const user = get(userStore);
if (emailVerificationState === 'success' && user) {
user.emailVerified = true;
userStore.setUser(user);
}
});
</script>
{#if emailVerificationState}
{#if emailVerificationState === 'success'}
<Alert.Root variant="success" {onDismiss}>
<LucideCheckCircle2 class="size-4" />
<Alert.Title class="font-semibold">{m.email_verification_success_title()}</Alert.Title>
<Alert.Description class="text-sm">
{m.email_verification_success_description()}
</Alert.Description>
</Alert.Root>
{:else}
<Alert.Root variant="destructive" {onDismiss}>
<LucideCircleX class="size-4" />
<Alert.Title class="font-semibold">{m.email_verification_error_title()}</Alert.Title>
<Alert.Description class="text-sm">
{emailVerificationState}
</Alert.Description>
</Alert.Root>
{/if}
{:else if $userStore && $appConfigStore.emailVerificationEnabled && !$userStore.emailVerified}
<Alert.Root variant="warning" class="flex gap-3">
<LucideAlertTriangle class="size-4" />
<div class="md:flex md:w-full md:place-content-between">
<div>
<Alert.Title class="font-semibold">{m.email_verification_warning()}</Alert.Title>
<Alert.Description class="text-sm">
{m.email_verification_warning_description()}
</Alert.Description>
</div>
<div>
<Button class="mt-2 md:mt-0" usePromiseLoading onclick={sendEmailVerification}>
{m.send_email()}
</Button>
</div>
</div>
</Alert.Root>
{/if}

View File

@@ -31,6 +31,7 @@
children,
onInput,
labelFor,
inputClass,
...restProps
}: HTMLAttributes<HTMLDivElement> &
(WithChildren | WithoutChildren) & {
@@ -39,6 +40,7 @@
docsLink?: string;
placeholder?: string;
disabled?: boolean;
inputClass?: string;
type?: 'text' | 'password' | 'email' | 'number' | 'checkbox' | 'date';
onInput?: (e: FormInputEvent) => void;
} = $props();
@@ -73,6 +75,7 @@
{:else}
<Input
aria-invalid={!!input.error}
class={inputClass}
{id}
{placeholder}
{type}

View File

@@ -6,9 +6,11 @@
variants: {
variant: {
default: 'bg-card text-card-foreground',
success:
'bg-green-100 text-green-900 dark:bg-green-900 dark:text-green-100 [&>svg]:text-green-900 dark:[&>svg]:text-green-100',
info: 'bg-blue-100 text-blue-900 dark:bg-blue-900 dark:text-blue-100 [&>svg]:text-blue-900 dark:[&>svg]:text-blue-100',
destructive:
'text-destructive bg-card *:data-[slot=alert-description]:text-destructive/90 [&>svg]:text-current',
'bg-red-100 text-red-900 dark:bg-red-900 dark:text-red-100 [&>svg]:text-red-900 dark:[&>svg]:text-red-100',
warning:
'bg-warning text-warning-foreground border-warning/40 [&>svg]:text-warning-foreground'
}
@@ -32,10 +34,12 @@
class: className,
variant = 'default',
children,
onDismiss,
dismissibleId = undefined,
...restProps
}: WithElementRef<HTMLAttributes<HTMLDivElement>> & {
variant?: AlertVariant;
onDismiss?: () => void;
dismissibleId?: string;
} = $props();
@@ -49,6 +53,7 @@
});
function dismiss() {
onDismiss?.();
if (dismissibleId) {
const dismissedAlerts = JSON.parse(localStorage.getItem('dismissed-alerts') || '[]');
localStorage.setItem('dismissed-alerts', JSON.stringify([...dismissedAlerts, dismissibleId]));
@@ -66,7 +71,7 @@
role="alert"
>
{@render children?.()}
{#if dismissibleId}
{#if dismissibleId || onDismiss}
<button onclick={dismiss} class="absolute right-0 top-0 m-3 text-black dark:text-white"
><LucideX class="size-4" /></button
>

View File

@@ -0,0 +1,13 @@
import Root from "./toggle.svelte";
export {
toggleVariants,
type ToggleSize,
type ToggleVariant,
type ToggleVariants,
} from "./toggle.svelte";
export {
Root,
//
Root as Toggle,
};

View File

@@ -0,0 +1,52 @@
<script lang="ts" module>
import { type VariantProps, tv } from "tailwind-variants";
export const toggleVariants = tv({
base: "hover:bg-muted hover:text-muted-foreground data-[state=on]:bg-accent data-[state=on]:text-accent-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
variants: {
variant: {
default: "bg-transparent",
outline:
"border-input hover:bg-accent hover:text-accent-foreground border bg-transparent shadow-xs",
},
size: {
default: "h-9 min-w-9 px-2",
sm: "h-8 min-w-8 px-1.5",
lg: "h-10 min-w-10 px-2.5",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
});
export type ToggleVariant = VariantProps<typeof toggleVariants>["variant"];
export type ToggleSize = VariantProps<typeof toggleVariants>["size"];
export type ToggleVariants = VariantProps<typeof toggleVariants>;
</script>
<script lang="ts">
import { Toggle as TogglePrimitive } from "bits-ui";
import { cn } from "$lib/utils/style.js";
let {
ref = $bindable(null),
pressed = $bindable(false),
class: className,
size = "default",
variant = "default",
...restProps
}: TogglePrimitive.RootProps & {
variant?: ToggleVariant;
size?: ToggleSize;
} = $props();
</script>
<TogglePrimitive.Root
bind:ref
bind:pressed
data-slot="toggle"
class={cn(toggleVariants({ variant, size }), className)}
{...restProps}
/>

View File

@@ -2,7 +2,7 @@ import userStore from '$lib/stores/user-store';
import type { ListRequestOptions, Paginated } from '$lib/types/list-request.type';
import type { SignupToken } from '$lib/types/signup-token.type';
import type { UserGroup } from '$lib/types/user-group.type';
import type { User, UserCreate, UserSignUp } from '$lib/types/user.type';
import type { AccountUpdate, User, UserCreate, UserSignUp } from '$lib/types/user.type';
import { cachedProfilePicture } from '$lib/utils/cached-image-util';
import { get } from 'svelte/store';
import APIService from './api-service';
@@ -38,7 +38,7 @@ export default class UserService extends APIService {
return res.data as User;
};
updateCurrent = async (user: UserCreate) => {
updateCurrent = async (user: AccountUpdate) => {
const res = await this.api.put('/users/me', user);
return res.data as User;
};
@@ -121,4 +121,14 @@ export default class UserService extends APIService {
deleteSignupToken = async (tokenId: string) => {
await this.api.delete(`/signup-tokens/${tokenId}`);
};
sendEmailVerification = async () => {
const res = await this.api.post('/users/me/send-email-verification');
return res.data as User;
};
verifyEmail = async (token: string) => {
const res = await this.api.post('/users/me/verify-email', { token });
return res.data as User;
};
}

View File

@@ -7,6 +7,7 @@ export type AppConfig = {
allowUserSignups: 'disabled' | 'withToken' | 'open';
emailOneTimeAccessAsUnauthenticatedEnabled: boolean;
emailOneTimeAccessAsAdminEnabled: boolean;
emailVerificationEnabled: boolean;
ldapEnabled: boolean;
disableAnimations: boolean;
uiConfigDisabled: boolean;

View File

@@ -6,6 +6,7 @@ export type User = {
id: string;
username: string;
email: string | undefined;
emailVerified: boolean;
firstName: string;
lastName?: string;
displayName: string;
@@ -19,6 +20,11 @@ export type User = {
export type UserCreate = Omit<User, 'id' | 'customClaims' | 'ldapId' | 'userGroups'>;
export type UserSignUp = Omit<UserCreate, 'isAdmin' | 'disabled' | 'displayName'> & {
export type AccountUpdate = Omit<UserCreate, 'isAdmin' | 'disabled' | 'emailVerified'>
export type UserSignUp = Omit<
UserCreate,
'isAdmin' | 'disabled' | 'displayName' | 'emailVerified'
> & {
token?: string;
};

View File

@@ -2,7 +2,8 @@ import type { User } from '$lib/types/user.type';
// Returns the path to redirect to based on the current path and user authentication status
// If no redirect is needed, it returns null
export function getAuthRedirectPath(path: string, user: User | null) {
export function getAuthRedirectPath(url: URL, user: User | null) {
const path = url.pathname;
const isSignedIn = !!user;
const isAdmin = user?.isAdmin;
@@ -19,7 +20,8 @@ export function getAuthRedirectPath(path: string, user: User | null) {
const isAdminPath = path == '/settings/admin' || path.startsWith('/settings/admin/');
if (!isUnauthenticatedOnlyPath && !isPublicPath && !isSignedIn) {
return '/login';
const redirect = url.pathname + url.search;
return `/login?redirect=${encodeURIComponent(redirect)}`;
}
if (isUnauthenticatedOnlyPath && isSignedIn) {
@@ -29,4 +31,6 @@ export function getAuthRedirectPath(path: string, user: User | null) {
if (isAdminPath && !isAdmin) {
return '/settings';
}
return null;
}