This commit is contained in:
+39
-2
@@ -220,7 +220,7 @@ export async function findOrCreateOAuthUser(input: {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
if (oauthAccount?.user) return toAuthUser(oauthAccount.user)
|
if (oauthAccount?.user) return toAuthUserEnsuringFreeLicense(oauthAccount.user)
|
||||||
|
|
||||||
const existingUser = await prisma.user.findUnique({
|
const existingUser = await prisma.user.findUnique({
|
||||||
where: { email },
|
where: { email },
|
||||||
@@ -242,7 +242,7 @@ export async function findOrCreateOAuthUser(input: {
|
|||||||
select: userSelect()
|
select: userSelect()
|
||||||
})
|
})
|
||||||
|
|
||||||
return toAuthUser(user)
|
return toAuthUserEnsuringFreeLicense(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
const freeLicense = await prisma.license.findUnique({
|
const freeLicense = await prisma.license.findUnique({
|
||||||
@@ -280,6 +280,43 @@ export async function findOrCreateOAuthUser(input: {
|
|||||||
return toAuthUser(user)
|
return toAuthUser(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function toAuthUserEnsuringFreeLicense(user: UserWithAffiliation): Promise<AuthUser> {
|
||||||
|
if (user.userLicenses?.[0]) return toAuthUser(user)
|
||||||
|
|
||||||
|
await ensureFreeLicense(user.id)
|
||||||
|
return (await findUserById(user.id)) ?? toAuthUser(user)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureFreeLicense(userId: string): Promise<void> {
|
||||||
|
const activeLicense = await prisma.userLicense.findFirst({
|
||||||
|
where: {
|
||||||
|
userId,
|
||||||
|
...activeLicenseWhere()
|
||||||
|
},
|
||||||
|
select: { id: true }
|
||||||
|
})
|
||||||
|
|
||||||
|
if (activeLicense) return
|
||||||
|
|
||||||
|
const freeLicense = await prisma.license.findUnique({
|
||||||
|
where: { code: 'FREE' },
|
||||||
|
select: { id: true, defaultDurationDays: true }
|
||||||
|
})
|
||||||
|
if (!freeLicense) throw new Error('FREE license is not configured')
|
||||||
|
|
||||||
|
const licenseStartsAt = new Date()
|
||||||
|
const licenseExpiresAt = calculateLicenseExpiresAt(licenseStartsAt, freeLicense.defaultDurationDays)
|
||||||
|
|
||||||
|
await prisma.userLicense.create({
|
||||||
|
data: {
|
||||||
|
userId,
|
||||||
|
licenseId: freeLicense.id,
|
||||||
|
startsAt: licenseStartsAt,
|
||||||
|
expiresAt: licenseExpiresAt
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
function calculateLicenseExpiresAt(startsAt: Date, durationDays: number | null | undefined): Date | null {
|
function calculateLicenseExpiresAt(startsAt: Date, durationDays: number | null | undefined): Date | null {
|
||||||
if (!durationDays) return null
|
if (!durationDays) return null
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user