feat: migrate auth from supabase to better auth (#596)

* feat: add README for @cio/db package and remove existingAccounts.json

* load session, load profile and organization, add create profile hook

* chore: cache session request

The trick was passing all the cookies to the backend. Previously I was only passing the better-auth.session_token and not better-auth.session_data. Read about the difference here https://www.better-auth.com/docs/concepts/cookies#custom-cookies

* feat: login, logout, onboarding, verify email, reset password.

* feat: complete change email and email verification

* feat: standardise how we make rpc calls and create org endpoints

* fix ui errors

* fix: handle potential undefined customerId and standardize avatar URL property

* refactor: standardize custom domain handling and update telegram chat ID references

* chore: add tailwind prefix to @cio/ui

this fixed the media query issues because  @cio/ui classes were overriding this dashboard tailwind build

* chore: clean up org sidebar

* chore: persist mode state

* feat: implement order breadcrumbs

* chore: upgrade to better auth 1.4

* chore: address common auth flow bugs and setup app for others to setup locally.
This commit is contained in:
Rotimi Best
2025-11-24 01:00:50 +01:00
committed by GitHub
parent 24741644d6
commit a3924100dd
567 changed files with 22364 additions and 13437 deletions
@@ -0,0 +1,162 @@
import { BaseApi, classroomio } from '$lib/utils/services/api';
import { currentOrg, isOrgStudent, orgs } from '$lib/utils/store/org';
import { defaultProfileState, defaultUserState, profile, user } from '$lib/utils/store/user';
import type { AccountResponse } from './types';
import type { TUser } from '@cio/db/types';
import { get } from 'svelte/store';
import { goto } from '$app/navigation';
import { handleLocaleChange } from '$lib/utils/functions/translations';
import { identifyPosthogUser } from '$lib/utils/services/posthog';
import { logout } from '$lib/utils/functions/logout';
import { page } from '$app/state';
import { resolve } from '$app/paths';
import { setSentryUser } from '$lib/utils/services/sentry';
import shouldRedirectOnAuth from '$lib/utils/functions/routes/shouldRedirectOnAuth';
type AppSetupParams = {
isOrgSite: boolean;
orgSiteName: string;
};
/*
Manages everything related to loading the logged in user and setting up the organization.
*/
class AppInitApi extends BaseApi {
data = $state<AccountResponse>(null);
session = $state<App.Locals | null>(null);
get loading() {
return this.isLoading;
}
async setupApp(locals: App.Locals, params: AppSetupParams): Promise<boolean | undefined> {
if (!locals.user) {
console.log('No user found in locals');
return;
}
this.session = locals;
await this.execute<typeof classroomio.account.$get>({
requestFn: () => classroomio.account.$get(),
logContext: 'fetching account',
onSuccess: (accountData) => {
this.data = accountData;
this.setupStores();
this.setUserAnalytics();
this.routeUserToNextPage(params);
},
onError: () => {
logout();
}
});
}
/*
1. Update user store
2. Update profile store
3. Update organizations store
*/
setupStores() {
if (!this.data?.success || !this.session) {
return;
}
user.update((_user) => ({
..._user,
fetchingUser: false,
isLoggedIn: true,
currentSession: (this.session?.user as unknown as TUser) || undefined
}));
profile.set(this.data.profile);
handleLocaleChange(this.data.profile.locale ?? 'en');
this.setOrgStore();
}
setOrgStore() {
if (!this.data?.success || !this.data) {
return;
}
if (!this.data.organizations.length) {
return;
}
orgs.set(this.data.organizations);
const lastOrgSiteName = localStorage.getItem('classroomio_org_sitename');
const lastOrg = this.data.organizations.find((org) => org.siteName === lastOrgSiteName);
currentOrg.set(lastOrg || this.data.organizations[0]);
}
routeUserToNextPage({ isOrgSite }: AppSetupParams) {
if (!this.data?.success) {
return;
}
const userHasOrganizations = this.data.organizations.length > 0;
const shouldRedirectToOnboarding = !isOrgSite && !userHasOrganizations;
if (shouldRedirectToOnboarding) {
return goto(resolve(`/onboarding`, {}));
}
const redirect = page.url.searchParams.get('redirect');
if (redirect) {
// goto redirect won't accept dynamic url so we need to use window.location.href
window.location.href = redirect;
return;
}
if (!shouldRedirectOnAuth(page.url.pathname)) return;
const isStudent = get(isOrgStudent);
return isOrgSite || isStudent ? this.goToLMS() : this.goToOrg();
}
goToLMS() {
goto(resolve('/lms', {}));
}
goToOrg() {
const selectedOrg = get(currentOrg);
goto(resolve(`/org/${selectedOrg.siteName}`, {}));
}
setUserAnalytics() {
const profileStore = get(profile);
if (!profileStore?.id) return;
setSentryUser({
id: profileStore.id,
username: profileStore.username,
email: profileStore.email,
fullname: profileStore.fullname
});
identifyPosthogUser(profileStore.id, {
email: profileStore.email,
name: profileStore.fullname
});
}
reset() {
super.reset();
this.data = null;
user.set(defaultUserState);
profile.set(defaultProfileState);
}
get isInitializedAndReady() {
return !this.isLoading && !this.error && this.data !== null;
}
}
export const appInitApi = new AppInitApi();
@@ -0,0 +1,120 @@
import type { Cookies } from '@sveltejs/kit';
import type { CurrentOrg } from '$lib/utils/types/org';
import { PUBLIC_IS_SELFHOSTED } from '$env/static/public';
import { blockedSubdomain } from '$lib/utils/constants/app';
import { env } from '$env/dynamic/private';
import { getCurrentOrg } from '$lib/utils/services/org';
export interface OrgSiteInfo {
isOrgSite: boolean;
org: CurrentOrg | null;
subdomain: string;
orgSiteName: string;
}
export async function getOrgSiteInfo(url: URL, cookies: Cookies): Promise<OrgSiteInfo> {
const response: OrgSiteInfo = {
orgSiteName: '',
subdomain: '',
isOrgSite: false,
org: null
};
// Selfhosted usecase
if (PUBLIC_IS_SELFHOSTED === 'true') {
const subdomain = getSubdomain(url);
// Student dashboard
if (subdomain) {
const org = (await getCurrentOrg(subdomain, true)) || null;
// Organization by subdomain not found
if (!org) {
return response;
}
response.org = org;
response.isOrgSite = true;
response.orgSiteName = subdomain;
response.subdomain = subdomain;
}
// Never go beyond this for selfhosted instances
return response;
}
const isLocalHost = url.host.includes('localhost');
const tempSiteName = url.searchParams.get('org');
if (isLocalHost && tempSiteName) {
cookies.set('_orgSiteName', tempSiteName, {
path: '/'
});
}
const _orgSiteName = cookies.get('_orgSiteName');
const debugMode = _orgSiteName && _orgSiteName !== 'false';
const subdomain = getSubdomain(url) || '';
// Custom domain
if (isURLCustomDomain(url)) {
response.org = (await getCurrentOrg(url.host, true, true)) || null;
if (!response.org) {
return response;
}
response.isOrgSite = true;
response.orgSiteName = response.org?.siteName || '';
response.subdomain = subdomain;
return response;
}
// Subdomain except blocked ones.
if (!blockedSubdomain.includes(subdomain)) {
const APP_SUBDOMAINS = env.PRIVATE_APP_SUBDOMAINS?.split(',') || [];
if (APP_SUBDOMAINS.includes(subdomain)) {
return response;
}
response.isOrgSite = debugMode || !!subdomain;
response.orgSiteName = debugMode ? _orgSiteName : subdomain;
response.org = (await getCurrentOrg(response.orgSiteName, true)) || null;
const shouldDeleteCookie = !response.org && _orgSiteName;
if (shouldDeleteCookie) {
cookies.delete('_orgSiteName', { path: '/' });
}
}
return response;
}
function isURLCustomDomain(url: URL) {
if (url.host.includes('localhost')) {
return false;
}
const notCustomDomainHosts = [env.PRIVATE_APP_HOST || '', 'classroomio.com', 'vercel.app'].filter(Boolean);
return !notCustomDomainHosts.some((host) => url.host.endsWith(host));
}
export function getSubdomain(url: URL) {
const host = url.hostname.replace('www.', '');
const parts = host.split('.');
const appHost = env.PRIVATE_APP_HOST;
const appHostParts = appHost.split('.');
const isAppHost = parts.slice(-appHostParts.length).join('.') === appHost;
if (isAppHost) {
// Subdomain exists only if extra part(s) before main domain
return parts.length > appHostParts.length ? parts[0] : null;
}
return null;
}
@@ -0,0 +1,7 @@
import { classroomio, type InferResponseType } from '$lib/utils/services/api';
export type AccountResponse = InferResponseType<typeof classroomio.account.$get> | null;
export type AccountSuccess = Extract<InferResponseType<typeof classroomio.account.$get>, { success: true }>;
export type AccountOrg = AccountSuccess['organizations'][number];