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