Files
classroomio/src/routes/+layout.svelte
T

376 lines
11 KiB
Svelte
Raw Normal View History

2020-12-24 20:32:05 +02:00
<script>
2021-07-31 23:06:14 +03:00
import { onMount } from 'svelte';
2021-09-11 19:27:11 +03:00
import { derived } from 'svelte/store';
import { goto } from '$app/navigation';
import { dev } from '$app/environment';
import { page, navigating } from '$app/stores';
import isEmpty from 'lodash/isEmpty';
2023-07-15 19:45:04 +00:00
import * as Sentry from '@sentry/browser';
import { Integrations } from '@sentry/tracing';
import { CaptureConsole } from '@sentry/integrations';
import { Theme } from 'carbon-components-svelte';
import { Moon } from 'svelte-loading-spinners';
import LandingNavigation from '$lib/components/Navigation/index.svelte';
import OrgNavigation from '$lib/components/Navigation/app.svelte';
import LMSNavigation from '$lib/components/Navigation/lms.svelte';
import OrgLandingPage from '$lib/components/Org/LandingPage/index.svelte';
import Snackbar from '$lib/components/Snackbar/index.svelte';
import Backdrop from '$lib/components/Backdrop/index.svelte';
import OrgSideBar from '$lib/components/Org/SideBar.svelte';
import LMSSideBar from '$lib/components/LMS/SideBar.svelte';
// import SideBar from "../components/SideBar/index.svelte";
// import Footer from '$lib/components/Footer/index.svelte';
import Apps from '$lib/components/Apps/index.svelte';
import PlayQuiz from '$lib/components/Org/Quiz/Play/index.svelte';
import { isCoursesPage, isOrgPage, isLMSPage, isQuizPage } from '$lib/utils/functions/app';
import showAppsSideBar from '$lib/utils/functions/showAppsSideBar';
import isPublicRoute from '$lib/utils/functions/routes/isPublicRoute';
import { user, profile } from '$lib/utils/store/user';
import { getSupabase } from '$lib/utils/functions/supabase';
import { isMobile } from '$lib/utils/store/useMobile';
import { ROUTES_TO_HIDE_NAV, ROUTE } from '$lib/utils/constants/routes';
import { getOrganizations, getCurrentOrg } from '$lib/utils/services/org';
import { toggleBodyByTheme } from '$lib/utils/functions/app';
import { appStore } from '$lib/utils/store/app';
import { currentOrg } from '$lib/utils/store/org';
import { blockedSubdomain } from '$lib/utils/constants/app';
2020-12-24 20:32:05 +02:00
import '../app.postcss';
let supabase = getSupabase();
let path = $page.url.pathname.replace('/', '');
let theme = 'white';
2023-06-17 19:11:29 +00:00
let skipAuth = false;
2021-07-31 23:06:14 +03:00
const delayedPreloading = derived(navigating, (currentPreloading, set) => {
2021-09-11 19:27:11 +03:00
setTimeout(() => set(currentPreloading), 250);
});
function setupSentry() {
if (!dev) {
Sentry.init({
dsn: 'https://c966f7e8cb1d4306be20b26bb4f0cc96@o476906.ingest.sentry.io/5999999',
integrations: [
new Integrations.BrowserTracing(),
new CaptureConsole({
levels: ['error']
})
],
environment: !dev ? 'production' : 'development',
// Set tracesSampleRate to 1.0 to capture 100%
// of transactions for performance monitoring.
// We recommend adjusting this value in production
tracesSampleRate: 1.0
});
}
}
2021-07-31 23:06:14 +03:00
async function getProfile() {
const params = new URLSearchParams(window.location.search);
2021-07-31 23:06:14 +03:00
// Get user profile
const {
data: { session }
} = await supabase.auth.getSession();
const { user: authUser } = session;
2022-11-30 09:18:41 +01:00
console.log('Get user profile', authUser);
2021-07-31 23:06:14 +03:00
// Check if user has profile
let {
data: profileData,
error,
status
} = await supabase.from('profile').select(`*`).eq('id', authUser?.id).single();
2021-07-31 23:06:14 +03:00
if (error && !profileData && status === 406 && authUser) {
2021-07-31 23:06:14 +03:00
// User wasn't found, create profile
2021-08-18 19:47:02 +03:00
console.log(`User wasn't found, create profile`);
2021-07-31 23:06:14 +03:00
const [regexUsernameMatch] = [...(authUser.email?.matchAll(/(.*)@/g) || [])];
2021-08-18 19:47:02 +03:00
const { data, error } = await supabase
.from('profile')
.insert({
id: authUser.id,
username: regexUsernameMatch[1] + '1669991321770',
fullname: regexUsernameMatch[1],
email: authUser.email
})
.select();
2021-07-31 23:06:14 +03:00
// Profile created, go to profile page
if (!error && data) {
2021-08-18 19:47:02 +03:00
$user.fetchingUser = false;
$user.isLoggedIn = true;
$user.currentSession = authUser;
profile.set(data[0]);
2021-10-22 14:55:33 +03:00
// Set user in sentry
2023-07-15 19:45:04 +00:00
Sentry.setUser($profile);
2022-12-03 22:45:01 +01:00
if ($appStore.isStudentDomain) {
const { data, error } = await supabase
.from('organizationmember')
.insert({
organization_id: $currentOrg.id,
profile_id: $profile.id,
role_id: 3
})
.select();
if (error) {
console.error('Error adding user to organisation', error);
} else {
console.log('Success adding user to organisation', data);
2023-05-20 23:53:28 +00:00
const memberId = data?.[0]?.id || '';
$currentOrg.memberId = memberId;
}
if (params.get('redirect')) {
goto(params.get('redirect') || '');
} else {
goto('/lms');
}
return;
}
2022-12-03 22:45:01 +01:00
goto(ROUTE.ONBOARDING);
2021-07-31 23:06:14 +03:00
}
2022-11-30 09:18:41 +01:00
$user.fetchingUser = false;
2021-07-31 23:06:14 +03:00
} else if (profileData) {
// Profile exists, go to profile page
2021-08-18 19:47:02 +03:00
$user.fetchingUser = false;
$user.isLoggedIn = true;
$user.currentSession = authUser;
2021-07-31 23:06:14 +03:00
profile.set(profileData);
2021-08-18 19:47:02 +03:00
2021-10-22 14:55:33 +03:00
// Set user in sentry
2023-07-15 19:45:04 +00:00
Sentry.setUser($profile);
2023-06-17 19:11:29 +00:00
const orgRes = await getOrganizations($profile.id);
2021-10-22 14:55:33 +03:00
// student redirect
if ($appStore.isStudentDomain) {
if (params.has('redirect')) {
goto(params.get('redirect') || '');
} else {
goto('/lms');
}
} else {
if (isEmpty(orgRes.orgs)) {
goto(ROUTE.ONBOARDING);
} else if (
2023-07-02 16:41:49 +01:00
['login', 'signup', 'onboarding'].some((r) => path.includes(r)) ||
path === '' // for home page
) {
// By default redirect to first organization
goto(`/org/${orgRes.currentOrg.siteName}`);
}
2021-08-18 19:47:02 +03:00
}
2021-07-31 23:06:14 +03:00
}
}
function setOrgBasedOnUrl(host) {
2023-05-13 07:16:32 +01:00
if (typeof window !== 'undefined') {
const debug = localStorage.getItem('role') === 'student';
const matches = host.match(/([a-z0-9]+).*classroomio[.]com/);
2023-05-16 16:30:30 +01:00
const subdomain = matches?.[1] ?? '';
2023-05-13 07:16:32 +01:00
2023-07-02 15:56:15 +01:00
if (!blockedSubdomain.includes(subdomain)) {
const answer = Array.isArray(matches) ? !!subdomain && subdomain !== 'www' : false;
2023-06-17 19:11:29 +00:00
2023-07-02 15:56:15 +01:00
$appStore.isStudentDomain = debug || answer;
$appStore.siteNameFromDomain = debug ? 'codingdojo' : subdomain;
2023-08-03 02:51:02 +01:00
} else if (subdomain === 'play' || debug) {
skipAuth = true;
2023-07-02 15:56:15 +01:00
}
2023-05-13 07:16:32 +01:00
}
}
2021-09-17 06:33:49 +03:00
function handleResize() {
isMobile.update(() => window.innerWidth <= 760);
}
2021-07-31 23:06:14 +03:00
onMount(() => {
2023-05-13 07:16:32 +01:00
console.log(
'Welcome to ClassroomIO, we are grateful you chose us.',
$page.url.host,
`\nIs student domain: ${$appStore.isStudentDomain}`
2023-05-13 07:16:32 +01:00
);
// Disable GA on localhost
if (dev) {
console.log('disable GA');
window['ga-disable-G-C7WBN0S06R'] = true;
}
setupSentry();
2021-09-17 06:33:49 +03:00
handleResize();
// if (
// !localStorage.getItem('supabase.auth.token') &&
// !isPublicRoute($page.url.pathname)
// ) {
// console.log(
// 'No auth token and is not a public route, redirect to login',
// path
// );
// return goto('/login');
// }
const { data: authListener } = supabase.auth.onAuthStateChange((event, session) => {
// Log key events
console.log(`event`, event);
if (event == 'PASSWORD_RECOVERY') {
console.log('PASSWORD RESET');
2021-07-31 23:06:14 +03:00
}
if (path.includes('reset')) {
console.log('Dont change auth when on reset page');
return;
}
// Skip Authentication
if (skipAuth) return;
// Authentication Steps
if (event === 'SIGNED_IN') {
$user.fetchingUser = true;
getProfile();
2023-08-03 02:51:02 +01:00
} else if (!['INITIAL_SESSION', 'TOKEN_REFRESHED'].includes(event)) {
console.log('not logged in, go to login');
return goto('/login');
}
});
2021-07-31 23:06:14 +03:00
// Update theme - dark or light mode
$appStore.isDark = localStorage.getItem('theme') === 'dark';
toggleBodyByTheme($appStore.isDark);
if ($appStore.isStudentDomain) {
getCurrentOrg($appStore.siteNameFromDomain);
}
2021-07-31 23:06:14 +03:00
return () => {
console.log('unsubscribed');
authListener?.unsubscribe();
2021-07-31 23:06:14 +03:00
};
});
$: path = $page.url.pathname.replace('/', '');
$: theme = $appStore.isDark ? 'g100' : 'white';
$: setOrgBasedOnUrl($page.url.host);
2020-12-24 20:32:05 +02:00
</script>
2021-09-17 06:33:49 +03:00
<svelte:window on:resize={handleResize} />
<svelte:head>
<link href="/css/carbon.css" rel="stylesheet" />
</svelte:head>
<Theme bind:theme />
2021-05-07 03:43:37 +03:00
2021-08-28 22:44:06 +03:00
<Snackbar />
2021-05-07 03:43:37 +03:00
2023-06-17 19:11:29 +00:00
{#if skipAuth}
<PlayQuiz />
{:else if $appStore.isStudentDomain && !path}
<OrgLandingPage />
{:else}
<main class="dark:bg-gray-800">
{#if $navigating && $delayedPreloading}
<Backdrop>
<Moon size="60" color="#1d4ed8" unit="px" duration="1s" />
</Backdrop>
{/if}
{#if !ROUTES_TO_HIDE_NAV.includes($page.url.pathname) && !isCoursesPage(path)}
{#if isOrgPage($page.url.pathname) || $page.url.pathname.includes('profile')}
<OrgNavigation />
{:else if isLMSPage($page.url.pathname)}
<LMSNavigation />
{:else}
<LandingNavigation
logo={$appStore.isStudentDomain ? $currentOrg.avatar_url : undefined}
orgName={$appStore.isStudentDomain ? $currentOrg.name : undefined}
disableLogin={false}
/>
{/if}
{/if}
2021-07-31 23:06:14 +03:00
<div class="flex justify-between">
{#if isOrgPage($page.url.pathname)}
<div class="org-root w-full flex items-center justify-between">
{#if !isQuizPage($page.url.pathname)}
2023-06-17 19:11:29 +00:00
<OrgSideBar />
{/if}
<div class="org-slot bg-white dark:bg-gray-800">
<slot />
</div>
</div>
{:else if isLMSPage($page.url.pathname)}
<div class="org-root w-full flex items-center justify-between">
<LMSSideBar />
<div class="org-slot bg-white dark:bg-gray-800">
<slot />
</div>
</div>
{:else}
<slot />
{/if}
2021-07-31 23:06:14 +03:00
{#if showAppsSideBar(path)}
<Apps />
{/if}
</div>
</main>
2021-05-07 03:43:37 +03:00
{#if !['about', ''].includes(path)}
<!-- <Footer /> -->
{/if}
2021-07-31 23:06:14 +03:00
{/if}
2021-05-07 03:43:37 +03:00
2020-12-24 20:32:05 +02:00
<style>
2020-12-30 22:29:01 +02:00
main {
2021-08-29 20:35:58 +03:00
background-color: #fafbfc;
2020-12-30 22:29:01 +02:00
box-sizing: border-box;
}
.org-root {
height: calc(100vh - 44px);
}
.org-slot {
2023-06-17 19:11:29 +00:00
min-width: calc(100vw - 250px);
height: calc(100vh - 44px);
overflow-y: auto;
}
2021-04-03 16:43:02 +03:00
:global(a:hover) {
text-decoration: underline;
}
2021-05-06 08:22:25 +03:00
:global(:root) {
2021-07-28 22:29:23 +03:00
--main-primary-color: rgba(29, 78, 216, 1);
2021-05-06 08:22:25 +03:00
--border-color: #eaecef;
2022-11-28 11:23:46 +01:00
--app-background-color: #fafbfc;
}
:global(.app-background-color) {
background-color: var(--app-background-color);
2021-05-06 08:22:25 +03:00
}
2023-04-23 22:28:18 +00:00
:global(.bx--data-table-container) {
width: 100%;
}
:global(.dark svg.dark path) {
fill: #fff;
}
:global(.border-c) {
border: 1px solid var(--border-color);
}
:global(.border-bottom-c) {
border-bottom: 1px solid var(--border-color);
}
2020-12-24 20:32:05 +02:00
</style>