| 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 ForgotPasswordEmail from '@/emails/templates/forgot-password' |
| 16 | import InvitationEmail from '@/emails/templates/invitation' |
| 17 | import VerifyEmail from '@/emails/templates/verify-email' |
| 18 | import { env } from '@/env' |
| 19 | import { polarClient } from '@/lib/polar' |
| 20 | import { todayDateOnly } from '@/lib/utils' |
| 21 | import { FREE_PLAN_LIMITS } from '@/limits' |
| 22 | import { db } from '@/server/db' |
| 23 | import * as schema from '@/server/db/schema' |
| 24 | import { memberRates, pendingMemberRates, settings } from '@/server/db/schema' |
| 25 | import { emailService } from '@/services/email.service' |
| 26 | import { ac, adminRole, clientRole, memberRole, ownerRole } from './permissions' |
| 27 | |
| 28 | function invalidateBillingCache(organizationId: string | null | undefined) { |
| 29 | if (!organizationId) { |
| 30 | return |
| 31 | } |
| 32 | for (const tag of BillingCacheKeys.getOrganizationBillingStatus( |
| 33 | organizationId |
| 34 | )) { |
| 35 | revalidateTag(tag, 'max') |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | export const auth = betterAuth({ |
| 40 | database: drizzleAdapter(db, { |
| 41 | provider: 'pg', |
| 42 | usePlural: true, |
| 43 | schema, |
| 44 | }), |
| 45 | user: { |
| 46 | additionalFields: { |
| 47 | timezone: { |
| 48 | type: 'string', |
| 49 | required: false, |
| 50 | // Written only through the IANA-validated updateTimezoneAction, never |
| 51 | // accepted as untrusted sign-up input. |
| 52 | input: false, |
| 53 | }, |
| 54 | }, |
| 55 | }, |
| 56 | emailAndPassword: { |
| 57 | enabled: true, |
| 58 | requireEmailVerification: true, |
| 59 | resetPasswordTokenExpiresIn: 60 * 60, |
| 60 | async sendResetPassword({ user, url }) { |
| 61 | const html = await render( |
| 62 | ForgotPasswordEmail({ |
| 63 | name: user.name, |
| 64 | resetUrl: url, |
| 65 | }) |
| 66 | ) |
| 67 | await emailService.sendEmail({ |
| 68 | to: user.email, |
| 69 | subject: 'Reset your Saturn password', |
| 70 | html, |
| 71 | }) |
| 72 | }, |
| 73 | }, |
| 74 | emailVerification: { |
| 75 | sendOnSignUp: true, |
| 76 | sendOnSignIn: true, |
| 77 | autoSignInAfterVerification: true, |
| 78 | expiresIn: 60 * 60, |
| 79 | async sendVerificationEmail({ user, url }) { |
| 80 | const verifyUrl = new URL(url) |
| 81 | verifyUrl.searchParams.set( |
| 82 | 'redirectTo', |
| 83 | `${env.NEXT_PUBLIC_BASE_URL}/dashboard` |
| 84 | ) |
| 85 | const html = await render( |
| 86 | VerifyEmail({ |
| 87 | name: user.name, |
| 88 | verifyUrl: verifyUrl.toString(), |
| 89 | }) |
| 90 | ) |
| 91 | await emailService.sendEmail({ |
| 92 | to: user.email, |
| 93 | subject: 'Verify your email for Saturn', |
| 94 | html, |
| 95 | }) |
| 96 | }, |
| 97 | }, |
| 98 | plugins: [ |
| 99 | apiKey({ |
| 100 | enableMetadata: true, |
| 101 | references: 'organization', |
| 102 | rateLimit: { |
| 103 | enabled: true, |
| 104 | timeWindow: 1000 * 60, |
| 105 | maxRequests: 120, |
| 106 | }, |
| 107 | }), |
| 108 | lastLoginMethod(), |
| 109 | organization({ |
| 110 | ac, |
| 111 | roles: { |
| 112 | owner: ownerRole, |
| 113 | admin: adminRole, |
| 114 | member: memberRole, |
| 115 | client: clientRole, |
| 116 | }, |
| 117 | async allowUserToCreateOrganization(user) { |
| 118 | const hasActiveSubscription = await getUserBillingStatus(user.id) |
| 119 | if (hasActiveSubscription) { |
| 120 | return true |
| 121 | } |
| 122 | |
| 123 | const [row] = await db |
| 124 | .select({ value: count() }) |
| 125 | .from(schema.members) |
| 126 | .where( |
| 127 | and( |
| 128 | eq(schema.members.userId, user.id), |
| 129 | eq(schema.members.role, 'owner') |
| 130 | ) |
| 131 | ) |
| 132 | const ownedCount = row?.value ?? 0 |
| 133 | |
| 134 | if (ownedCount >= FREE_PLAN_LIMITS.WORKSPACES) { |
| 135 | throw new APIError('PAYMENT_REQUIRED', { |
| 136 | message: `Free plan is limited to ${FREE_PLAN_LIMITS.WORKSPACES} workspace. Upgrade to Pro to create additional workspaces.`, |
| 137 | }) |
| 138 | } |
| 139 | return true |
| 140 | }, |
| 141 | async sendInvitationEmail(data) { |
| 142 | const html = await render( |
| 143 | InvitationEmail({ |
| 144 | invitedByName: data.inviter.user.name, |
| 145 | organizationName: data.organization.name, |
| 146 | role: data.role, |
| 147 | inviteLink: `${env.NEXT_PUBLIC_BASE_URL}/invite/${data.id}`, |
| 148 | }) |
| 149 | ) |
| 150 | await emailService.sendEmail({ |
| 151 | to: data.email, |
| 152 | subject: `You've been invited to join ${data.organization.name}`, |
| 153 | html, |
| 154 | }) |
| 155 | }, |
| 156 | organizationHooks: { |
| 157 | async afterAcceptInvitation({ invitation, member, organization }) { |
| 158 | // Check for a rate specified at invite time |
| 159 | const [pendingRate] = await db |
| 160 | .select() |
| 161 | .from(pendingMemberRates) |
| 162 | .where(eq(pendingMemberRates.invitationId, invitation.id)) |
| 163 | |
| 164 | if (pendingRate) { |
| 165 | // Insert + delete are one state transition — keep them atomic so a |
| 166 | // failure can't leave a stale pending row or duplicate the rate. |
| 167 | await db.transaction(async (tx) => { |
| 168 | await tx.insert(memberRates).values({ |
| 169 | effectiveFrom: todayDateOnly(), |
| 170 | memberId: member.id, |
| 171 | payRate: pendingRate.payRate, |
| 172 | billingCurrency: pendingRate.billingCurrency, |
| 173 | billingFrequency: pendingRate.billingFrequency, |
| 174 | billingRate: pendingRate.billingRate, |
| 175 | payCurrency: pendingRate.payCurrency, |
| 176 | payFrequency: pendingRate.payFrequency, |
| 177 | }) |
| 178 | await tx |
| 179 | .delete(pendingMemberRates) |
| 180 | .where(eq(pendingMemberRates.id, pendingRate.id)) |
| 181 | }) |
| 182 | return |
| 183 | } |
| 184 | |
| 185 | // Fall back to workspace wide defaults |
| 186 | const [setting] = await db |
| 187 | .select() |
| 188 | .from(settings) |
| 189 | .where( |
| 190 | and( |
| 191 | eq(settings.organizationId, organization.id), |
| 192 | isNull(settings.projectId) |
| 193 | ) |
| 194 | ) |
| 195 | if (!setting?.payRate) { |
| 196 | return |
| 197 | } |
| 198 | await db.insert(memberRates).values({ |
| 199 | effectiveFrom: todayDateOnly(), |
| 200 | memberId: member.id, |
| 201 | payRate: setting.payRate, |
| 202 | billingCurrency: setting.billingCurrency, |
| 203 | billingFrequency: setting.billingFrequency, |
| 204 | billingRate: setting.billingRate, |
| 205 | payCurrency: setting.payCurrency, |
| 206 | payFrequency: setting.payFrequency, |
| 207 | }) |
| 208 | }, |
| 209 | async afterCreateOrganization({ organization }) { |
| 210 | const defaultCategories = [ |
| 211 | { name: 'Software & Tools', color: '#6366f1' }, |
| 212 | { name: 'Travel', color: '#f59e0b' }, |
| 213 | { name: 'Equipment', color: '#10b981' }, |
| 214 | { name: 'Office Supplies', color: '#8b5cf6' }, |
| 215 | { name: 'Communication', color: '#3b82f6' }, |
| 216 | { name: 'Professional Services', color: '#ec4899' }, |
| 217 | { name: 'Miscellaneous', color: '#6b7280' }, |
| 218 | ] |
| 219 | await db.insert(schema.expenseCategories).values( |
| 220 | defaultCategories.map((cat, i) => ({ |
| 221 | organizationId: organization.id, |
| 222 | name: cat.name, |
| 223 | color: cat.color, |
| 224 | sortOrder: i, |
| 225 | })) |
| 226 | ) |
| 227 | |
| 228 | const owner = await db |
| 229 | .select({ email: schema.users.email, name: schema.users.name }) |
| 230 | .from(schema.members) |
| 231 | .innerJoin(schema.users, eq(schema.members.userId, schema.users.id)) |
| 232 | .where( |
| 233 | and( |
| 234 | eq(schema.members.organizationId, organization.id), |
| 235 | eq(schema.members.role, 'owner') |
| 236 | ) |
| 237 | ) |
| 238 | .then((r) => r.at(0)) |
| 239 | |
| 240 | if (owner) { |
| 241 | await polarClient.customers |
| 242 | .create({ |
| 243 | email: owner.email, |
| 244 | name: owner.name ?? organization.name, |
| 245 | externalId: organization.id, |
| 246 | metadata: { organizationName: organization.name }, |
| 247 | }) |
| 248 | .catch(() => { |
| 249 | // Customer may already exist — safe to ignore |
| 250 | }) |
| 251 | } |
| 252 | }, |
| 253 | }, |
| 254 | teams: { |
| 255 | enabled: true, |
| 256 | allowRemovingAllTeams: false, |
| 257 | defaultTeam: { |
| 258 | enabled: true, |
| 259 | async customCreateDefaultTeam(organization) { |
| 260 | const team = await db |
| 261 | .insert(schema.teams) |
| 262 | .values({ |
| 263 | name: 'Default Team', |
| 264 | organizationId: organization.id, |
| 265 | createdAt: new Date(), |
| 266 | id: createId(), |
| 267 | updatedAt: new Date(), |
| 268 | }) |
| 269 | .returning() |
| 270 | return team[0] as { |
| 271 | id: string |
| 272 | name: string |
| 273 | organizationId: string |
| 274 | createdAt: Date |
| 275 | updatedAt: Date |
| 276 | } |
| 277 | }, |
| 278 | }, |
| 279 | }, |
| 280 | }), |
| 281 | polar({ |
| 282 | client: polarClient, |
| 283 | /// 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 |
| 284 | createCustomerOnSignUp: false, |
| 285 | use: [ |
| 286 | checkout({ |
| 287 | products: [ |
| 288 | { |
| 289 | productId: env.POLAR_PRODUCT_ID, |
| 290 | slug: env.POLAR_PRODUCT_SLUG, |
| 291 | }, |
| 292 | ], |
| 293 | successUrl: `${env.NEXT_PUBLIC_BASE_URL}/success?checkout_id={CHECKOUT_ID}`, |
| 294 | authenticatedUsersOnly: true, |
| 295 | }), |
| 296 | portal(), |
| 297 | webhooks({ |
| 298 | secret: env.POLAR_WEBHOOK_SECRET, |
| 299 | onSubscriptionCreated: async ({ data }) => { |
| 300 | await invalidateBillingCache(data.customer.externalId) |
| 301 | }, |
| 302 | onSubscriptionUpdated: async ({ data }) => { |
| 303 | await invalidateBillingCache(data.customer.externalId) |
| 304 | }, |
| 305 | }), |
| 306 | ], |
| 307 | }), |
| 308 | ], |
| 309 | socialProviders: { |
| 310 | github: { |
| 311 | clientId: env.GITHUB_CLIENT_ID, |
| 312 | clientSecret: env.GITHUB_CLIENT_SECRET, |
| 313 | }, |
| 314 | google: { |
| 315 | clientId: env.GOOGLE_CLIENT_ID, |
| 316 | clientSecret: env.GOOGLE_CLIENT_SECRET, |
| 317 | }, |
| 318 | }, |
| 319 | trustedOrigins: env.CORS_ORIGIN, |
| 320 | baseURL: env.NEXT_PUBLIC_BASE_URL, |
| 321 | }) |
| 322 | |
| 323 | export const getSession = async (request?: NextRequest) => |
| 324 | auth.api.getSession({ |
| 325 | headers: request ? request.headers : await headers(), |
| 326 | }) |