| 1 | import { apiKey } from '@better-auth/api-key' |
| 2 | import { createId } from '@paralleldrive/cuid2' |
| 3 | import { checkout, polar, portal, webhooks } from '@polar-sh/better-auth' |
| 4 | import { render } from '@react-email/render' |
| 5 | import { betterAuth } from 'better-auth' |
| 6 | import { drizzleAdapter } from 'better-auth/adapters/drizzle' |
| 7 | import { APIError } from 'better-auth/api' |
| 8 | import { lastLoginMethod, organization } from 'better-auth/plugins' |
| 9 | import { and, count, eq, isNull } from 'drizzle-orm' |
| 10 | import { revalidateTag } from 'next/cache' |
| 11 | import { headers } from 'next/headers' |
| 12 | import type { NextRequest } from 'next/server' |
| 13 | import { getUserBillingStatus } from '@/cache/billing' |
| 14 | import { BillingCacheKeys } from '@/cache/billing/keys' |
| 15 | import InvitationEmail from '@/emails/templates/invitation' |
| 16 | import { env } from '@/env' |
| 17 | import { polarClient } from '@/lib/polar' |
| 18 | import { FREE_PLAN_LIMITS } from '@/limits' |
| 19 | import { db } from '@/server/db' |
| 20 | import * as schema from '@/server/db/schema' |
| 21 | import { memberRates, pendingMemberRates, settings } from '@/server/db/schema' |
| 22 | import { emailService } from '@/services/email.service' |
| 23 | import { ac, adminRole, clientRole, memberRole, ownerRole } from './permissions' |
| 24 | |
| 25 | function invalidateBillingCache(organizationId: string | null | undefined) { |
| 26 | if (!organizationId) { |
| 27 | return |
| 28 | } |
| 29 | for (const tag of BillingCacheKeys.getOrganizationBillingStatus( |
| 30 | organizationId |
| 31 | )) { |
| 32 | revalidateTag(tag, 'max') |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | export const auth = betterAuth({ |
| 37 | database: drizzleAdapter(db, { |
| 38 | provider: 'pg', |
| 39 | usePlural: true, |
| 40 | schema, |
| 41 | }), |
| 42 | emailAndPassword: { |
| 43 | enabled: true, |
| 44 | }, |
| 45 | plugins: [ |
| 46 | apiKey({ |
| 47 | enableMetadata: true, |
| 48 | references: 'organization', |
| 49 | rateLimit: { |
| 50 | enabled: true, |
| 51 | timeWindow: 1000 * 60, |
| 52 | maxRequests: 120, |
| 53 | }, |
| 54 | }), |
| 55 | lastLoginMethod(), |
| 56 | organization({ |
| 57 | ac, |
| 58 | roles: { |
| 59 | owner: ownerRole, |
| 60 | admin: adminRole, |
| 61 | member: memberRole, |
| 62 | client: clientRole, |
| 63 | }, |
| 64 | async allowUserToCreateOrganization(user) { |
| 65 | const hasActiveSubscription = await getUserBillingStatus(user.id) |
| 66 | if (hasActiveSubscription) { |
| 67 | return true |
| 68 | } |
| 69 | |
| 70 | const [row] = await db |
| 71 | .select({ value: count() }) |
| 72 | .from(schema.members) |
| 73 | .where( |
| 74 | and( |
| 75 | eq(schema.members.userId, user.id), |
| 76 | eq(schema.members.role, 'owner') |
| 77 | ) |
| 78 | ) |
| 79 | const ownedCount = row?.value ?? 0 |
| 80 | |
| 81 | if (ownedCount >= FREE_PLAN_LIMITS.WORKSPACES) { |
| 82 | throw new APIError('PAYMENT_REQUIRED', { |
| 83 | message: `Free plan is limited to ${FREE_PLAN_LIMITS.WORKSPACES} workspace. Upgrade to Pro to create additional workspaces.`, |
| 84 | }) |
| 85 | } |
| 86 | return true |
| 87 | }, |
| 88 | async sendInvitationEmail(data) { |
| 89 | const html = await render( |
| 90 | InvitationEmail({ |
| 91 | invitedByName: data.inviter.user.name, |
| 92 | organizationName: data.organization.name, |
| 93 | role: data.role, |
| 94 | inviteLink: `${env.NEXT_PUBLIC_BASE_URL}/invite/${data.id}`, |
| 95 | }) |
| 96 | ) |
| 97 | await emailService.sendEmail({ |
| 98 | to: data.email, |
| 99 | subject: `You've been invited to join ${data.organization.name}`, |
| 100 | html, |
| 101 | }) |
| 102 | }, |
| 103 | organizationHooks: { |
| 104 | async afterAcceptInvitation({ invitation, member, organization }) { |
| 105 | // Check for a rate specified at invite time |
| 106 | const [pendingRate] = await db |
| 107 | .select() |
| 108 | .from(pendingMemberRates) |
| 109 | .where(eq(pendingMemberRates.invitationId, invitation.id)) |
| 110 | |
| 111 | if (pendingRate) { |
| 112 | await db.insert(memberRates).values({ |
| 113 | effectiveFrom: new Date(), |
| 114 | hourlyRate: pendingRate.hourlyRate, |
| 115 | memberId: member.id, |
| 116 | currency: pendingRate.currency, |
| 117 | }) |
| 118 | await db |
| 119 | .delete(pendingMemberRates) |
| 120 | .where(eq(pendingMemberRates.id, pendingRate.id)) |
| 121 | return |
| 122 | } |
| 123 | |
| 124 | // Fall back to workspace wide defaults |
| 125 | const [setting] = await db |
| 126 | .select() |
| 127 | .from(settings) |
| 128 | .where( |
| 129 | and( |
| 130 | eq(settings.organizationId, organization.id), |
| 131 | isNull(settings.projectId) |
| 132 | ) |
| 133 | ) |
| 134 | if (!setting) { |
| 135 | return |
| 136 | } |
| 137 | await db.insert(memberRates).values({ |
| 138 | effectiveFrom: new Date(), |
| 139 | hourlyRate: setting.memberRate, |
| 140 | memberId: member.id, |
| 141 | currency: setting.currency, |
| 142 | }) |
| 143 | }, |
| 144 | async afterCreateOrganization({ organization }) { |
| 145 | const defaultCategories = [ |
| 146 | { name: 'Software & Tools', color: '#6366f1' }, |
| 147 | { name: 'Travel', color: '#f59e0b' }, |
| 148 | { name: 'Equipment', color: '#10b981' }, |
| 149 | { name: 'Office Supplies', color: '#8b5cf6' }, |
| 150 | { name: 'Communication', color: '#3b82f6' }, |
| 151 | { name: 'Professional Services', color: '#ec4899' }, |
| 152 | { name: 'Miscellaneous', color: '#6b7280' }, |
| 153 | ] |
| 154 | await db.insert(schema.expenseCategories).values( |
| 155 | defaultCategories.map((cat, i) => ({ |
| 156 | organizationId: organization.id, |
| 157 | name: cat.name, |
| 158 | color: cat.color, |
| 159 | sortOrder: i, |
| 160 | })) |
| 161 | ) |
| 162 | |
| 163 | const owner = await db |
| 164 | .select({ email: schema.users.email, name: schema.users.name }) |
| 165 | .from(schema.members) |
| 166 | .innerJoin(schema.users, eq(schema.members.userId, schema.users.id)) |
| 167 | .where( |
| 168 | and( |
| 169 | eq(schema.members.organizationId, organization.id), |
| 170 | eq(schema.members.role, 'owner') |
| 171 | ) |
| 172 | ) |
| 173 | .then((r) => r.at(0)) |
| 174 | |
| 175 | if (owner) { |
| 176 | await polarClient.customers |
| 177 | .create({ |
| 178 | email: owner.email, |
| 179 | name: owner.name ?? organization.name, |
| 180 | externalId: organization.id, |
| 181 | metadata: { organizationName: organization.name }, |
| 182 | }) |
| 183 | .catch(() => { |
| 184 | // Customer may already exist — safe to ignore |
| 185 | }) |
| 186 | } |
| 187 | }, |
| 188 | }, |
| 189 | teams: { |
| 190 | enabled: true, |
| 191 | allowRemovingAllTeams: false, |
| 192 | defaultTeam: { |
| 193 | enabled: true, |
| 194 | async customCreateDefaultTeam(organization) { |
| 195 | const team = await db |
| 196 | .insert(schema.teams) |
| 197 | .values({ |
| 198 | name: 'Default Team', |
| 199 | organizationId: organization.id, |
| 200 | createdAt: new Date(), |
| 201 | id: createId(), |
| 202 | updatedAt: new Date(), |
| 203 | }) |
| 204 | .returning() |
| 205 | return team[0] as { |
| 206 | id: string |
| 207 | name: string |
| 208 | organizationId: string |
| 209 | createdAt: Date |
| 210 | updatedAt: Date |
| 211 | } |
| 212 | }, |
| 213 | }, |
| 214 | }, |
| 215 | }), |
| 216 | polar({ |
| 217 | client: polarClient, |
| 218 | /// we don't need to create a customer on sign up, as only owners can upgrade themselves, we create them when they create a new organization |
| 219 | createCustomerOnSignUp: false, |
| 220 | use: [ |
| 221 | checkout({ |
| 222 | products: [ |
| 223 | { |
| 224 | productId: env.POLAR_PRODUCT_ID, |
| 225 | slug: env.POLAR_PRODUCT_SLUG, |
| 226 | }, |
| 227 | ], |
| 228 | successUrl: '/success?checkout_id={CHECKOUT_ID}', |
| 229 | authenticatedUsersOnly: true, |
| 230 | }), |
| 231 | portal(), |
| 232 | webhooks({ |
| 233 | secret: env.POLAR_WEBHOOK_SECRET, |
| 234 | onSubscriptionCreated: async ({ data }) => { |
| 235 | await invalidateBillingCache(data.customer.externalId) |
| 236 | }, |
| 237 | onSubscriptionUpdated: async ({ data }) => { |
| 238 | await invalidateBillingCache(data.customer.externalId) |
| 239 | }, |
| 240 | }), |
| 241 | ], |
| 242 | }), |
| 243 | ], |
| 244 | socialProviders: { |
| 245 | github: { |
| 246 | clientId: env.GITHUB_CLIENT_ID, |
| 247 | clientSecret: env.GITHUB_CLIENT_SECRET, |
| 248 | }, |
| 249 | }, |
| 250 | trustedOrigins: env.CORS_ORIGIN, |
| 251 | baseURL: env.NEXT_PUBLIC_BASE_URL, |
| 252 | }) |
| 253 | |
| 254 | export const getSession = async (request?: NextRequest) => { |
| 255 | return auth.api.getSession({ |
| 256 | headers: request ? request.headers : await headers(), |
| 257 | }) |
| 258 | } |