UNPKG

autumn-js

Version:
105 lines (103 loc) 3.04 kB
// src/libraries/backend/utils/betterAuth/middlewares.ts import { getSessionFromCtx } from "better-auth/api"; var scopeContainsOrg = ({ options }) => { return options?.customerScope === "organization" || options?.customerScope === "user_and_organization"; }; async function getOrganizationContext(ctx, options) { if (!scopeContainsOrg({ options }) && !options?.identify) { return { activeOrganizationId: null, activeOrganization: null, activeOrganizationEmail: null }; } try { const session = await getSessionFromCtx(ctx); const orgId = session?.session.activeOrganizationId; if (orgId && session) { const [member, organization] = await Promise.all([ ctx.context.adapter.findOne({ model: "member", where: [ { field: "userId", value: session.user.id }, { field: "organizationId", value: orgId } ] }), ctx.context.adapter.findOne({ model: "organization", where: [{ field: "id", value: orgId }] }) ]); if (!member) { return { activeOrganizationId: null, activeOrganization: null, activeOrganizationEmail: null }; } const creatorRole = ctx.context.orgOptions?.creatorRole || "owner"; let ownerUserId = member.role === creatorRole ? member.userId : null; let owner = null; if (member.role !== creatorRole) { const ownerMembers = await ctx.context.adapter.findMany({ model: "member", where: [ { field: "organizationId", value: orgId }, { field: "role", value: creatorRole } ] }); ownerUserId = ownerMembers.length > 0 ? ownerMembers[0].userId : null; } if (ownerUserId) { const ownerUser = await ctx.context.adapter.findOne({ model: "user", where: [{ field: "id", value: ownerUserId }] }); owner = ownerUser; } return { activeOrganizationId: orgId, activeOrganization: organization, activeOrganizationEmail: owner?.email }; } return { activeOrganizationId: null, activeOrganization: null, activeOrganizationEmail: null }; } catch (error) { console.log("[org context error]", error); return { activeOrganizationId: null, activeOrganization: null, activeOrganizationEmail: null }; } } async function getIdentityContext({ orgContext, options, session }) { if (!options?.identify) return null; const orgData = orgContext.activeOrganization?.id ? { ...orgContext.activeOrganization, ownerEmail: orgContext.activeOrganizationEmail } : null; try { const identity = await options.identify({ session, organization: orgData }); return identity; } catch (error) { console.log("[identity context error]", error); return null; } } export { scopeContainsOrg, getOrganizationContext, getIdentityContext };