Files
NianAIGC/lib/server/auth/platform-authorization-store.ts

70 lines
2.4 KiB
TypeScript

import "server-only";
import { getPlatformOrganization, getPlatformUserById } from "@/lib/server/account-store";
import type { PlatformAuthorizationSnapshot } from "@/lib/server/auth/platform-session";
import { isPostgresBackend, queryDatabase } from "@/lib/server/database";
const AUTHORIZATION_SQL = `SELECT
users.id AS account_id,
users.phone AS account_phone,
users.display_name AS account_display_name,
users.role AS account_role,
users.organization_id AS account_organization_id,
users.status AS account_status,
users.session_version AS account_session_version,
organizations.id AS organization_id,
organizations.name AS organization_name,
organizations.status AS organization_status
FROM public.platform_users AS users
LEFT JOIN public.platform_organizations AS organizations
ON organizations.id = users.organization_id
WHERE users.id = $1`;
export async function loadPlatformAuthorizationSnapshot(
accountId: string
): Promise<PlatformAuthorizationSnapshot | null> {
if (!isPostgresBackend()) {
const account = await getPlatformUserById(accountId, { includeDisabled: true });
if (!account) return null;
const organization = account.organizationId
? await getPlatformOrganization(account.organizationId)
: null;
return {
account: {
id: account.id,
phone: account.phone,
displayName: account.displayName,
role: account.role,
organizationId: account.organizationId,
status: account.status,
sessionVersion: account.sessionVersion
},
organization: organization
? { id: organization.id, name: organization.name, status: organization.status }
: null
};
}
const { rows } = await queryDatabase<Record<string, unknown>>(AUTHORIZATION_SQL, [accountId]);
const row = rows[0];
if (!row) return null;
return {
account: {
id: String(row.account_id),
phone: String(row.account_phone),
displayName: String(row.account_display_name),
role: String(row.account_role),
organizationId: row.account_organization_id == null ? undefined : String(row.account_organization_id),
status: String(row.account_status),
sessionVersion: Number(row.account_session_version)
},
organization: row.organization_id == null
? null
: {
id: String(row.organization_id),
name: String(row.organization_name),
status: String(row.organization_status)
}
};
}