mirror of
https://github.com/Memo-2023/mana-monorepo.git
synced 2026-05-18 07:49:41 +02:00
✨ feat(admin): add user data dashboard for cross-project data visualization
Add comprehensive admin dashboard to view and manage user data across all projects: Backend: - Add admin endpoints to Chat, Todo, Contacts, Calendar, Picture, Zitare, Presi - Each backend exposes GET/DELETE /api/v1/admin/user-data/:userId - Service-to-service auth via X-Service-Key header Aggregation (mana-core-auth): - GET /api/v1/admin/users - Paginated user list with search - GET /api/v1/admin/users/:userId/data - Aggregated data from all backends - DELETE /api/v1/admin/users/:userId/data - GDPR deletion across all projects Frontend (ManaCore web): - New User Data tab in admin navigation - User search page at /admin/user-data - User detail page with ProjectDataCard components - GDPR deletion dialog with email confirmation Presi: - Migrate user_id from UUID to TEXT for Better Auth compatibility - Add SQL migration script
This commit is contained in:
parent
5b6f231e1a
commit
a2e2a5b73c
57 changed files with 3847 additions and 465 deletions
47
apps/chat/apps/backend/src/admin/admin.controller.ts
Normal file
47
apps/chat/apps/backend/src/admin/admin.controller.ts
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Delete,
|
||||
Param,
|
||||
UseGuards,
|
||||
Logger,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { AdminService } from './admin.service';
|
||||
import { ServiceAuthGuard } from './guards/service-auth.guard';
|
||||
import { UserDataResponse, DeleteUserDataResponse } from './dto/user-data-response.dto';
|
||||
|
||||
/**
|
||||
* Admin controller for user data queries
|
||||
* Used by mana-core-auth aggregation service
|
||||
* Protected by X-Service-Key authentication
|
||||
*/
|
||||
@Controller('api/v1/admin')
|
||||
@UseGuards(ServiceAuthGuard)
|
||||
export class AdminController {
|
||||
private readonly logger = new Logger(AdminController.name);
|
||||
|
||||
constructor(private readonly adminService: AdminService) {}
|
||||
|
||||
/**
|
||||
* Get user data counts for a specific user
|
||||
* GET /api/v1/admin/user-data/:userId
|
||||
*/
|
||||
@Get('user-data/:userId')
|
||||
async getUserData(@Param('userId') userId: string): Promise<UserDataResponse> {
|
||||
this.logger.log(`Admin request: getUserData for userId=${userId}`);
|
||||
return this.adminService.getUserData(userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete all user data (GDPR right to be forgotten)
|
||||
* DELETE /api/v1/admin/user-data/:userId
|
||||
*/
|
||||
@Delete('user-data/:userId')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async deleteUserData(@Param('userId') userId: string): Promise<DeleteUserDataResponse> {
|
||||
this.logger.log(`Admin request: deleteUserData for userId=${userId}`);
|
||||
return this.adminService.deleteUserData(userId);
|
||||
}
|
||||
}
|
||||
12
apps/chat/apps/backend/src/admin/admin.module.ts
Normal file
12
apps/chat/apps/backend/src/admin/admin.module.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { AdminController } from './admin.controller';
|
||||
import { AdminService } from './admin.service';
|
||||
import { DatabaseModule } from '../db/database.module';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, DatabaseModule],
|
||||
controllers: [AdminController],
|
||||
providers: [AdminService],
|
||||
})
|
||||
export class AdminModule {}
|
||||
148
apps/chat/apps/backend/src/admin/admin.service.ts
Normal file
148
apps/chat/apps/backend/src/admin/admin.service.ts
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Inject } from '@nestjs/common';
|
||||
import { NodePgDatabase } from 'drizzle-orm/node-postgres';
|
||||
import { eq, sql, desc } from 'drizzle-orm';
|
||||
import * as schema from '../db/schema';
|
||||
import {
|
||||
UserDataResponse,
|
||||
DeleteUserDataResponse,
|
||||
EntityCount,
|
||||
} from './dto/user-data-response.dto';
|
||||
|
||||
@Injectable()
|
||||
export class AdminService {
|
||||
private readonly logger = new Logger(AdminService.name);
|
||||
|
||||
constructor(
|
||||
@Inject('DATABASE_CONNECTION')
|
||||
private readonly db: NodePgDatabase<typeof schema>
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Get user data counts for a specific user
|
||||
*/
|
||||
async getUserData(userId: string): Promise<UserDataResponse> {
|
||||
this.logger.log(`Getting user data for userId: ${userId}`);
|
||||
|
||||
// Count conversations
|
||||
const conversationsResult = await this.db
|
||||
.select({ count: sql<number>`count(*)::int` })
|
||||
.from(schema.conversations)
|
||||
.where(eq(schema.conversations.userId, userId));
|
||||
const conversationsCount = conversationsResult[0]?.count ?? 0;
|
||||
|
||||
// Count messages (through conversations)
|
||||
const messagesResult = await this.db
|
||||
.select({ count: sql<number>`count(*)::int` })
|
||||
.from(schema.messages)
|
||||
.innerJoin(schema.conversations, eq(schema.messages.conversationId, schema.conversations.id))
|
||||
.where(eq(schema.conversations.userId, userId));
|
||||
const messagesCount = messagesResult[0]?.count ?? 0;
|
||||
|
||||
// Count spaces owned by user
|
||||
const spacesOwnedResult = await this.db
|
||||
.select({ count: sql<number>`count(*)::int` })
|
||||
.from(schema.spaces)
|
||||
.where(eq(schema.spaces.ownerId, userId));
|
||||
const spacesOwnedCount = spacesOwnedResult[0]?.count ?? 0;
|
||||
|
||||
// Count space memberships
|
||||
const spaceMembershipsResult = await this.db
|
||||
.select({ count: sql<number>`count(*)::int` })
|
||||
.from(schema.spaceMembers)
|
||||
.where(eq(schema.spaceMembers.userId, userId));
|
||||
const spaceMembershipsCount = spaceMembershipsResult[0]?.count ?? 0;
|
||||
|
||||
// Count documents (through conversations)
|
||||
const documentsResult = await this.db
|
||||
.select({ count: sql<number>`count(*)::int` })
|
||||
.from(schema.documents)
|
||||
.innerJoin(schema.conversations, eq(schema.documents.conversationId, schema.conversations.id))
|
||||
.where(eq(schema.conversations.userId, userId));
|
||||
const documentsCount = documentsResult[0]?.count ?? 0;
|
||||
|
||||
// Get last activity (most recent conversation or message)
|
||||
const lastConversation = await this.db
|
||||
.select({ updatedAt: schema.conversations.updatedAt })
|
||||
.from(schema.conversations)
|
||||
.where(eq(schema.conversations.userId, userId))
|
||||
.orderBy(desc(schema.conversations.updatedAt))
|
||||
.limit(1);
|
||||
const lastActivityAt = lastConversation[0]?.updatedAt?.toISOString();
|
||||
|
||||
const entities: EntityCount[] = [
|
||||
{ entity: 'conversations', count: conversationsCount, label: 'Conversations' },
|
||||
{ entity: 'messages', count: messagesCount, label: 'Messages' },
|
||||
{ entity: 'spaces_owned', count: spacesOwnedCount, label: 'Spaces (Owned)' },
|
||||
{ entity: 'space_memberships', count: spaceMembershipsCount, label: 'Space Memberships' },
|
||||
{ entity: 'documents', count: documentsCount, label: 'Documents' },
|
||||
];
|
||||
|
||||
const totalCount =
|
||||
conversationsCount +
|
||||
messagesCount +
|
||||
spacesOwnedCount +
|
||||
spaceMembershipsCount +
|
||||
documentsCount;
|
||||
|
||||
return {
|
||||
entities,
|
||||
totalCount,
|
||||
lastActivityAt,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete all user data (GDPR right to be forgotten)
|
||||
*/
|
||||
async deleteUserData(userId: string): Promise<DeleteUserDataResponse> {
|
||||
this.logger.log(`Deleting user data for userId: ${userId}`);
|
||||
|
||||
const deletedCounts: EntityCount[] = [];
|
||||
let totalDeleted = 0;
|
||||
|
||||
// Delete space memberships first
|
||||
const deletedMemberships = await this.db
|
||||
.delete(schema.spaceMembers)
|
||||
.where(eq(schema.spaceMembers.userId, userId))
|
||||
.returning();
|
||||
deletedCounts.push({
|
||||
entity: 'space_memberships',
|
||||
count: deletedMemberships.length,
|
||||
label: 'Space Memberships',
|
||||
});
|
||||
totalDeleted += deletedMemberships.length;
|
||||
|
||||
// Delete spaces owned by user (cascades to members)
|
||||
const deletedSpaces = await this.db
|
||||
.delete(schema.spaces)
|
||||
.where(eq(schema.spaces.ownerId, userId))
|
||||
.returning();
|
||||
deletedCounts.push({
|
||||
entity: 'spaces_owned',
|
||||
count: deletedSpaces.length,
|
||||
label: 'Spaces (Owned)',
|
||||
});
|
||||
totalDeleted += deletedSpaces.length;
|
||||
|
||||
// Delete conversations (cascades to messages and documents)
|
||||
const deletedConversations = await this.db
|
||||
.delete(schema.conversations)
|
||||
.where(eq(schema.conversations.userId, userId))
|
||||
.returning();
|
||||
deletedCounts.push({
|
||||
entity: 'conversations',
|
||||
count: deletedConversations.length,
|
||||
label: 'Conversations',
|
||||
});
|
||||
totalDeleted += deletedConversations.length;
|
||||
|
||||
this.logger.log(`Deleted ${totalDeleted} records for userId: ${userId}`);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
deletedCounts,
|
||||
totalDeleted,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
export interface EntityCount {
|
||||
entity: string;
|
||||
count: number;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface UserDataResponse {
|
||||
entities: EntityCount[];
|
||||
totalCount: number;
|
||||
lastActivityAt?: string;
|
||||
}
|
||||
|
||||
export interface DeleteUserDataResponse {
|
||||
success: boolean;
|
||||
deletedCounts: EntityCount[];
|
||||
totalDeleted: number;
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
import {
|
||||
Injectable,
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
UnauthorizedException,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Request } from 'express';
|
||||
|
||||
/**
|
||||
* Guard for internal service-to-service authentication using X-Service-Key header
|
||||
* Used by mana-core-auth to query user data across backends
|
||||
*/
|
||||
@Injectable()
|
||||
export class ServiceAuthGuard implements CanActivate {
|
||||
private readonly logger = new Logger(ServiceAuthGuard.name);
|
||||
private readonly serviceKey: string;
|
||||
|
||||
constructor(private readonly configService: ConfigService) {
|
||||
this.serviceKey = this.configService.get<string>('ADMIN_SERVICE_KEY', 'dev-admin-key');
|
||||
}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const request = context.switchToHttp().getRequest<Request>();
|
||||
const providedKey = request.headers['x-service-key'] as string;
|
||||
|
||||
if (!providedKey) {
|
||||
this.logger.warn('Missing X-Service-Key header');
|
||||
throw new UnauthorizedException('Missing service key');
|
||||
}
|
||||
|
||||
if (providedKey !== this.serviceKey) {
|
||||
this.logger.warn('Invalid service key provided');
|
||||
throw new UnauthorizedException('Invalid service key');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -9,6 +9,7 @@ import { TemplateModule } from './template/template.module';
|
|||
import { SpaceModule } from './space/space.module';
|
||||
import { DocumentModule } from './document/document.module';
|
||||
import { ModelModule } from './model/model.module';
|
||||
import { AdminModule } from './admin/admin.module';
|
||||
import { HealthModule } from '@manacore/shared-nestjs-health';
|
||||
|
||||
@Module({
|
||||
|
|
@ -37,6 +38,7 @@ import { HealthModule } from '@manacore/shared-nestjs-health';
|
|||
SpaceModule,
|
||||
DocumentModule,
|
||||
ModelModule,
|
||||
AdminModule,
|
||||
HealthModule.forRoot({ serviceName: 'chat-backend' }),
|
||||
],
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue