258 lines
8.3 KiB
TypeScript
258 lines
8.3 KiB
TypeScript
import type { AdminPermissionName } from "@hivegrid/db/admin-permissions";
|
|
import { adminHasPermission } from "@hivegrid/db/admin-rbac.server";
|
|
import {
|
|
createAdminConnectionsService,
|
|
createPrismaAdminConnectionsRepository,
|
|
} from "@hivegrid/db/admin-connections.server";
|
|
import {
|
|
createAdminEmailComposeService,
|
|
createPrismaAdminEmailComposeRepository,
|
|
} from "@hivegrid/db/admin-email-compose.server";
|
|
import {
|
|
createPrismaAdminMailboxRepository,
|
|
} from "@hivegrid/db/admin-mailboxes.server";
|
|
import {
|
|
createAdminMailProviderGateway,
|
|
type AdminMailConnectionProvider,
|
|
type AdminOAuthCredentialBundle,
|
|
} from "@hivegrid/integrations";
|
|
|
|
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
|
|
import {
|
|
extractWebActorIp,
|
|
extractWebActorUserAgent,
|
|
extractWebRequestId,
|
|
} from "~/utils/audit/withAuditContext";
|
|
import { db } from "~/utils/db.server";
|
|
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
|
|
|
|
export type AdminEmailOperatorContext = {
|
|
readonly adminUserId: string;
|
|
readonly email: string;
|
|
readonly locale: string | null;
|
|
readonly canReadAllCommunication: boolean;
|
|
readonly connections: ReturnType<typeof createAdminConnectionsService>;
|
|
readonly mailboxes: ReturnType<typeof createPrismaAdminMailboxRepository>;
|
|
readonly providers: ReturnType<typeof createAdminMailProviderGateway>;
|
|
readonly compose: ReturnType<typeof createAdminEmailComposeService>;
|
|
readonly actor: (reason: string) => {
|
|
readonly adminUserId: string;
|
|
readonly email: string;
|
|
readonly reason: string;
|
|
readonly requestId: string | null;
|
|
readonly ip: string | null;
|
|
readonly userAgent: string | null;
|
|
};
|
|
};
|
|
|
|
export async function runAsAdminEmailOperator<T>(
|
|
request: Request,
|
|
permission:
|
|
| Extract<
|
|
AdminPermissionName,
|
|
| "admin_sales.email.connect"
|
|
| "admin_sales.email.send"
|
|
| "admin_sales.email.track"
|
|
| "admin_sales.email.bulk_send"
|
|
| "admin_sales.communication.read_all"
|
|
>
|
|
| readonly Extract<
|
|
AdminPermissionName,
|
|
| "admin_sales.email.connect"
|
|
| "admin_sales.email.send"
|
|
| "admin_sales.email.track"
|
|
| "admin_sales.email.bulk_send"
|
|
| "admin_sales.communication.read_all"
|
|
>[],
|
|
operation: (context: AdminEmailOperatorContext) => Promise<T>
|
|
): Promise<T> {
|
|
return runAsAdminIdentity(request, permission, async (session) => {
|
|
const admin = await db.adminUser.findFirst({
|
|
where: { id: session.adminUserId, status: "active" },
|
|
select: { id: true, email: true, locale: true },
|
|
});
|
|
if (!admin) throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
|
|
const authorize = async (requested: AdminPermissionName) => {
|
|
if (!(await adminHasPermission(admin.id, requested, db))) {
|
|
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
|
|
}
|
|
};
|
|
const auditBase = {
|
|
adminUserId: admin.id,
|
|
email: admin.email,
|
|
requestId: extractWebRequestId(request),
|
|
ip: extractWebActorIp(request),
|
|
userAgent: extractWebActorUserAgent(request),
|
|
};
|
|
const canReadAllCommunication = await adminHasPermission(
|
|
admin.id,
|
|
"admin_sales.communication.read_all",
|
|
db
|
|
);
|
|
return operation({
|
|
adminUserId: admin.id,
|
|
email: admin.email,
|
|
locale: admin.locale,
|
|
canReadAllCommunication,
|
|
connections: createAdminConnectionsService({
|
|
repository: createPrismaAdminConnectionsRepository(db),
|
|
authorize,
|
|
}),
|
|
mailboxes: createPrismaAdminMailboxRepository(db),
|
|
providers: createAdminMailProviderGateway(),
|
|
compose: createAdminEmailComposeService({
|
|
repository: createPrismaAdminEmailComposeRepository(db),
|
|
authorize,
|
|
}),
|
|
actor: (reason) => ({ ...auditBase, reason }),
|
|
});
|
|
});
|
|
}
|
|
|
|
export async function completeAdminEmailConnection(input: {
|
|
readonly context: AdminEmailOperatorContext;
|
|
readonly provider: AdminMailConnectionProvider;
|
|
readonly code: string;
|
|
}) {
|
|
const grant = await input.context.providers.exchange(
|
|
input.provider,
|
|
input.code
|
|
);
|
|
const reason = "Persönliches Vertriebspostfach verbinden";
|
|
const actor = input.context.actor(reason);
|
|
const connection = await input.context.connections.connect({
|
|
adminUserId: input.context.adminUserId,
|
|
provider: input.provider,
|
|
capability: "email",
|
|
label: grant.account.displayName ?? grant.account.emailAddress,
|
|
externalAccountId: grant.account.externalAccountId,
|
|
externalAccountEmail: grant.account.emailAddress,
|
|
scopes: grant.credentials.scopes,
|
|
tokenExpiresAt: new Date(grant.credentials.expiresAt),
|
|
credentials: grant.credentials,
|
|
actor,
|
|
});
|
|
const mailbox = await input.context.mailboxes.activate({
|
|
adminUserId: input.context.adminUserId,
|
|
connectionId: connection.id,
|
|
provider: input.provider,
|
|
emailAddress: grant.account.emailAddress,
|
|
displayName: grant.account.displayName,
|
|
providerAccountId: grant.account.externalAccountId,
|
|
actor,
|
|
});
|
|
return { connectionId: connection.id, mailboxId: mailbox.id };
|
|
}
|
|
|
|
export async function listAdminEmailConnectionSettings(
|
|
context: AdminEmailOperatorContext
|
|
) {
|
|
const accounts = await db.adminMailbox.findMany({
|
|
where: {
|
|
adminUserId: context.adminUserId,
|
|
archivedAt: null,
|
|
},
|
|
orderBy: [{ normalizedEmail: "asc" }, { id: "asc" }],
|
|
select: {
|
|
id: true,
|
|
connectionId: true,
|
|
emailAddress: true,
|
|
displayName: true,
|
|
status: true,
|
|
lastSyncAt: true,
|
|
connection: {
|
|
select: {
|
|
provider: true,
|
|
healthMessageKey: true,
|
|
},
|
|
},
|
|
},
|
|
});
|
|
return accounts.map((account) => {
|
|
if (
|
|
account.connection.provider !== "google_mail" &&
|
|
account.connection.provider !== "microsoft_mail"
|
|
) {
|
|
throw new Error(
|
|
"admin.sales.email.connections.errors.invalidProvider"
|
|
);
|
|
}
|
|
return {
|
|
id: account.id,
|
|
connectionId: account.connectionId,
|
|
provider: account.connection.provider,
|
|
emailAddress: account.emailAddress,
|
|
displayName: account.displayName,
|
|
status: account.status,
|
|
lastSyncAt: account.lastSyncAt,
|
|
healthMessageKey: account.connection.healthMessageKey,
|
|
};
|
|
});
|
|
}
|
|
|
|
export async function refreshAdminEmailConnection(input: {
|
|
readonly context: AdminEmailOperatorContext;
|
|
readonly connectionId: string;
|
|
readonly provider: AdminMailConnectionProvider;
|
|
}) {
|
|
return input.context.connections.withCredentials(
|
|
input.connectionId,
|
|
input.context.adminUserId,
|
|
async (raw) => {
|
|
const current = credentialBundle(raw);
|
|
const refreshed = await input.context.providers.refresh(
|
|
input.provider,
|
|
current
|
|
);
|
|
return input.context.connections.refresh({
|
|
connectionId: input.connectionId,
|
|
adminUserId: input.context.adminUserId,
|
|
credentials: refreshed,
|
|
scopes: refreshed.scopes,
|
|
tokenExpiresAt: new Date(refreshed.expiresAt),
|
|
actor: input.context.actor("OAuth-Token erneuern"),
|
|
});
|
|
}
|
|
);
|
|
}
|
|
|
|
export async function disconnectAdminEmailConnection(input: {
|
|
readonly context: AdminEmailOperatorContext;
|
|
readonly connectionId: string;
|
|
readonly mailboxId: string;
|
|
readonly provider: AdminMailConnectionProvider;
|
|
}) {
|
|
await input.context.connections.disconnect({
|
|
connectionId: input.connectionId,
|
|
adminUserId: input.context.adminUserId,
|
|
actor: input.context.actor("Persönliches Vertriebspostfach trennen"),
|
|
revokeProviderCredentials: (raw) =>
|
|
input.context.providers.revoke(input.provider, credentialBundle(raw)),
|
|
});
|
|
return input.context.mailboxes.revoke({
|
|
adminUserId: input.context.adminUserId,
|
|
mailboxId: input.mailboxId,
|
|
actor: input.context.actor("Persönliches Vertriebspostfach trennen"),
|
|
});
|
|
}
|
|
|
|
function credentialBundle(
|
|
raw: Readonly<Record<string, unknown>>
|
|
): AdminOAuthCredentialBundle {
|
|
if (
|
|
typeof raw.accessToken !== "string" ||
|
|
typeof raw.refreshToken !== "string" ||
|
|
typeof raw.expiresAt !== "string" ||
|
|
!Array.isArray(raw.scopes) ||
|
|
raw.scopes.some((scope) => typeof scope !== "string")
|
|
) {
|
|
throw new Error("admin.sales.email.connections.errors.invalidCredential");
|
|
}
|
|
return {
|
|
accessToken: raw.accessToken,
|
|
refreshToken: raw.refreshToken,
|
|
expiresAt: raw.expiresAt,
|
|
scopes: raw.scopes as string[],
|
|
};
|
|
}
|