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,68 @@
|
||||
import * as schema from '@db/schema';
|
||||
import bcrypt from 'bcrypt';
|
||||
|
||||
import { db, eq } from '@db/drizzle';
|
||||
import { type BetterAuthOptions } from 'better-auth';
|
||||
import { sendEmail } from '@cio/email';
|
||||
|
||||
/**
|
||||
* Configuration for the email and password options
|
||||
* @see https://www.better-auth.com/docs/authentication/email-password
|
||||
*/
|
||||
export const config: BetterAuthOptions['emailAndPassword'] = {
|
||||
enabled: true,
|
||||
password: {
|
||||
hash: async (password) => {
|
||||
return await bcrypt.hash(password, 10);
|
||||
},
|
||||
verify: async ({ hash, password }) => {
|
||||
return await bcrypt.compare(password, hash);
|
||||
}
|
||||
},
|
||||
sendResetPassword: sendResetPassword,
|
||||
onPasswordReset: onPasswordReset
|
||||
};
|
||||
|
||||
/**
|
||||
* Types for the email and password options
|
||||
*/
|
||||
type ResetPasswordOptions = Parameters<
|
||||
NonNullable<NonNullable<BetterAuthOptions['emailAndPassword']>['sendResetPassword']>
|
||||
>[0];
|
||||
type OnPasswordResetEmail = Parameters<
|
||||
NonNullable<NonNullable<BetterAuthOptions['emailAndPassword']>['onPasswordReset']>
|
||||
>[0];
|
||||
|
||||
async function sendResetPassword(options: ResetPasswordOptions) {
|
||||
const { user, url } = options;
|
||||
|
||||
const [profile] = await db.select().from(schema.profile).where(eq(schema.profile.id, user.id)).limit(1);
|
||||
if (!profile) {
|
||||
throw new Error('Profile not found');
|
||||
}
|
||||
|
||||
await sendEmail('forgotPassword', {
|
||||
to: user.email,
|
||||
fields: {
|
||||
name: profile.fullname,
|
||||
email: user.email,
|
||||
link: url
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function onPasswordReset(options: OnPasswordResetEmail) {
|
||||
const { user } = options;
|
||||
|
||||
const [profile] = await db.select().from(schema.profile).where(eq(schema.profile.id, user.id)).limit(1);
|
||||
if (!profile) {
|
||||
throw new Error('Profile not found');
|
||||
}
|
||||
|
||||
await sendEmail('onPasswordReset', {
|
||||
to: user.email,
|
||||
fields: {
|
||||
name: profile.fullname
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { type BetterAuthOptions } from 'better-auth';
|
||||
import { sendEmail } from '@cio/email';
|
||||
|
||||
type EmailVerificationOptions = Parameters<
|
||||
NonNullable<NonNullable<BetterAuthOptions['emailVerification']>['sendVerificationEmail']>
|
||||
>[0];
|
||||
|
||||
type ChangeEmailConfirmationOptions = Parameters<
|
||||
NonNullable<NonNullable<NonNullable<BetterAuthOptions['user']>['changeEmail']>['sendChangeEmailConfirmation']>
|
||||
>[0];
|
||||
|
||||
/**
|
||||
* Email verification flow.
|
||||
*
|
||||
* 1. user says I want to change my email from email@old.com to email@new.com
|
||||
* 2. we send an email to email@old.com asking user to verify if they really want to change their email to email@new.com `sendChangeEmailConfirmation()`. [better-auth].
|
||||
* 3. user clicks the link in the email
|
||||
* 4. we update the email in the database. [better-auth].
|
||||
* 5. we send a confirmation email to email@new.com `sendVerificationEmail()`. [dashboard].
|
||||
* 6. user clicks the link in the email
|
||||
* 7. we mark email@new.com as verified. [better-auth].
|
||||
*/
|
||||
|
||||
/**
|
||||
* Sends a verification email to the user when they sign up or change their email address.
|
||||
* @param options - The options for sending the verification email.
|
||||
* @returns The verification email.
|
||||
*/
|
||||
export const sendVerificationEmail = async (options: EmailVerificationOptions) => {
|
||||
const { user, url } = options;
|
||||
console.log('\nsendVerificationEmail');
|
||||
|
||||
// The purpose of this is to prevent verification email trigger from better-auth because we already have a flow in the UI for triggering this email.
|
||||
if (!url.includes('trigger=app') && !url.includes('trigger%3Dapp')) {
|
||||
return;
|
||||
}
|
||||
|
||||
await sendEmail('verifyEmail', {
|
||||
to: user.email,
|
||||
fields: {
|
||||
link: url,
|
||||
userName: user.name || undefined
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Sends a confirmation email to the user when they change their email address.
|
||||
* @param options - The options for sending the change email confirmation.
|
||||
* @returns The confirmation email.
|
||||
*/
|
||||
export const sendChangeEmailConfirmation = async (options: ChangeEmailConfirmationOptions) => {
|
||||
const { user, newEmail, url } = options;
|
||||
console.log('\nsendChangeEmailConfirmation');
|
||||
|
||||
await sendEmail('verifyEmail', {
|
||||
to: user.email,
|
||||
fields: {
|
||||
link: url,
|
||||
newEmail,
|
||||
userName: user.name || undefined
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,51 @@
|
||||
import * as schema from '@db/schema';
|
||||
|
||||
import { and, eq } from 'drizzle-orm';
|
||||
|
||||
import { User } from 'better-auth';
|
||||
import { db } from '@db/drizzle';
|
||||
|
||||
/**
|
||||
* This hook runs after user creation (email/password or OAuth signup).
|
||||
*
|
||||
* We use the profile table for everything related to the user because we heavily used supabase and supabase didn't allow you add fields to the auth.users table.
|
||||
*
|
||||
*/
|
||||
export const createProfileHook = async (user: User) => {
|
||||
console.debug('createProfileHook', user);
|
||||
|
||||
const existingProfile = await db.select().from(schema.profile).where(eq(schema.profile.id, user.id)).limit(1);
|
||||
console.debug('existingProfile', existingProfile);
|
||||
if (existingProfile.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const googleAccount = await db
|
||||
.select()
|
||||
.from(schema.account)
|
||||
.where(and(eq(schema.account.userId, user.id), eq(schema.account.providerId, 'google')))
|
||||
.limit(1);
|
||||
|
||||
const isEmailVerified = user.emailVerified || googleAccount.length > 0;
|
||||
const verifiedAt = isEmailVerified ? new Date().toISOString() : undefined;
|
||||
|
||||
// Extract username from email (part before @)
|
||||
const emailMatch = user.email?.match(/^([^@]+)@/);
|
||||
const emailPrefix = emailMatch ? emailMatch[1] : 'user';
|
||||
const username = `${emailPrefix}${new Date().getTime()}`;
|
||||
const fullname = emailPrefix;
|
||||
|
||||
try {
|
||||
const newProfile = await db.insert(schema.profile).values({
|
||||
id: user.id,
|
||||
username,
|
||||
fullname,
|
||||
email: user.email || undefined,
|
||||
isEmailVerified,
|
||||
verifiedAt
|
||||
});
|
||||
console.debug('newProfile', newProfile);
|
||||
} catch (error) {
|
||||
console.error('Error creating profile for user:', error);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import { createAuthMiddleware } from 'better-auth/api';
|
||||
|
||||
export type AuthMiddlewareContext = Parameters<Parameters<typeof createAuthMiddleware>[0]>[0];
|
||||
|
||||
/**
|
||||
* Array of all hooks to run after better-auth requests
|
||||
*
|
||||
* Add new hooks here to register them
|
||||
*/
|
||||
const afterHooks: Array<(context: AuthMiddlewareContext) => Promise<unknown>> = [
|
||||
// add hooks here
|
||||
];
|
||||
|
||||
/**
|
||||
* Combines all after hooks into a single function
|
||||
* This function will be called by better-auth after each request
|
||||
*/
|
||||
export const combineAfterHooks = async (context: AuthMiddlewareContext) => {
|
||||
for (const hook of afterHooks) {
|
||||
try {
|
||||
await hook(context);
|
||||
} catch (error) {
|
||||
console.error('Error executing hook:', error);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import * as schema from '@db/schema';
|
||||
|
||||
import { User } from 'better-auth';
|
||||
import { db } from '@db/drizzle';
|
||||
import { eq } from 'drizzle-orm';
|
||||
|
||||
export const syncUserWithProfile = async (user: User) => {
|
||||
console.debug('syncUserWithProfile', user);
|
||||
|
||||
if (!user?.id) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// update profile and mark as verified
|
||||
await db
|
||||
.update(schema.profile)
|
||||
.set({
|
||||
email: user.email,
|
||||
isEmailVerified: user.emailVerified
|
||||
})
|
||||
.where(eq(schema.profile.id, user.id));
|
||||
} catch (error) {
|
||||
console.error('Error marking profile as verified:', error);
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user