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