Skip to content

πŸ“¨ The ultimate agentic social media scheduling tool πŸ€–

feat: x-postiz-org override and support debug endpoints on the public API

Enno Gelhausfacc77d8a1cf
diff --git a/apps/backend/src/main.ts b/apps/backend/src/main.ts
index 703a06424..31228ab82 100644
--- a/apps/backend/src/main.ts
+++ b/apps/backend/src/main.ts
@@ -31,6 +31,7 @@ async function start() {
'auth',
'showorg',
'impersonate',
+ 'x-postiz-org',
'x-copilotkit-runtime-client-gql-version',
],
exposedHeaders: [
diff --git a/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts b/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts
index 8d1e0aa95..c6617354b 100644
--- a/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts
+++ b/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts
@@ -47,6 +47,9 @@ import { UsersService } from '@gitroom/nestjs-libraries/database/prisma/users/us
import { SuperAdminGuard } from '@gitroom/backend/services/auth/super.admin.guard';
import { timer } from '@gitroom/helpers/utils/timer';
import { ioRedis } from '@gitroom/nestjs-libraries/redis/redis.service';
+import { AdminStatsService } from '@gitroom/nestjs-libraries/database/prisma/admin-stats/admin-stats.service';
+import { GetOrgActivityDto } from '@gitroom/nestjs-libraries/dtos/analytics/get.org.activity.dto';
+import dayjs from 'dayjs';
@ApiTags('Public API')
@Controller('/public/v1')
@@ -58,7 +61,8 @@ export class PublicIntegrationsController {
private _notificationService: NotificationService,
private _integrationManager: IntegrationManager,
private _refreshIntegrationService: RefreshIntegrationService,
- private _usersService: UsersService
+ private _usersService: UsersService,
+ private _adminStatsService: AdminStatsService
) {}
@Post('/upload')
@@ -317,6 +321,44 @@ export class PublicIntegrationsController {
return this._usersService.getImpersonateUser(name);
}
+ @Get('/debug/posts/:id')
+ async getPostTimeline(
+ @GetOrgFromRequest() org: Organization,
+ @Param('id') id: string
+ ) {
+ Sentry.metrics.count('public_api-request', 1);
+ const timeline = await this._postsService.getPostTimeline(id, org.id);
+
+ if (!timeline) {
+ throw new HttpException({ msg: 'Post not found' }, 404);
+ }
+
+ return timeline;
+ }
+
+ @Get('/debug/channels')
+ async getChannelHealth(@GetOrgFromRequest() org: Organization) {
+ Sentry.metrics.count('public_api-request', 1);
+ return this._integrationService.getChannelHealth(org.id);
+ }
+
+ @Get('/debug/activity')
+ async getOrgActivity(
+ @GetOrgFromRequest() org: Organization,
+ @Query() query: GetOrgActivityDto
+ ) {
+ Sentry.metrics.count('public_api-request', 1);
+
+ const from = query.from ? dayjs(query.from) : dayjs().subtract(30, 'day');
+ const to = query.to ? dayjs(query.to) : dayjs();
+
+ return this._adminStatsService.getOrgActivity({
+ organizationId: org.id,
+ from: from.startOf('day').toDate(),
+ to: to.endOf('day').toDate(),
+ });
+ }
+
@Get('/notifications')
async getNotifications(
@GetOrgFromRequest() org: Organization,
diff --git a/apps/backend/src/services/auth/public.auth.middleware.ts b/apps/backend/src/services/auth/public.auth.middleware.ts
index 36353de88..4436a80df 100644
--- a/apps/backend/src/services/auth/public.auth.middleware.ts
+++ b/apps/backend/src/services/auth/public.auth.middleware.ts
@@ -1,5 +1,6 @@
-import { HttpStatus, Injectable, NestMiddleware } from '@nestjs/common';
+import { HttpStatus, Injectable, Logger, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
+import { Organization } from '@prisma/client';
import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/organizations/organization.service';
import { OAuthService } from '@gitroom/nestjs-libraries/database/prisma/oauth/oauth.service';
import { HttpForbiddenException } from '@gitroom/nestjs-libraries/services/exception.filter';
@@ -7,10 +8,18 @@ import { setSentryUserContext } from '@gitroom/nestjs-libraries/sentry/initializ
@Injectable()
export class PublicAuthMiddleware implements NestMiddleware {
+ private readonly _logger = new Logger(PublicAuthMiddleware.name);
+
constructor(
private _organizationService: OrganizationService,
private _oauthService: OAuthService
) {}
+
+ private setOrg(req: Request, org: Organization) {
+ // @ts-ignore
+ req.org = { ...org, users: [{ users: { role: 'SUPERADMIN' } }] };
+ }
+
async use(req: Request, res: Response, next: NextFunction) {
const auth = (req.headers.authorization ||
req.headers.Authorization) as string;
@@ -19,6 +28,8 @@ export class PublicAuthMiddleware implements NestMiddleware {
return;
}
try {
+ let org: Organization & { subscription?: unknown };
+
if (auth.startsWith('pos_')) {
const authorization = await this._oauthService.getOrgByOAuthToken(auth);
if (!authorization) {
@@ -28,34 +39,51 @@ export class PublicAuthMiddleware implements NestMiddleware {
return;
}
- const org = authorization.organization;
- if (!!process.env.STRIPE_SECRET_KEY && !org.subscription) {
- res
- .status(HttpStatus.UNAUTHORIZED)
- .json({ msg: 'No subscription found' });
- return;
- }
-
- // @ts-ignore
- req.org = { ...org, users: [{ users: { role: 'SUPERADMIN' } }] };
+ org = authorization.organization;
} else {
- const org = await this._organizationService.getOrgByApiKey(auth);
+ org = await this._organizationService.getOrgByApiKey(auth);
if (!org) {
res
.status(HttpStatus.UNAUTHORIZED)
.json({ msg: 'Invalid API key' });
return;
}
+ }
- if (!!process.env.STRIPE_SECRET_KEY && !org.subscription) {
+ if (!!process.env.STRIPE_SECRET_KEY && !org.subscription) {
+ res
+ .status(HttpStatus.UNAUTHORIZED)
+ .json({ msg: 'No subscription found' });
+ return;
+ }
+
+ this.setOrg(req, org);
+
+ const overrideOrgId = (req.headers['x-postiz-org'] as string)?.trim();
+
+ if (overrideOrgId) {
+ if (!(await this._organizationService.hasSuperAdminUser(org.id))) {
+ res.status(HttpStatus.FORBIDDEN).json({ msg: 'Unauthorized' });
+ return;
+ }
+
+ const overrideOrg =
+ await this._organizationService.getOrgByIdWithSubscription(
+ overrideOrgId
+ );
+
+ if (!overrideOrg || overrideOrg.deletedAt) {
res
- .status(HttpStatus.UNAUTHORIZED)
- .json({ msg: 'No subscription found' });
+ .status(HttpStatus.NOT_FOUND)
+ .json({ msg: 'Organization not found' });
return;
}
- // @ts-ignore
- req.org = { ...org, users: [{ users: { role: 'SUPERADMIN' } }] };
+ this.setOrg(req, overrideOrg);
+
+ this._logger.log(
+ `Organization override performed by organization ${org.id}: acting as ${overrideOrg.id} on ${req.method} ${req.path}`
+ );
}
} catch (err) {
throw new HttpForbiddenException();
diff --git a/libraries/nestjs-libraries/src/database/prisma/admin-stats/admin-stats.repository.ts b/libraries/nestjs-libraries/src/database/prisma/admin-stats/admin-stats.repository.ts
index 160825a52..4ef2331af 100644
--- a/libraries/nestjs-libraries/src/database/prisma/admin-stats/admin-stats.repository.ts
+++ b/libraries/nestjs-libraries/src/database/prisma/admin-stats/admin-stats.repository.ts
@@ -6,6 +6,13 @@ export interface StatsParams {
from: Date;
to: Date;
unknownOnly?: boolean;
+ organizationId?: string;
+}
+
+export interface OrgActivityParams {
+ from: Date;
+ to: Date;
+ organizationId: string;
}
// Unknown errors are stored as the serialized error payload, e.g.
@@ -17,6 +24,23 @@ interface PerSocial {
count: number;
}
+interface PerState {
+ state: string;
+ count: number;
+}
+
+export interface OrgActivityResponse {
+ from: string;
+ to: string;
+ organizationId: string;
+ errors: { total: number; perSocial: PerSocial[] };
+ posts: { total: number; perSocial: PerSocial[] };
+ connected: { total: number; perSocial: PerSocial[] };
+ postsByState: PerState[];
+ firstActivityAt: string | null;
+ lastActivityAt: string | null;
+}
+
export interface StatsResponse {
from: string;
to: string;
@@ -47,6 +71,9 @@ export class AdminStatsRepository {
...(params.unknownOnly
? { message: { contains: UNKNOWN_ERROR_TOKEN } }
: {}),
+ ...(params.organizationId
+ ? { organizationId: params.organizationId }
+ : {}),
};
const [total, grouped] = await Promise.all([
@@ -77,6 +104,9 @@ export class AdminStatsRepository {
parentPostId: null,
deletedAt: null,
publishDate: { gte: params.from, lte: params.to },
+ ...(params.organizationId
+ ? { organizationId: params.organizationId }
+ : {}),
};
const [total, grouped] = await Promise.all([
@@ -254,6 +284,9 @@ export class AdminStatsRepository {
const where: Prisma.IntegrationWhereInput = {
deletedAt: null,
createdAt: { gte: params.from, lte: params.to },
+ ...(params.organizationId
+ ? { organizationId: params.organizationId }
+ : {}),
};
const [total, grouped] = await Promise.all([
@@ -276,6 +309,60 @@ export class AdminStatsRepository {
};
}
+ private async postStateStats(params: OrgActivityParams) {
+ const grouped = await this._post.model.post.groupBy({
+ by: ['state'],
+ where: {
+ organizationId: params.organizationId,
+ parentPostId: null,
+ deletedAt: null,
+ publishDate: { gte: params.from, lte: params.to },
+ },
+ _count: { _all: true },
+ });
+
+ return grouped
+ .map((g) => ({ state: g.state as string, count: g._count._all }))
+ .sort((a, b) => b.count - a.count || a.state.localeCompare(b.state));
+ }
+
+ private async activityRange(organizationId: string) {
+ const { _min, _max } = await this._post.model.post.aggregate({
+ where: { organizationId, state: 'PUBLISHED', deletedAt: null },
+ _min: { publishDate: true },
+ _max: { publishDate: true },
+ });
+
+ return {
+ firstActivityAt: _min.publishDate?.toISOString() || null,
+ lastActivityAt: _max.publishDate?.toISOString() || null,
+ };
+ }
+
+ async getOrgActivity(
+ params: OrgActivityParams
+ ): Promise<OrgActivityResponse> {
+ const [errors, posts, connected, postsByState, activity] =
+ await Promise.all([
+ this.errorStats(params),
+ this.postStats(params),
+ this.connectedStats(params),
+ this.postStateStats(params),
+ this.activityRange(params.organizationId),
+ ]);
+
+ return {
+ from: params.from.toISOString(),
+ to: params.to.toISOString(),
+ organizationId: params.organizationId,
+ errors,
+ posts,
+ connected,
+ postsByState,
+ ...activity,
+ };
+ }
+
async getStats(params: StatsParams): Promise<StatsResponse> {
const [errors, posts, accounts, connected, activeOrgsBySource] =
await Promise.all([
diff --git a/libraries/nestjs-libraries/src/database/prisma/admin-stats/admin-stats.service.ts b/libraries/nestjs-libraries/src/database/prisma/admin-stats/admin-stats.service.ts
index e1af176bb..62c024c3a 100644
--- a/libraries/nestjs-libraries/src/database/prisma/admin-stats/admin-stats.service.ts
+++ b/libraries/nestjs-libraries/src/database/prisma/admin-stats/admin-stats.service.ts
@@ -1,6 +1,7 @@
import { Injectable } from '@nestjs/common';
import {
AdminStatsRepository,
+ OrgActivityParams,
StatsParams,
} from '@gitroom/nestjs-libraries/database/prisma/admin-stats/admin-stats.repository';
@@ -11,4 +12,8 @@ export class AdminStatsService {
getStats(params: StatsParams) {
return this._adminStatsRepository.getStats(params);
}
+
+ getOrgActivity(params: OrgActivityParams) {
+ return this._adminStatsRepository.getOrgActivity(params);
+ }
}
diff --git a/libraries/nestjs-libraries/src/database/prisma/integrations/integration.repository.ts b/libraries/nestjs-libraries/src/database/prisma/integrations/integration.repository.ts
index aa241ff24..7dd598008 100644
--- a/libraries/nestjs-libraries/src/database/prisma/integrations/integration.repository.ts
+++ b/libraries/nestjs-libraries/src/database/prisma/integrations/integration.repository.ts
@@ -560,6 +560,91 @@ export class IntegrationRepository {
});
}
+ async getChannelHealth(org: string) {
+ const [integrations, lastPublished, lastErrored] = await Promise.all([
+ this._integration.model.integration.findMany({
+ where: {
+ organizationId: org,
+ },
+ orderBy: {
+ createdAt: 'asc',
+ },
+ select: {
+ id: true,
+ internalId: true,
+ name: true,
+ providerIdentifier: true,
+ type: true,
+ disabled: true,
+ refreshNeeded: true,
+ inBetweenSteps: true,
+ tokenExpiration: true,
+ deletedAt: true,
+ createdAt: true,
+ updatedAt: true,
+ customer: {
+ select: {
+ id: true,
+ name: true,
+ },
+ },
+ },
+ }),
+ this._posts.model.post.findMany({
+ where: {
+ organizationId: org,
+ state: 'PUBLISHED',
+ deletedAt: null,
+ },
+ orderBy: [{ integrationId: 'asc' }, { publishDate: 'desc' }],
+ distinct: ['integrationId'],
+ select: {
+ id: true,
+ integrationId: true,
+ publishDate: true,
+ releaseURL: true,
+ },
+ }),
+ this._posts.model.post.findMany({
+ where: {
+ organizationId: org,
+ state: 'ERROR',
+ deletedAt: null,
+ },
+ orderBy: [{ integrationId: 'asc' }, { updatedAt: 'desc' }],
+ distinct: ['integrationId'],
+ select: {
+ id: true,
+ integrationId: true,
+ updatedAt: true,
+ error: true,
+ },
+ }),
+ ]);
+
+ const publishedByIntegration = new Map(
+ lastPublished.map((post) => [post.integrationId, post])
+ );
+ const erroredByIntegration = new Map(
+ lastErrored.map((post) => [post.integrationId, post])
+ );
+
+ return integrations.map((integration) => {
+ const published = publishedByIntegration.get(integration.id);
+ const errored = erroredByIntegration.get(integration.id);
+
+ return {
+ ...integration,
+ lastPublishedAt: published?.publishDate || null,
+ lastPublishedPostId: published?.id || null,
+ lastPublishedUrl: published?.releaseURL || null,
+ lastErrorAt: errored?.updatedAt || null,
+ lastErrorPostId: errored?.id || null,
+ lastError: errored?.error || null,
+ };
+ });
+ }
+
async disableChannel(org: string, id: string) {
await this._integration.model.integration.update({
where: {
diff --git a/libraries/nestjs-libraries/src/database/prisma/integrations/integration.service.ts b/libraries/nestjs-libraries/src/database/prisma/integrations/integration.service.ts
index 884ce9578..a0f4fe7a4 100644
--- a/libraries/nestjs-libraries/src/database/prisma/integrations/integration.service.ts
+++ b/libraries/nestjs-libraries/src/database/prisma/integrations/integration.service.ts
@@ -154,6 +154,10 @@ export class IntegrationService {
return this._integrationRepository.getIntegrationsList(org);
}
+ getChannelHealth(org: string) {
+ return this._integrationRepository.getChannelHealth(org);
+ }
+
getIntegrationForOrder(id: string, order: string, user: string, org: string) {
return this._integrationRepository.getIntegrationForOrder(
id,
diff --git a/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.ts b/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.ts
index 5741b6a96..1aa9e1538 100644
--- a/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.ts
+++ b/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.ts
@@ -734,6 +734,59 @@ export class PostsRepository {
});
}
+ private get postTimelineSelect() {
+ return {
+ id: true,
+ state: true,
+ publishDate: true,
+ createdAt: true,
+ updatedAt: true,
+ deletedAt: true,
+ releaseId: true,
+ releaseURL: true,
+ error: true,
+ creationMethod: true,
+ group: true,
+ parentPostId: true,
+ } as const;
+ }
+
+ getPostTimeline(id: string, org: string) {
+ return this._post.model.post.findFirst({
+ where: {
+ id,
+ organizationId: org,
+ },
+ select: {
+ ...this.postTimelineSelect,
+ integration: {
+ select: {
+ id: true,
+ name: true,
+ providerIdentifier: true,
+ disabled: true,
+ refreshNeeded: true,
+ deletedAt: true,
+ },
+ },
+ childrenPost: {
+ select: this.postTimelineSelect,
+ orderBy: { publishDate: 'asc' as const },
+ },
+ errors: {
+ select: {
+ id: true,
+ platform: true,
+ message: true,
+ body: true,
+ createdAt: true,
+ },
+ orderBy: { createdAt: 'desc' as const },
+ },
+ },
+ });
+ }
+
findAllExistingCategories() {
return this._popularPosts.model.popularPosts.findMany({
select: {
diff --git a/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts b/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts
index 3467dc981..5d5508bc6 100644
--- a/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts
+++ b/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts
@@ -146,6 +146,10 @@ export class PostsService {
return this._postRepository.getPostById(postId, orgId);
}
+ async getPostTimeline(postId: string, orgId: string) {
+ return this._postRepository.getPostTimeline(postId, orgId);
+ }
+
async updateReleaseId(orgId: string, postId: string, releaseId: string) {
return this._postRepository.updateReleaseId(postId, orgId, releaseId);
}
diff --git a/libraries/nestjs-libraries/src/dtos/analytics/get.org.activity.dto.ts b/libraries/nestjs-libraries/src/dtos/analytics/get.org.activity.dto.ts
new file mode 100644
index 000000000..6311b1d92
--- /dev/null
+++ b/libraries/nestjs-libraries/src/dtos/analytics/get.org.activity.dto.ts
@@ -0,0 +1,11 @@
+import { IsDateString, IsOptional } from 'class-validator';
+
+export class GetOrgActivityDto {
+ @IsOptional()
+ @IsDateString()
+ from?: string;
+
+ @IsOptional()
+ @IsDateString()
+ to?: string;
+}