fix: auth flow bug on joining course

This commit is contained in:
Rotimi Best
2023-12-05 08:31:26 +03:00
parent 8fc3a5e1fc
commit 6fa1d0fcfb
12 changed files with 69 additions and 86 deletions
@@ -47,9 +47,11 @@
height="h-10" height="h-10"
className="mr-2" className="mr-2"
/> />
<h4 class="dark:text-white text-xl mt-0"> <a href="/">
{$currentOrg.name ? $currentOrg.name : 'ClassroomIO'} <h4 class="dark:text-white text-xl mt-0">
</h4> {$currentOrg.name ? $currentOrg.name : 'ClassroomIO'}
</h4>
</a>
</div> </div>
{/if} {/if}
<form <form
@@ -5,25 +5,17 @@
import { VARIANTS } from '$lib/components/PrimaryButton/constants'; import { VARIANTS } from '$lib/components/PrimaryButton/constants';
import { supabase } from '$lib/utils/functions/supabase'; import { supabase } from '$lib/utils/functions/supabase';
import { capturePosthogEvent } from '$lib/utils/services/posthog'; import { capturePosthogEvent } from '$lib/utils/services/posthog';
import { currentOrg, orgs } from '$lib/utils/store/org'; import { currentOrg, orgs, defaultCurrentOrgState } from '$lib/utils/store/org';
import { user, profile, defaultProfileState, defaultUserState } from '$lib/utils/store/user';
async function logout() { async function logout() {
const { error } = await supabase.auth.signOut(); const { error } = await supabase.auth.signOut();
console.error('Error logging out: ', error); console.error('Error logging out: ', error);
// Reset organization values, TODO: consider abstracting if needed in other places currentOrg.set(defaultCurrentOrgState);
currentOrg.set({ orgs.set([]);
id: '', user.set(defaultUserState);
name: '', profile.set(defaultProfileState);
shortName: '',
siteName: '',
avatar_url: '',
memberId: '',
role_id: '',
landingpage: {},
theme: ''
})
orgs.set([]);
capturePosthogEvent('user_logged_out'); capturePosthogEvent('user_logged_out');
posthog.reset(); posthog.reset();
@@ -5,6 +5,7 @@
import ChevronRightIcon from 'carbon-icons-svelte/lib/ChevronRight.svelte'; import ChevronRightIcon from 'carbon-icons-svelte/lib/ChevronRight.svelte';
import ArrowLeftIcon from 'carbon-icons-svelte/lib/ArrowLeft.svelte'; import ArrowLeftIcon from 'carbon-icons-svelte/lib/ArrowLeft.svelte';
import ArrowUpRightIcon from 'carbon-icons-svelte/lib/ArrowUpRight.svelte'; import ArrowUpRightIcon from 'carbon-icons-svelte/lib/ArrowUpRight.svelte';
import { currentOrgDomain } from '$lib/utils/store/org';
import IconButton from '$lib/components/IconButton/index.svelte'; import IconButton from '$lib/components/IconButton/index.svelte';
import CloseButton from '$lib/components/Buttons/Close/index.svelte'; import CloseButton from '$lib/components/Buttons/Close/index.svelte';
@@ -128,12 +129,9 @@
loading = false; loading = false;
syncCourseStore(course); syncCourseStore(course);
} }
/**
* 1. Use all you have for editing now
* 2. Make course one interface we might need to computation
*/
async function handlePreview() { async function handlePreview() {
const link = `${window.location.origin}/course/${course.slug}`; const link = `${$currentOrgDomain}/course/${course.slug}`;
window.open(link, '_blank'); window.open(link, '_blank');
} }
</script> </script>
@@ -4,7 +4,7 @@
import getCurrencyFormatter from '$lib/utils/functions/getCurrencyFormatter'; import getCurrencyFormatter from '$lib/utils/functions/getCurrencyFormatter';
import { isCourseFree } from '$lib/utils/functions/course'; import { isCourseFree } from '$lib/utils/functions/course';
import { getStudentInviteLink } from '$lib/utils/functions/course'; import { getStudentInviteLink } from '$lib/utils/functions/course';
import { currentOrg } from '$lib/utils/store/org'; import { currentOrg, currentOrgDomain } from '$lib/utils/store/org';
import { goto } from '$app/navigation'; import { goto } from '$app/navigation';
import PaymentModal from './PaymentModal.svelte'; import PaymentModal from './PaymentModal.svelte';
import type { Course } from '$lib/utils/types'; import type { Course } from '$lib/utils/types';
@@ -17,6 +17,7 @@
export let startCoursePayment = false; export let startCoursePayment = false;
export let mobile = false; export let mobile = false;
let openModal = false;
let calculatedCost = 0; let calculatedCost = 0;
let discount = 0; let discount = 0;
let formatter: Intl.NumberFormat | undefined; let formatter: Intl.NumberFormat | undefined;
@@ -39,11 +40,13 @@
course_free: isFree course_free: isFree
}); });
if (isFree) { if (isFree) {
const link = getStudentInviteLink(courseData, $currentOrg.siteName); const link = getStudentInviteLink(courseData, $currentOrg.siteName, $currentOrgDomain);
goto(link); goto(link);
} else { } else {
startCoursePayment = true; openModal = true;
} }
startCoursePayment = false;
} }
function setFormatter(currency: string | undefined) { function setFormatter(currency: string | undefined) {
@@ -62,10 +65,11 @@
$: discount = get(courseData, 'metadata.discount', 0); $: discount = get(courseData, 'metadata.discount', 0);
$: calculatedCost = calcDisc(discount, courseData.cost || 0, !!courseData.metadata.showDiscount); $: calculatedCost = calcDisc(discount, courseData.cost || 0, !!courseData.metadata.showDiscount);
$: isFree = isCourseFree(calculatedCost); $: isFree = isCourseFree(calculatedCost);
$: startCoursePayment && handleJoinCourse();
</script> </script>
<PaymentModal <PaymentModal
bind:open={startCoursePayment} bind:open={openModal}
paymentLink={get(courseData, 'metadata.paymentLink', '')} paymentLink={get(courseData, 'metadata.paymentLink', '')}
courseName={courseData.title} courseName={courseData.title}
teacherEmail={getTeacherEmail(courseData.group)} teacherEmail={getTeacherEmail(courseData.group)}
@@ -66,8 +66,10 @@
height="h-20" height="h-20"
/> />
<div class="mt-5"> <div class="mt-5 flex justify-center w-full">
<p class="dark:text-white text-lg font-bold whitespace-nowrap truncate"> <p
class="dark:text-white text-lg font-bold whitespace-nowrap truncate max-w-[80%] text-center"
>
{$profile.fullname} {$profile.fullname}
</p> </p>
</div> </div>
@@ -3,7 +3,7 @@ import type { Course } from '../types';
export const isCourseFree = (cost: number) => !(Number(cost) > 0); export const isCourseFree = (cost: number) => !(Number(cost) > 0);
export const getStudentInviteLink = (_course: Course, orgSiteName: string) => { export const getStudentInviteLink = (_course: Course, orgSiteName: string, origin: string) => {
const hash = encodeURIComponent( const hash = encodeURIComponent(
btoa( btoa(
JSON.stringify({ JSON.stringify({
@@ -15,7 +15,7 @@ export const getStudentInviteLink = (_course: Course, orgSiteName: string) => {
) )
); );
return `https://${orgSiteName}.classroomio.com/invite/s/${hash}`; return `${origin}/invite/s/${hash}`;
}; };
export const getTextFromHTML = (html: string): string => { export const getTextFromHTML = (html: string): string => {
@@ -27,7 +27,7 @@ export const getTextFromHTML = (html: string): string => {
return dummyDiv.textContent?.trim() || ''; return dummyDiv.textContent?.trim() || '';
}; };
const tagsToReplace = { const tagsToReplace: { [k: string]: string } = {
'&': '&amp;', '&': '&amp;',
'<': '&lt;', '<': '&lt;',
'>': '&gt;' '>': '&gt;'
+5 -3
View File
@@ -6,8 +6,7 @@ import type { CurrentOrg, OrgTeamMember, OrgAudience } from '../types/org';
import { ROLE } from '$lib/utils/constants/roles'; import { ROLE } from '$lib/utils/constants/roles';
import type { UserLessonDataType } from '$lib/utils/types'; import type { UserLessonDataType } from '$lib/utils/types';
export const orgs = writable<CurrentOrg[]>([]); export const defaultCurrentOrgState: CurrentOrg = {
export const currentOrg: Writable<CurrentOrg> = writable({
id: '', id: '',
name: '', name: '',
shortName: '', shortName: '',
@@ -17,7 +16,10 @@ export const currentOrg: Writable<CurrentOrg> = writable({
role_id: '', role_id: '',
landingpage: {}, landingpage: {},
theme: '' theme: ''
}); };
export const orgs = writable<CurrentOrg[]>([]);
export const currentOrg: Writable<CurrentOrg> = writable(defaultCurrentOrgState);
export const orgAudience = writable<OrgAudience[]>([]); export const orgAudience = writable<OrgAudience[]>([]);
export const orgTeam = writable<OrgTeamMember[]>([]); export const orgTeam = writable<OrgTeamMember[]>([]);
export const isOrgAdmin = derived( export const isOrgAdmin = derived(
+19 -11
View File
@@ -1,21 +1,15 @@
import { writable } from 'svelte/store'; import { writable } from 'svelte/store';
import type { User } from '@supabase/supabase-js'; import type { User } from '@supabase/supabase-js';
export const user = writable<{ interface UserStore {
openAuthModal: boolean; openAuthModal: boolean;
fetchingUser: boolean; fetchingUser: boolean;
isLoggedIn: boolean; isLoggedIn: boolean;
currentSession: User | undefined; currentSession: User | undefined;
expiresAt: number; expiresAt: number;
}>({ }
openAuthModal: false,
fetchingUser: false,
isLoggedIn: false,
currentSession: undefined,
expiresAt: 0
});
export const profile = writable<{ interface ProfileStore {
id: string | undefined; id: string | undefined;
fullname: string; fullname: string;
avatar_url: string; avatar_url: string;
@@ -27,7 +21,17 @@ export const profile = writable<{
goal: string; goal: string;
source: string; source: string;
telegram_chat_id: number | null; telegram_chat_id: number | null;
}>({ }
export const defaultUserState: UserStore = {
openAuthModal: false,
fetchingUser: false,
isLoggedIn: false,
currentSession: undefined,
expiresAt: 0
};
export const defaultProfileState: ProfileStore = {
id: undefined, id: undefined,
fullname: '', fullname: '',
avatar_url: 'https://pbs.twimg.com/profile_images/1416443682157473795/dGtFbtht_normal.jpg', avatar_url: 'https://pbs.twimg.com/profile_images/1416443682157473795/dGtFbtht_normal.jpg',
@@ -38,4 +42,8 @@ export const profile = writable<{
goal: '', goal: '',
source: '', source: '',
telegram_chat_id: null telegram_chat_id: null
}); };
export const user = writable<UserStore>(defaultUserState);
export const profile = writable<ProfileStore>(defaultProfileState);
+5 -5
View File
@@ -80,8 +80,8 @@
const { user: authUser } = session || {}; const { user: authUser } = session || {};
console.log('Get user', authUser); console.log('Get user', authUser);
if (!authUser) { if (!authUser && !isPublicRoute($page.url.pathname)) {
goto('/login?redirect=/' + path); return goto('/login?redirect=/' + path);
} }
// Check if user has profile // Check if user has profile
@@ -185,7 +185,7 @@
} }
} }
if (!profileData) { if (!profileData && !isPublicRoute($page.url.pathname)) {
goto('/login?redirect=/' + path); goto('/login?redirect=/' + path);
} }
} }
@@ -239,10 +239,10 @@
if (data.skipAuth) return; if (data.skipAuth) return;
// Authentication Steps // Authentication Steps
if (event === 'SIGNED_IN') { if (event === 'SIGNED_IN' || event === 'INITIAL_SESSION') {
$user.fetchingUser = true; $user.fetchingUser = true;
getProfile(); getProfile();
} else if (!['INITIAL_SESSION', 'TOKEN_REFRESHED'].includes(event)) { } else if (!['TOKEN_REFRESHED'].includes(event)) {
console.log('not logged in, go to login'); console.log('not logged in, go to login');
return goto('/login'); return goto('/login');
} }
@@ -16,12 +16,12 @@
} from '$lib/utils/services/notification/notification'; } from '$lib/utils/services/notification/notification';
import { snackbar } from '$lib/components/Snackbar/store.js'; import { snackbar } from '$lib/components/Snackbar/store.js';
import { capturePosthogEvent } from '$lib/utils/services/posthog'; import { capturePosthogEvent } from '$lib/utils/services/posthog';
import { page } from '$app/stores';
export let data; export let data;
let supabase = getSupabase(); let supabase = getSupabase();
let loading = false; let loading = false;
let refresh = false;
let disableSubmit = false; let disableSubmit = false;
let formRef: HTMLFormElement; let formRef: HTMLFormElement;
@@ -29,16 +29,9 @@
async function handleSubmit() { async function handleSubmit() {
loading = true; loading = true;
if (refresh) {
window.location.reload();
refresh = false;
return;
}
if (!$profile.id || !$profile.email) { if (!$profile.id || !$profile.email) {
console.log('Profile not found', $profile); console.log('Profile not found', $profile);
refresh = true; return goto(`/signup?redirect=${$page.url?.pathname || ''}`);
return;
} }
const member = { const member = {
@@ -124,19 +117,13 @@
bind:formRef bind:formRef
> >
<div class="mt-0 w-full"> <div class="mt-0 w-full">
{#if refresh} <h3 class="dark:text-white text-lg font-medium mt-0 mb-4 text-center">{data.name}</h3>
<p class="dark:text-white text-sm font-light text-center"> <p class="dark:text-white text-sm font-light text-center">{data.description}</p>
Something went wrong, please try again.
</p>
{:else}
<h3 class="dark:text-white text-lg font-medium mt-0 mb-4 text-center">{data.name}</h3>
<p class="dark:text-white text-sm font-light text-center">{data.description}</p>
{/if}
</div> </div>
<div class="my-4 w-full flex justify-center items-center"> <div class="my-4 w-full flex justify-center items-center">
<PrimaryButton <PrimaryButton
label={refresh ? 'Try again' : 'Join Course'} label="Join Course"
type="submit" type="submit"
isDisabled={disableSubmit || loading} isDisabled={disableSubmit || loading}
isLoading={loading} isLoading={loading}
+4 -4
View File
@@ -13,7 +13,7 @@
let hasFetched = false; let hasFetched = false;
let progressPercentage = 0; let progressPercentage = 0;
let totalLessons = 0; let totalLessons = 0;
let totalComPleted = 0; let totalCompleted = 0;
async function getCourses(userId: string | undefined, orgId: string) { async function getCourses(userId: string | undefined, orgId: string) {
if (hasFetched || !userId || !orgId) { if (hasFetched || !userId || !orgId) {
@@ -32,10 +32,10 @@
} }
function calcTotalProgress(courses: Course[]) { function calcTotalProgress(courses: Course[]) {
totalComPleted = courses.reduce((acc, cur) => acc + (cur.progress_rate || 0), 0); totalCompleted = courses.reduce((acc, cur) => acc + (cur.progress_rate || 0), 0);
totalLessons = courses.reduce((acc, cur) => acc + (cur.total_lessons || 0), 0); totalLessons = courses.reduce((acc, cur) => acc + (cur.total_lessons || 0), 0);
progressPercentage = Math.round((totalComPleted / totalLessons) * 100); progressPercentage = Math.round((totalCompleted / totalLessons) * 100) || 0;
} }
$: getCourses($profile.id, $currentOrg.id); $: getCourses($profile.id, $currentOrg.id);
@@ -93,7 +93,7 @@
</p> </p>
{#if totalLessons > 0} {#if totalLessons > 0}
<p class="text-xs font-normal text-[#656565] dark:text-white"> <p class="text-xs font-normal text-[#656565] dark:text-white">
{totalComPleted}/{totalLessons} lessons completed {totalCompleted}/{totalLessons} lessons completed
</p> </p>
{:else} {:else}
<p class="text-xs font-normal text-[#656565] dark:text-white">No courses started</p> <p class="text-xs font-normal text-[#656565] dark:text-white">No courses started</p>
+2 -14
View File
@@ -7,16 +7,14 @@
import { LOGIN_FIELDS } from '$lib/utils/constants/authentication'; import { LOGIN_FIELDS } from '$lib/utils/constants/authentication';
import AuthUI from '$lib/components/AuthUI/index.svelte'; import AuthUI from '$lib/components/AuthUI/index.svelte';
import { currentOrg } from '$lib/utils/store/org'; import { currentOrg } from '$lib/utils/store/org';
import { onDestroy } from 'svelte';
import { capturePosthogEvent } from '$lib/utils/services/posthog'; import { capturePosthogEvent } from '$lib/utils/services/posthog';
let formRef; let formRef: HTMLFormElement;
let supabase = getSupabase(); let supabase = getSupabase();
let fields = Object.assign({}, LOGIN_FIELDS); let fields = Object.assign({}, LOGIN_FIELDS);
let submitError: string; let submitError: string;
let loading = false; let loading = false;
let errors = {}; let errors = Object.assign({}, LOGIN_FIELDS);
// let reloadTimeout: NodeJS.Timeout;
let query = new URLSearchParams($page.url.search); let query = new URLSearchParams($page.url.search);
let redirect = query.get('redirect'); let redirect = query.get('redirect');
@@ -39,12 +37,6 @@
console.log('data', data); console.log('data', data);
if (error) throw error; if (error) throw error;
// reload page on org site cause for some reason the authlistener on +layout.svelte doesn't run sometimes
// reloadTimeout = setTimeout(() => {
// console.log('Forcing full page reload for auth listener');
// window.location.reload();
// }, 1500);
capturePosthogEvent('login', { capturePosthogEvent('login', {
email: fields.email email: fields.email
}); });
@@ -54,10 +46,6 @@
loading = false; loading = false;
} }
} }
// onDestroy(() => {
// clearTimeout(reloadTimeout);
// });
</script> </script>
<svelte:head> <svelte:head>