Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 148 additions & 24 deletions src/lib/components/account/sendVerificationEmailModal.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,116 @@
import { invalidate } from '$app/navigation';
import { Modal } from '$lib/components';
import { Button } from '$lib/elements/forms';
import Link from '$lib/elements/link.svelte';
import { addNotification } from '$lib/stores/notifications';
import { sdk } from '$lib/stores/sdk';
import { user } from '$lib/stores/user';
import { get } from 'svelte/store';
import { page } from '$app/state';
import { Card, Layout, Typography } from '@appwrite.io/pink-svelte';
import { Dependencies } from '$lib/constants';
import { onMount } from 'svelte';
import { onMount, onDestroy } from 'svelte';
import { isCloud } from '$lib/system';
import { wizard, isNewWizardStatusOpen } from '$lib/stores/wizard';
import { logout } from '$lib/helpers/logout';
import { browser } from '$app/environment';

let { show = $bindable(false) } = $props();
let creating = $state(false);
let emailSent = $state(false);
let resendTimer = $state(0);
let timerInterval: ReturnType<typeof setInterval> | null = null;

// Timer state key for localStorage
const TIMER_END_KEY = 'email-verification-timer-end';
const EMAIL_SENT_KEY = 'email-verification-sent';

let cleanUrl = $derived(page.url.origin + page.url.pathname);

async function onSubmit() {
if (creating) return;
// Determine if we should show the modal
const hasUser = $derived(!!$user);
const needsEmailVerification = $derived(hasUser && !$user.emailVerification);
const notOnOnboarding = $derived(!page.route.id.includes('/onboarding'));
const notOnWizard = $derived(!$wizard.show && !$isNewWizardStatusOpen);
const shouldShowModal = $derived(
isCloud && hasUser && needsEmailVerification && notOnOnboarding && notOnWizard
);

function startResendTimer() {
const timerEndTime = Date.now() + 60 * 1000;
resendTimer = 60;
emailSent = true;

if (browser) {
localStorage.setItem(TIMER_END_KEY, timerEndTime.toString());
localStorage.setItem(EMAIL_SENT_KEY, 'true');
}

startTimerCountdown(timerEndTime);
}

function restoreTimerState() {
if (!browser) return;

const savedTimerEnd = localStorage.getItem(TIMER_END_KEY);
const savedEmailSent = localStorage.getItem(EMAIL_SENT_KEY);

if (savedTimerEnd && savedEmailSent) {
const timerEndTime = parseInt(savedTimerEnd);
const now = Date.now();
const remainingTime = Math.max(0, Math.ceil((timerEndTime - now) / 1000));

if (remainingTime > 0) {
resendTimer = remainingTime;
emailSent = true;
startTimerCountdown(timerEndTime);
} else {
// Timer has expired, clean up
localStorage.removeItem(TIMER_END_KEY);
localStorage.removeItem(EMAIL_SENT_KEY);
resendTimer = 0;
emailSent = false;
}
}
}

function startTimerCountdown(timerEndTime: number) {
timerInterval = setInterval(() => {
const now = Date.now();
const remainingTime = Math.max(0, Math.ceil((timerEndTime - now) / 1000));

resendTimer = remainingTime;

if (remainingTime <= 0) {
clearInterval(timerInterval);
timerInterval = null;
if (browser) {
localStorage.removeItem(TIMER_END_KEY);
localStorage.removeItem(EMAIL_SENT_KEY);
}
}
}, 1000);
}

async function sendVerificationEmail() {
if (creating || resendTimer > 0) return;
creating = true;
try {
await sdk.forConsole.account.createVerification({ url: cleanUrl });
addNotification({ message: 'Verification email has been sent', type: 'success' });
emailSent = true;
show = false;
startResendTimer();
// Don't close modal - user needs to verify email first
} catch (error) {
addNotification({ message: error.message, type: 'error' });
} finally {
creating = false;
}
}

function onSubmit() {
// This is required by the Modal component but we handle clicks directly
}

async function updateEmailVerification() {
const searchParams = page.url.searchParams;
const userId = searchParams.get('userId');
Expand All @@ -40,10 +120,6 @@
if (userId && secret) {
try {
await sdk.forConsole.account.updateVerification({ userId, secret });
addNotification({
message: 'Email verified successfully',
type: 'success'
});
await Promise.all([
invalidate(Dependencies.ACCOUNT),
invalidate(Dependencies.FACTORS)
Expand All @@ -59,21 +135,69 @@

onMount(() => {
updateEmailVerification();
restoreTimerState();
});

onDestroy(() => {
if (timerInterval) {
clearInterval(timerInterval);
}
// round up localstorage when component is destroyed
if (browser) {
localStorage.removeItem(TIMER_END_KEY);
localStorage.removeItem(EMAIL_SENT_KEY);
}
});
Comment on lines +141 to 150
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Don't clear localStorage on destroy; it defeats persistence of the resend timer.

Clearing TIMER_END_KEY/EMAIL_SENT_KEY in onDestroy breaks the “persist across reloads” goal and allows immediate resends after a refresh/navigation.

Apply this diff:

 onDestroy(() => {
     if (timerInterval) {
         clearInterval(timerInterval);
     }
-    // round up localstorage when component is destroyed
-    if (browser) {
-        localStorage.removeItem(TIMER_END_KEY);
-        localStorage.removeItem(EMAIL_SENT_KEY);
-    }
 });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
onDestroy(() => {
if (timerInterval) {
clearInterval(timerInterval);
}
// round up localstorage when component is destroyed
if (browser) {
localStorage.removeItem(TIMER_END_KEY);
localStorage.removeItem(EMAIL_SENT_KEY);
}
});
onDestroy(() => {
if (timerInterval) {
clearInterval(timerInterval);
}
});
🤖 Prompt for AI Agents
In src/lib/components/account/sendVerificationEmailModal.svelte around lines 146
to 155, the onDestroy handler currently clears TIMER_END_KEY and EMAIL_SENT_KEY
from localStorage which breaks persistence across navigations; remove the
localStorage.removeItem calls from onDestroy so the resend timer state is
preserved across reloads and navigations, leaving only the
clearInterval(timerInterval) logic; ensure any clearing of those keys happens
only when the timer naturally expires or when an explicit cancel/reset action
occurs (not on component destroy).

</script>

<Modal bind:show title="Send verification email" {onSubmit}>
<Card.Base variant="secondary" padding="s">
<Layout.Stack gap="m">
<Typography.Text gap="m">
To continue using Appwrite Cloud, please verify your email address. An email will be
sent to <Typography.Text variant="m-600" style="display: inline;"
>{get(user)?.email}</Typography.Text>
</Typography.Text>
</Layout.Stack>
</Card.Base>

<svelte:fragment slot="footer">
<Button submit disabled={creating}>{emailSent ? 'Resend email' : 'Send email'}</Button>
</svelte:fragment>
</Modal>
{#if shouldShowModal || show}
<div class="email-verification-scrim">
<Modal
show={true}
title="Verify your email address"
{onSubmit}
dismissible={false}
autoClose={false}>
<Card.Base variant="secondary" padding="s">
<Layout.Stack gap="s">
<Typography.Text gap="m">
To continue using Appwrite Cloud, please verify your email address. An email
will be sent to <Typography.Text
variant="m-600"
color="neutral-secondary"
style="display: inline;">{get(user)?.email}</Typography.Text>
</Typography.Text>
<Layout.Stack direction="row" gap="xxs">
<Link variant="default" on:click={() => logout(false)}>Switch account</Link>
</Layout.Stack>
{#if emailSent && resendTimer > 0}
<Typography.Text color="neutral-secondary">
Didn't get the email? Try again in {resendTimer}s
</Typography.Text>
{/if}
</Layout.Stack>
</Card.Base>

<svelte:fragment slot="footer">
<Button on:click={sendVerificationEmail} disabled={creating || resendTimer > 0}>
{emailSent ? 'Resend email' : 'Send email'}
</Button>
Comment on lines +182 to +184
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not button submit and use the onSubmit?

</svelte:fragment>
</Modal>
</div>
{/if}

<style>
.email-verification-scrim {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: hsl(240 5% 8% / 0.6);
backdrop-filter: blur(4px);
display: flex;
align-items: center;
justify-content: center;
}
</style>
36 changes: 0 additions & 36 deletions src/lib/components/alerts/emailVerificationBanner.svelte

This file was deleted.

1 change: 0 additions & 1 deletion src/lib/components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,5 +85,4 @@ export { default as ViewToggle } from './viewToggle.svelte';
export { default as RegionEndpoint } from './regionEndpoint.svelte';
export { default as ExpirationInput } from './expirationInput.svelte';
export { default as EstimatedCard } from './estimatedCard.svelte';
export { default as EmailVerificationBanner } from './alerts/emailVerificationBanner.svelte';
export { default as SortButton, type SortDirection } from './sortButton.svelte';
15 changes: 9 additions & 6 deletions src/routes/(console)/+layout.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@
import { headerAlert } from '$lib/stores/headerAlert';
import { UsageRates } from '$lib/components/billing';
import { canSeeProjects } from '$lib/stores/roles';
import { BottomModalAlert, EmailVerificationBanner } from '$lib/components';
import { BottomModalAlert } from '$lib/components';
import SendVerificationEmailModal from '$lib/components/account/sendVerificationEmailModal.svelte';
Comment on lines +48 to +49
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Duplicate verification modal renders on /console/verify-email

This layout always renders SendVerificationEmailModal, and the verify-email page also renders it. Results: double scrims, duplicate timers/listeners.

Apply this diff to suppress the layout modal on the verify-email route:

 <BottomModalAlert />
-<SendVerificationEmailModal />
+{#if !page.url.pathname.includes('/console/verify-email')}
+    <SendVerificationEmailModal />
+{/if}

Also applies to: 370-371

🤖 Prompt for AI Agents
In src/routes/(console)/+layout.svelte around lines 48-49 (and similarly at
lines 370-371), the layout unconditionally imports and renders
SendVerificationEmailModal causing duplicate modals on the /console/verify-email
page; change the layout to conditionally render that modal only when the current
route is not /console/verify-email by using the SvelteKit page store (or
$page.url.pathname) to check the pathname and wrap the modal import/render in
that condition so the modal is suppressed on the verify-email route.

import {
IconAnnotation,
IconBookOpen,
Expand Down Expand Up @@ -337,17 +338,18 @@
!page?.params.organization &&
!page.url.pathname.includes('/console/account') &&
!page.url.pathname.includes('/console/card') &&
!page.url.pathname.includes('/console/onboarding')}
showHeader={!page.url.pathname.includes('/console/onboarding/create-project')}
showFooter={!page.url.pathname.includes('/console/onboarding/create-project')}
!page.url.pathname.includes('/console/onboarding') &&
!page.url.pathname.includes('/console/verify-email')}
showHeader={!page.url.pathname.includes('/console/onboarding/create-project') &&
!page.url.pathname.includes('/console/verify-email')}
showFooter={!page.url.pathname.includes('/console/onboarding/create-project') &&
!page.url.pathname.includes('/console/verify-email')}
selectedProject={page.data?.project}>
<!-- <Header slot="header" />-->
<slot />
<Footer slot="footer" />
</Shell>

<EmailVerificationBanner />

{#if $wizard.show && $wizard.component}
<svelte:component this={$wizard.component} {...$wizard.props} />
{:else if $wizard.cover}
Expand All @@ -365,3 +367,4 @@
{/if}

<BottomModalAlert />
<SendVerificationEmailModal />
10 changes: 8 additions & 2 deletions src/routes/(console)/+layout.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import { Dependencies } from '$lib/constants';
import { sdk } from '$lib/stores/sdk';
import { isCloud } from '$lib/system';
import { redirect } from '@sveltejs/kit';
import { base } from '$app/paths';
import type { LayoutLoad } from './$types';
import type { Tier } from '$lib/stores/billing';
import type { Plan, PlanList } from '$lib/sdk/billing';
import { Query } from '@appwrite.io/console';

export const load: LayoutLoad = async ({ depends, parent }) => {
const { organizations } = await parent();
export const load: LayoutLoad = async ({ depends, parent, url }) => {
const { organizations, account } = await parent();

if (isCloud && !account.emailVerification && !url.pathname.includes('/verify-email')) {
redirect(303, `${base}/verify-email${url.search}`);
}

depends(Dependencies.RUNTIMES);
depends(Dependencies.CONSOLE_VARIABLES);
Expand Down
1 change: 1 addition & 0 deletions src/routes/(console)/onboarding/create-project/+page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export const load: PageLoad = async ({ parent }) => {
}
} catch (e) {
trackError(e, Submit.OrganizationCreate);
redirect(303, `${base}/create-organization`);
}
} else if (organizations?.total === 1) {
const org = organizations.teams[0];
Expand Down
5 changes: 5 additions & 0 deletions src/routes/(console)/verify-email/+layout.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<script lang="ts">
// verify email layout
</script>

<slot />
Loading