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