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:
@@ -0,0 +1,141 @@
|
||||
import { getErrMsg } from './utils';
|
||||
import type { InferResponseType } from '@cio/api/rpc-types';
|
||||
import { ApiError, type ZodValidationError, type ZodValidatorMesssage } from './types';
|
||||
import { mapZodErrorsToTranslations } from '$lib/utils/validation/validation';
|
||||
import { ZodError } from 'zod/v4';
|
||||
|
||||
// Extract the data type from a success response
|
||||
type ExtractData<T> = Extract<InferResponseType<T>, { success: true }>;
|
||||
type ExtractError<T> = Extract<InferResponseType<T>, { success: false }>;
|
||||
|
||||
interface ExecuteOptions<TrpcType> {
|
||||
requestFn: () => Promise<Response>;
|
||||
errorMessage?: string;
|
||||
onSuccess?: (data: ExtractData<TrpcType>) => Promise<void> | void;
|
||||
onError?: (error: ExtractError<TrpcType> | string) => Promise<void> | void;
|
||||
logContext?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Base API class that provides shared state management and request handling
|
||||
* for all API classes in the application.
|
||||
*/
|
||||
export class BaseApi {
|
||||
isLoading = $state(false);
|
||||
error = $state<string | null>(null);
|
||||
|
||||
/**
|
||||
* Execute an API request with automatic loading and error state management
|
||||
* Type is automatically inferred from the RPC call (e.g., classroomio.organization.plan.$post)
|
||||
* @param options Configuration for the request
|
||||
* @returns The data from the response, or the default return value on error
|
||||
*/
|
||||
protected async execute<TrpcType>(options: ExecuteOptions<TrpcType>): Promise<ExtractData<TrpcType> | undefined> {
|
||||
const { requestFn, onSuccess, logContext = 'API request' } = options;
|
||||
|
||||
this.isLoading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const response = await requestFn();
|
||||
const result = (await response.json()) as unknown;
|
||||
|
||||
if (typeof result === 'object' && result !== null && 'success' in result) {
|
||||
const apiResult = result as { success: boolean; data?: unknown; error?: string; message?: string };
|
||||
|
||||
if (apiResult.success === false) {
|
||||
console.log('apiResult false', apiResult);
|
||||
options.onError?.(apiResult as ExtractError<TrpcType>);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const typedResult = apiResult as ExtractData<TrpcType>;
|
||||
|
||||
this.resetErrors();
|
||||
|
||||
if (onSuccess) {
|
||||
await onSuccess(typedResult);
|
||||
}
|
||||
|
||||
return typedResult;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error in ${logContext}:`, error);
|
||||
this.error = getErrMsg(error, `Error ${logContext}:`);
|
||||
|
||||
const errorResult = this.getServerError<ExtractError<TrpcType>>(error);
|
||||
options.onError?.(errorResult);
|
||||
} finally {
|
||||
this.isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
getServerError<T>(error: unknown): T | string {
|
||||
if (error instanceof ApiError) {
|
||||
console.log('instance of ApiError', error);
|
||||
try {
|
||||
const json = JSON.parse(error.message) as T;
|
||||
return json;
|
||||
} catch (e) {
|
||||
console.log('error parsing json', e);
|
||||
return error.message;
|
||||
}
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
|
||||
if (typeof error === 'string') {
|
||||
return error;
|
||||
}
|
||||
|
||||
return `${error}`;
|
||||
}
|
||||
|
||||
resetErrors() {
|
||||
this.error = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset the API state
|
||||
*/
|
||||
reset() {
|
||||
this.isLoading = false;
|
||||
this.error = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extended base API class that supports errors object (Record<string, string>)
|
||||
* for form validation scenarios
|
||||
*/
|
||||
export class BaseApiWithErrors extends BaseApi {
|
||||
errors = $state<Record<string, string>>({});
|
||||
success = $state(false);
|
||||
|
||||
handleValidationError(result: { success: false; error: string; code: string; field?: string }): Promise<void> | void {
|
||||
const zodValidationError = result.error as unknown as ZodValidationError;
|
||||
if (zodValidationError.name === 'ZodError') {
|
||||
const issues = JSON.parse(zodValidationError.message) as ZodValidatorMesssage;
|
||||
|
||||
this.errors = mapZodErrorsToTranslations(new ZodError(issues));
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
override resetErrors() {
|
||||
this.errors = {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset the API state including errors and success
|
||||
*/
|
||||
override reset() {
|
||||
super.reset();
|
||||
this.errors = {};
|
||||
this.success = false;
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ import { type ApiClientConfig, ApiError, type RequestConfig } from './types';
|
||||
import { DEFAULT_CONFIG } from './constants';
|
||||
import { delay } from './utils';
|
||||
import { env } from '$env/dynamic/public';
|
||||
import { getAccessToken } from '$lib/utils/functions/supabase';
|
||||
import { hcWithType } from '@cio/api/rpc-types';
|
||||
|
||||
class ApiClient {
|
||||
@@ -14,13 +13,7 @@ class ApiClient {
|
||||
}
|
||||
|
||||
private async makeRequest(input: RequestInfo | URL, requestConfig: RequestConfig = {}): Promise<Response> {
|
||||
console.log('makeRequest', input, requestConfig);
|
||||
const {
|
||||
timeout = this.config.timeout,
|
||||
retries = this.config.retries,
|
||||
skipAuth = false,
|
||||
...fetchConfig
|
||||
} = requestConfig;
|
||||
const { timeout = this.config.timeout, retries = this.config.retries, ...fetchConfig } = requestConfig;
|
||||
|
||||
const url = typeof input === 'string' ? input : input.toString();
|
||||
const fullUrl = url.startsWith('http') ? url : `${this.config.baseURL}${url}`;
|
||||
@@ -48,19 +41,6 @@ class ApiClient {
|
||||
}
|
||||
}
|
||||
|
||||
// Add authentication if not skipped
|
||||
if (!skipAuth) {
|
||||
try {
|
||||
const token = await getAccessToken();
|
||||
if (token) {
|
||||
headers.set('Authorization', `Bearer ${token}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to get access token:', error);
|
||||
// Continue without auth if token retrieval fails
|
||||
}
|
||||
}
|
||||
|
||||
// Create abort controller for timeout
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
||||
@@ -94,16 +74,11 @@ class ApiClient {
|
||||
|
||||
if (response.status >= 400 && response.status < 500) {
|
||||
const errorText = await response.text().catch(() => 'Unknown error');
|
||||
throw new ApiError(`Client error: ${errorText}`, response.status, response.statusText, response);
|
||||
throw new ApiError(errorText, response.status, response.statusText, response);
|
||||
}
|
||||
|
||||
if (response.status >= 500) {
|
||||
const error = new ApiError(
|
||||
`Server error: ${response.statusText}`,
|
||||
response.status,
|
||||
response.statusText,
|
||||
response
|
||||
);
|
||||
const error = new ApiError(response.statusText, response.status, response.statusText, response);
|
||||
|
||||
if (attempt === retries) {
|
||||
throw error;
|
||||
@@ -165,6 +140,9 @@ export const apiClient = new ApiClient();
|
||||
export const classroomio = hcWithType(env.PUBLIC_SERVER_URL, {
|
||||
fetch: async (input: RequestInfo | URL, requestInit?: RequestInit) => {
|
||||
return apiClient.request(input, requestInit);
|
||||
},
|
||||
init: {
|
||||
credentials: 'include' // Required for sending cookies cross-origin
|
||||
}
|
||||
});
|
||||
|
||||
@@ -188,3 +166,6 @@ export {
|
||||
} from './utils';
|
||||
|
||||
export type { InferResponseType, InferRequestType } from '@cio/api/rpc-types';
|
||||
|
||||
// Export base API classes
|
||||
export { BaseApi, BaseApiWithErrors } from './base.svelte';
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// Types for better type safety
|
||||
import type { ZodError } from 'zod';
|
||||
|
||||
export interface ApiClientConfig {
|
||||
baseURL?: string;
|
||||
timeout?: number;
|
||||
@@ -10,6 +11,13 @@ export interface ApiClientConfig {
|
||||
onResponse?: (response: Response) => Promise<void> | void;
|
||||
}
|
||||
|
||||
export type ZodValidationError = {
|
||||
message: string; // stringified error.issues from zod
|
||||
name: 'ZodError';
|
||||
};
|
||||
|
||||
export type ZodValidatorMesssage = ZodError['issues'];
|
||||
|
||||
export interface RequestConfig extends RequestInit {
|
||||
timeout?: number;
|
||||
retries?: number;
|
||||
|
||||
@@ -3,6 +3,23 @@ import { ApiError } from './types';
|
||||
// Utility function for exponential backoff
|
||||
export const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
export const getErrMsg = (error: unknown, fallback = 'Something went wrong'): string => {
|
||||
if (error instanceof ApiError) {
|
||||
return error.message;
|
||||
}
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
if (typeof error === 'string') {
|
||||
return error;
|
||||
}
|
||||
if (error instanceof Object && 'message' in error) {
|
||||
return error.message as string;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
};
|
||||
|
||||
// Helper function to handle JSON responses
|
||||
export const handleJsonResponse = async <T = any>(response: Response): Promise<T> => {
|
||||
if (!response.ok) {
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { createAuthClient } from 'better-auth/svelte';
|
||||
import { env } from '$env/dynamic/public';
|
||||
|
||||
export const authClient = createAuthClient({
|
||||
baseURL: env.PUBLIC_SERVER_URL,
|
||||
fetchOptions: {
|
||||
credentials: 'include' // Include cookies in requests
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { Cookies } from '@sveltejs/kit';
|
||||
import { authClient } from './client';
|
||||
import { classroomio } from '$lib/utils/services/api';
|
||||
|
||||
export const getSessionData = async (cookies: Cookies): Promise<App.Locals | null> => {
|
||||
try {
|
||||
const cioCookies = cookies
|
||||
.getAll()
|
||||
.filter((c) => c.name.includes('classroomio'))
|
||||
.map((c) => `${c.name}=${c.value}`)
|
||||
.join('; ');
|
||||
|
||||
if (!cioCookies) return null;
|
||||
|
||||
const locals = await getThroughAuthClient(cioCookies);
|
||||
|
||||
if (!locals) return null;
|
||||
|
||||
locals.fromSessions = !!cookies.get('classroomio.session_data');
|
||||
|
||||
return locals;
|
||||
} catch (error) {
|
||||
console.error('Session verification failed:', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export async function getThroughTrpc(allCookies: string) {
|
||||
const session = await classroomio.session.$get(undefined, {
|
||||
headers: {
|
||||
cookie: allCookies
|
||||
}
|
||||
});
|
||||
|
||||
const data = (await session.json()) as App.Locals;
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
async function getThroughAuthClient(allCookies: string) {
|
||||
const session = await authClient.getSession({
|
||||
fetchOptions: {
|
||||
headers: {
|
||||
cookie: allCookies
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return session.data as App.Locals | null;
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
import { getAccessToken } from '$lib/utils/functions/supabase';
|
||||
|
||||
export const NOTIFICATION_NAME = {
|
||||
WELCOME_TO_APP: 'WELCOME TO APP',
|
||||
VERIFY_EMAIL: 'VERFIY_EMAIL',
|
||||
INVITE_TEACHER: 'INVITE TEACHER',
|
||||
WELCOME_TEACHER_TO_COURSE: 'WELCOME TEACHER TO COURSE',
|
||||
SEND_TEACHER_STUDENT_BUY_REQUEST: 'SEND TEACHER STUDENT BUY REQUEST',
|
||||
@@ -15,8 +13,6 @@ export const NOTIFICATION_NAME = {
|
||||
};
|
||||
|
||||
const NAME_TO_PATH = {
|
||||
[NOTIFICATION_NAME.WELCOME_TO_APP]: '/api/email/welcome',
|
||||
[NOTIFICATION_NAME.VERIFY_EMAIL]: '/api/email/verify_email',
|
||||
[NOTIFICATION_NAME.INVITE_TEACHER]: '/api/email/invite',
|
||||
[NOTIFICATION_NAME.WELCOME_TEACHER_TO_COURSE]: '/api/email/course/teacher_welcome',
|
||||
[NOTIFICATION_NAME.SEND_TEACHER_STUDENT_BUY_REQUEST]: '/api/email/course/teacher_student_buycourse',
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import type { CurrentOrg, OrgTeamMember } from '$lib/utils/types/org';
|
||||
import { ROLE, ROLE_LABEL } from '$lib/utils/constants/roles';
|
||||
import { currentOrg, orgAudience, orgTeam, orgs } from '$lib/utils/store/org';
|
||||
|
||||
import type { OrganizationPlan } from '$lib/utils/types';
|
||||
import type { PostgrestError } from '@supabase/supabase-js';
|
||||
import { ROLE } from '@cio/utils/constants';
|
||||
import { ROLE_LABEL } from '$lib/utils/constants/roles';
|
||||
import { get } from 'svelte/store';
|
||||
import { goto } from '$app/navigation';
|
||||
import { supabase } from '$lib/utils/functions/supabase';
|
||||
|
||||
Reference in New Issue
Block a user