| 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 InvitationEmail from '@/emails/templates/invitation |
| 16 | import VerifyEmail from '@/emails/templates/verify-email |
| 17 | import { env } |
| 18 | import { polarClient } |
| 19 | import { FREE_PLAN_LIMITS } |
| 20 | import { db } |
| 21 | import * as schema |
| 22 | import { memberRates, pendingMemberRates |
| 23 | import { emailService } |
| 24 | import { ac, adminRole |
| 25 | |
| 26 | function invalidateBillingCache(organizationId |
| 27 | if (!organizationId) |
| 28 | return |
| 29 | } |
| 30 | for (const tag |
| 31 | organizationId |
| 32 | )) { |
| 33 | revalidateTag(tag, ' |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | export const auth = |
| 38 | database: drizzleAdapter(db |
| 39 | provider: 'pg', |
| 40 | usePlural: true, |
| 41 | schema, |
| 42 | }), |
| 43 | emailAndPassword: { |
| 44 | enabled: true, |
| 45 | requireEmailVerification: true, |
| 46 | }, |
| 47 | emailVerification: { |
| 48 | sendOnSignUp: true, |
| 49 | autoSignInAfterVerification: true, |
| 50 | expiresIn: 60 * 60, |
| 51 | async sendVerificationEmail({ |
| 52 | const verifyUrl = |
| 53 | verifyUrl.searchParams.set |
| 54 | 'callbackURL', |
| 55 | `${env.NEXT_PUBLIC_BASE_URL} |
| 56 | ) |
| 57 | const html = |
| 58 | VerifyEmail({ |
| 59 | name: user.name |
| 60 | verifyUrl: verifyUrl.toString |
| 61 | }) |
| 62 | ) |
| 63 | await emailService.sendEmail |
| 64 | to: user.email |
| 65 | subject: 'Verify your email for Saturn', |
| 66 | html, |
| 67 | }) |
| 68 | }, |
| 69 | }, |
| 70 | plugins: [ |
| 71 | apiKey({ |
| 72 | enableMetadata: true, |
| 73 | references: 'organization', |
| 74 | rateLimit: { |
| 75 | enabled: true, |
| 76 | timeWindow: 1000 * 60, |
| 77 | maxRequests: 120, |
| 78 | }, |
| 79 | }), |
| 80 | lastLoginMethod(), |
| 81 | organization({ |
| 82 | ac, |
| 83 | roles: { |
| 84 | owner: ownerRole, |
| 85 | admin: adminRole, |
| 86 | member: memberRole, |
| 87 | client: clientRole, |
| 88 | }, |
| 89 | async allowUserToCreateOrganization(user |
| 90 | const hasActiveSubscription = |
| 91 | if (hasActiveSubscription) { |
| 92 | return true |
| 93 | } |
| 94 | |
| 95 | const [row] |
| 96 | .select({ value: |
| 97 | .from(schema.members |
| 98 | .where( |
| 99 | and( |
| 100 | eq(schema.members |
| 101 | eq(schema.members |
| 102 | ) |
| 103 | ) |
| 104 | const ownedCount = |
| 105 | |
| 106 | if (ownedCount >= |
| 107 | throw new APIError( |
| 108 | message: `Free plan is limited to ${FREE_PLAN_LIMITS |
| 109 | }) |
| 110 | } |
| 111 | return true |
| 112 | }, |
| 113 | async sendInvitationEmail(data |
| 114 | const html = |
| 115 | InvitationEmail({ |
| 116 | invitedByName: data.inviter |
| 117 | organizationName: data.organization |
| 118 | role: data.role |
| 119 | inviteLink: `${env. |
| 120 | }) |
| 121 | ) |
| 122 | await emailService.sendEmail |
| 123 | to: data.email |
| 124 | subject: `You've been invited to join ${data |
| 125 | html, |
| 126 | }) |
| 127 | }, |
| 128 | organizationHooks: { |
| 129 | async afterAcceptInvitation({ |
| 130 | // Check for a rate specified at invite time |
| 131 | const [pendingRate] |
| 132 | .select() |
| 133 | .from(pendingMemberRates) |
| 134 | .where(eq(pendingMemberRates |
| 135 | |
| 136 | if (pendingRate) { |
| 137 | await db.insert |
| 138 | effectiveFrom: new Date |
| 139 | hourlyRate: pendingRate.hourlyRate |
| 140 | memberId: member.id |
| 141 | currency: pendingRate.currency |
| 142 | }) |
| 143 | await db |
| 144 | .delete(pendingMemberRates) |
| 145 | .where(eq(pendingMemberRates |
| 146 | return |
| 147 | } |
| 148 | |
| 149 | // Fall back to workspace wide defaults |
| 150 | const [setting] |
| 151 | .select() |
| 152 | .from(settings) |
| 153 | .where( |
| 154 | and( |
| 155 | eq(settings.organizationId |
| 156 | isNull(settings.projectId |
| 157 | ) |
| 158 | ) |
| 159 | if (!setting) |
| 160 | return |
| 161 | } |
| 162 | await db.insert |
| 163 | effectiveFrom: new Date |
| 164 | hourlyRate: setting.memberRate |
| 165 | memberId: member.id |
| 166 | currency: setting.currency |
| 167 | }) |
| 168 | }, |
| 169 | async afterCreateOrganization({ |
| 170 | const defaultCategories = |
| 171 | { name: 'Software & Tools', |
| 172 | { name: 'Travel', |
| 173 | { name: 'Equipment', |
| 174 | { name: 'Office Supplies', |
| 175 | { name: 'Communication', |
| 176 | { name: 'Professional Services', |
| 177 | { name: 'Miscellaneous', |
| 178 | ] |
| 179 | await db.insert |
| 180 | defaultCategories.map((cat |
| 181 | organizationId: organization.id |
| 182 | name: cat.name |
| 183 | color: cat.color |
| 184 | sortOrder: i, |
| 185 | })) |
| 186 | ) |
| 187 | |
| 188 | const owner = |
| 189 | .select({ email: |
| 190 | .from(schema.members |
| 191 | .innerJoin(schema.users |
| 192 | .where( |
| 193 | and( |
| 194 | eq(schema.members |
| 195 | eq(schema.members |
| 196 | ) |
| 197 | ) |
| 198 | .then((r) |
| 199 | |
| 200 | if (owner) { |
| 201 | await polarClient.customers |
| 202 | .create({ |
| 203 | email: owner.email |
| 204 | name: owner.name |
| 205 | externalId: organization.id |
| 206 | metadata: { organizationName: organization |
| 207 | }) |
| 208 | .catch(() => |
| 209 | // Customer may already exist — safe to ignore |
| 210 | }) |
| 211 | } |
| 212 | }, |
| 213 | }, |
| 214 | teams: { |
| 215 | enabled: true, |
| 216 | allowRemovingAllTeams: false, |
| 217 | defaultTeam: { |
| 218 | enabled: true, |
| 219 | async customCreateDefaultTeam(organization |
| 220 | const team = |
| 221 | .insert(schema.teams |
| 222 | .values({ |
| 223 | name: 'Default Team', |
| 224 | organizationId: organization.id |
| 225 | createdAt: new Date |
| 226 | id: createId(), |
| 227 | updatedAt: new Date |
| 228 | }) |
| 229 | .returning() |
| 230 | return team[0] |
| 231 | id: string |
| 232 | name: string |
| 233 | organizationId: string |
| 234 | createdAt: Date |
| 235 | updatedAt: Date |
| 236 | } |
| 237 | }, |
| 238 | }, |
| 239 | }, |
| 240 | }), |
| 241 | polar({ |
| 242 | client: polarClient, |
| 243 | /// 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 |
| 244 | createCustomerOnSignUp: false, |
| 245 | use: [ |
| 246 | checkout({ |
| 247 | products: [ |
| 248 | { |
| 249 | productId: env.POLAR_PRODUCT_ID |
| 250 | slug: env.POLAR_PRODUCT_SLUG |
| 251 | }, |
| 252 | ], |
| 253 | successUrl: `${env. |
| 254 | authenticatedUsersOnly: true, |
| 255 | }), |
| 256 | portal(), |
| 257 | webhooks({ |
| 258 | secret: env.POLAR_WEBHOOK_SECRET |
| 259 | onSubscriptionCreated: async ( |
| 260 | await invalidateBillingCache(data |
| 261 | }, |
| 262 | onSubscriptionUpdated: async ( |
| 263 | await invalidateBillingCache(data |
| 264 | }, |
| 265 | }), |
| 266 | ], |
| 267 | }), |
| 268 | ], |
| 269 | socialProviders: { |
| 270 | github: { |
| 271 | clientId: env.GITHUB_CLIENT_ID |
| 272 | clientSecret: env.GITHUB_CLIENT_SECRET |
| 273 | }, |
| 274 | google: { |
| 275 | clientId: env.GOOGLE_CLIENT_ID |
| 276 | clientSecret: env.GOOGLE_CLIENT_SECRET |
| 277 | }, |
| 278 | }, |
| 279 | trustedOrigins: env.CORS_ORIGIN |
| 280 | baseURL: env.NEXT_PUBLIC_BASE_URL |
| 281 | }) |
| 282 | |
| 283 | export const getSession = |
| 284 | return auth.api |
| 285 | headers: request ? |
| 286 | }) |
| 287 | } |