Files
classroomio/apps/dashboard/src/routes/invite/t/[hash]/+page.svelte
T

269 lines
7.7 KiB
Svelte
Raw Normal View History

<script lang="ts">
2025-11-01 15:49:29 +01:00
import { page } from '$app/state';
import { AuthUI } from '$features/ui';
import type { Profile } from '$lib/components/Course/components/People/types';
import { InputField } from '@cio/ui/custom/input-field';
import { Button } from '@cio/ui/base/button';
import * as Field from '@cio/ui/base/field';
import { Password } from '@cio/ui/custom/password';
import { SIGNUP_FIELDS } from '$lib/utils/constants/authentication';
import { logout } from '$lib/utils/functions/logout';
import { getSupabase } from '$lib/utils/functions/supabase';
import { setTheme } from '$lib/utils/functions/theme';
import { t } from '$lib/utils/functions/translations';
import { profile, user } from '$lib/utils/store/user';
2025-11-01 15:49:29 +01:00
import { authValidation, getConfirmPasswordError, getDisableSubmit } from '$lib/utils/functions/validator';
import { currentOrg, currentOrgPath } from '$lib/utils/store/org';
2025-11-01 15:49:29 +01:00
import { onMount, untrack } from 'svelte';
import { snackbar } from '$features/ui/snackbar/store';
2025-11-01 15:49:29 +01:00
let { data } = $props();
let supabase = getSupabase();
2025-11-01 15:49:29 +01:00
let fields = $state(Object.assign({}, SIGNUP_FIELDS));
let loading = $state(false);
let isLoggingOut = $state(false);
let shouldLogout = $state(false);
let errors: {
name?: string;
email?: string;
password?: string;
2025-11-01 15:49:29 +01:00
} = $state({});
2025-11-01 15:49:29 +01:00
let submitError: string = $state('');
const confirmPasswordError = $derived(getConfirmPasswordError(fields));
const disableSubmit = $derived(getDisableSubmit(fields));
async function joinOrg(profileId: string, email: string | null) {
if (!profileId || !email || !data.invite.currentOrg?.id) return;
// Update member response
const updateMemberRes = await supabase
.from('organizationmember')
.update({
verified: true,
profile_id: profileId
})
.match({ email: email, organization_id: data.invite.currentOrg?.id });
console.log('Update member response', updateMemberRes);
window.location.href = $currentOrgPath;
}
async function signUserIn(profileId: string, email: string) {
if (!profileId || !email) {
throw $t('login.validation.unable_to_create_profile');
}
const res = await supabase.auth.signInWithPassword({
email,
password: fields.password
});
if (res.error) {
throw res.error;
}
}
async function handleSubmit() {
if ($profile && $profile.id) {
loading = true;
await joinOrg($profile.id, $profile.email);
return;
}
const validationRes = authValidation({
...fields,
email: data.invite.email // validation for this ema
});
console.log('validationRes', validationRes);
if (Object.keys(validationRes).length) {
errors = Object.assign(errors, validationRes);
return;
}
try {
loading = true;
2024-09-17 14:24:37 +01:00
let profile: Profile | null = data.invite.profile;
2024-09-17 14:24:37 +01:00
if (!data.invite.profile) {
// Signup
const { data: signupData, error } = await supabase.auth.signUp({
2024-09-17 14:24:37 +01:00
email: data.invite.email,
password: fields.password
});
console.log('Signup', signupData);
if (error) throw error;
if (!signupData.user) {
throw $t('login.validation.user_cannot_be_created');
}
// Insert profile
const userId = signupData.user.id;
const profileRes = await supabase
.from('profile')
.insert({
id: userId,
username: fields.name.toLowerCase().replace(' ', '-') + new Date().getTime(),
fullname: fields.name,
2024-09-17 14:24:37 +01:00
email: data.invite.email
})
.select();
console.log('Insert profile', profileRes.data);
if (profileRes.error) {
throw profileRes.error;
}
profile = profileRes.data[0] || {};
}
if (!profile?.id) {
throw $t('login.validation.unable_to_create_profile');
}
await signUserIn(profile.id, profile.email);
await joinOrg(profile.id, profile.email);
} catch (error) {
if (error instanceof Error) {
submitError = error.message;
} else {
submitError = error?.toString() || '';
}
} finally {
loading = false;
}
}
2024-09-17 14:24:37 +01:00
onMount(async () => {
if (!data.invite.currentOrg) return;
2024-09-17 14:24:37 +01:00
setTheme(data.invite.currentOrg?.theme || '');
currentOrg.set(data.invite.currentOrg);
});
2025-11-01 15:49:29 +01:00
const isLoading = $derived(loading || $user.fetchingUser);
2025-11-01 15:49:29 +01:00
$effect(() => {
const email = $profile?.email;
2025-09-10 18:27:49 +01:00
if (!email) return;
if (email !== data.invite.email) {
console.log('logout');
snackbar.error('You are logged in with a different email');
2025-11-01 15:49:29 +01:00
untrack(() => {
shouldLogout = true;
});
2025-09-10 18:27:49 +01:00
}
2025-11-01 15:49:29 +01:00
});
</script>
<svelte:head>
<title>Join ClassroomIO</title>
</svelte:head>
<AuthUI redirectPathname={page.url.pathname} isLogin={false} {handleSubmit} {isLoading} showLogo={true}>
<div class="mt-4 w-full {shouldLogout ? 'hidden' : ''}">
<p class="mb-6 text-lg font-semibold dark:text-white">
2024-09-17 14:24:37 +01:00
{#if data.invite.profile}
{$t('login.login_to_join')}
{:else}
{$t('login.create_to_join')}
{/if}
</p>
<InputField
label={$t('login.fields.email')}
2024-09-17 14:24:37 +01:00
value={data.invite.email}
type="email"
placeholder="you@domain.com"
className="mb-6"
isDisabled={true}
/>
{#if $profile?.email !== data.invite.email}
{#if !data.invite.profile}
<InputField
label={$t('login.fields.full_name')}
bind:value={fields.name}
type="text"
autoFocus={true}
placeholder="e.g Joke Silva"
className="mb-6"
isDisabled={isLoading}
errorMessage={errors.name}
isRequired
/>
{/if}
<Field.Field class="mb-6">
<Field.Label for="password">{$t('login.fields.password')}</Field.Label>
<Field.Content>
<Password
id="password"
bind:value={fields.password}
placeholder="************"
disabled={isLoading}
aria-invalid={errors.password ? 'true' : undefined}
autocomplete={data.invite.profile ? 'current-password' : 'new-password'}
/>
{#if errors.password}
<Field.Error>{$t(errors.password)}</Field.Error>
{:else}
<Field.Description>{$t('login.fields.password_helper_message')}</Field.Description>
{/if}
</Field.Content>
</Field.Field>
{#if !data.invite.profile}
<Field.Field class="mb-6">
<Field.Label for="confirm-password">{$t('login.fields.confirm_password')}</Field.Label>
<Field.Content>
<Password
id="confirm-password"
bind:value={fields.confirmPassword}
placeholder="************"
disabled={isLoading}
aria-invalid={confirmPasswordError ? 'true' : undefined}
autocomplete="new-password"
/>
{#if confirmPasswordError}
<Field.Error>{$t(confirmPasswordError)}</Field.Error>
{/if}
</Field.Content>
</Field.Field>
{/if}
{/if}
{#if submitError}
<p class="text-sm text-red-500">{submitError}</p>
{/if}
</div>
<div class="my-4 flex w-full items-center justify-end">
{#if shouldLogout}
<Button
type="button"
loading={isLoggingOut}
variant="destructive"
onclick={async () => {
isLoggingOut = true;
await logout(false);
isLoggingOut = false;
shouldLogout = false;
}}
>
Logout
</Button>
{:else}
<Button type="submit" disabled={disableSubmit} loading={isLoading}>Accept Invite</Button>
{/if}
</div>
</AuthUI>