| 1 | import { apiKey } from '@better-auth/api-key' |
| 2 | import { createId } |
| 3 | import { checkout, polar |
| 4 | import { render } |
| 5 | import { betterAuth } |
| 6 | import { drizzleAdapter } |
| 7 | import { APIError } |
| 8 | import { lastLoginMethod, organization |
| 9 | import { and, count |
| 10 | import { revalidateTag } |
| 11 | import { headers } |
| 12 | import type { NextRequest |
| 13 | import { getUserBillingStatus } |
| 14 | import { BillingCacheKeys } |
| 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 } |
| 19 | import { polarClient } |
| 20 | import { todayDateOnly } |
| 21 | import { FREE_PLAN_LIMITS } |
| 22 | import { db } |
| 23 | import * as schema |
| 24 | import { memberRates, pendingMemberRates |
| 25 | import { emailService } |
| 26 | import { ac, adminRole |
| 27 | |
| 28 | function invalidateBillingCache(organizationId |
| 29 | if (!organizationId) |
| 30 | return |
| 31 | } |
| 32 | for (const tag |
| 33 | organizationId |
| 34 | )) { |
| 35 | revalidateTag(tag, ' |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | export const auth = |
| 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({ |
| 61 | const html = |
| 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({ |
| 80 | const verifyUrl = |
| 81 | verifyUrl.searchParams.set |
| 82 | 'redirectTo', |
| 83 | `${env.NEXT_PUBLIC_BASE_URL} |
| 84 | ) |
| 85 | const html = |
| 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 = |
| 119 | if (hasActiveSubscription) { |
| 120 | return true |
| 121 | } |
| 122 | |
| 123 | const [row] |
| 124 | .select({ value: |
| 125 | .from(schema.members |
| 126 | .where( |
| 127 | and( |
| 128 | eq(schema.members |
| 129 | eq(schema.members |
| 130 | ) |
| 131 | ) |
| 132 | const ownedCount = |
| 133 | |
| 134 | if (ownedCount >= |
| 135 | throw new APIError( |
| 136 | message: `Free plan is limited to ${FREE_PLAN_LIMITS |
| 137 | }) |
| 138 | } |
| 139 | return true |
| 140 | }, |
| 141 | async sendInvitationEmail(data |
| 142 | const html = |
| 143 | InvitationEmail({ |
| 144 | invitedByName: data.inviter |
| 145 | organizationName: data.organization |
| 146 | role: data.role |
| 147 | inviteLink: `${env. |
| 148 | }) |
| 149 | ) |
| 150 | await emailService.sendEmail |
| 151 | to: data.email |
| 152 | subject: `You've been invited to join ${data |
| 153 | html, |
| 154 | }) |
| 155 | }, |
| 156 | organizationHooks: { |
| 157 | async afterAcceptInvitation({ |
| 158 | // Check for a rate specified at invite time |
| 159 | const [pendingRate] |
| 160 | .select() |
| 161 | .from(pendingMemberRates) |
| 162 | .where(eq(pendingMemberRates |
| 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 |
| 168 | await tx.insert |
| 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 |
| 181 | }) |
| 182 | return |
| 183 | } |
| 184 | |
| 185 | // Fall back to workspace wide defaults |
| 186 | const [setting] |
| 187 | .select() |
| 188 | .from(settings) |
| 189 | .where( |
| 190 | and( |
| 191 | eq(settings.organizationId |
| 192 | isNull(settings.projectId |
| 193 | ) |
| 194 | ) |
| 195 | if (!setting?.payRate |
| 196 | return |
| 197 | } |
| 198 | await db.insert |
| 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({ |
| 210 | const defaultCategories = |
| 211 | { name: 'Software & Tools', |
| 212 | { name: 'Travel', |
| 213 | { name: 'Equipment', |
| 214 | { name: 'Office Supplies', |
| 215 | { name: 'Communication', |
| 216 | { name: 'Professional Services', |
| 217 | { name: 'Miscellaneous', |
| 218 | ] |
| 219 | await db.insert |
| 220 | defaultCategories.map((cat |
| 221 | organizationId: organization.id |
| 222 | name: cat.name |
| 223 | color: cat.color |
| 224 | sortOrder: i, |
| 225 | })) |
| 226 | ) |
| 227 | |
| 228 | const owner = |
| 229 | .select({ email: |
| 230 | .from(schema.members |
| 231 | .innerJoin(schema.users |
| 232 | .where( |
| 233 | and( |
| 234 | eq(schema.members |
| 235 | eq(schema.members |
| 236 | ) |
| 237 | ) |
| 238 | .then((r) |
| 239 | |
| 240 | if (owner) { |
| 241 | await polarClient.customers |
| 242 | .create({ |
| 243 | email: owner.email |
| 244 | name: owner.name |
| 245 | externalId: organization.id |
| 246 | metadata: { organizationName: organization |
| 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 = |
| 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] |
| 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. |
| 294 | authenticatedUsersOnly: true, |
| 295 | }), |
| 296 | portal(), |
| 297 | webhooks({ |
| 298 | secret: env.POLAR_WEBHOOK_SECRET |
| 299 | onSubscriptionCreated: async ( |
| 300 | await invalidateBillingCache(data |
| 301 | }, |
| 302 | onSubscriptionUpdated: async ( |
| 303 | await invalidateBillingCache(data |
| 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 = |
| 324 | auth.api.getSession |
| 325 | headers: request ? |
| 326 | }) |