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:
Till-JS 2026-02-11 14:59:18 +01:00
parent 5b6f231e1a
commit a2e2a5b73c
57 changed files with 3847 additions and 465 deletions

View file

@ -0,0 +1,34 @@
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';
@Controller('api/v1/admin')
@UseGuards(ServiceAuthGuard)
export class AdminController {
private readonly logger = new Logger(AdminController.name);
constructor(private readonly adminService: AdminService) {}
@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('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);
}
}

View 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 {}

View file

@ -0,0 +1,159 @@
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>
) {}
async getUserData(userId: string): Promise<UserDataResponse> {
this.logger.log(`Getting user data for userId: ${userId}`);
// Count images
const imagesResult = await this.db
.select({ count: sql<number>`count(*)::int` })
.from(schema.images)
.where(eq(schema.images.userId, userId));
const imagesCount = imagesResult[0]?.count ?? 0;
// Count image generations
const generationsResult = await this.db
.select({ count: sql<number>`count(*)::int` })
.from(schema.imageGenerations)
.where(eq(schema.imageGenerations.userId, userId));
const generationsCount = generationsResult[0]?.count ?? 0;
// Count boards
const boardsResult = await this.db
.select({ count: sql<number>`count(*)::int` })
.from(schema.boards)
.where(eq(schema.boards.userId, userId));
const boardsCount = boardsResult[0]?.count ?? 0;
// Count image likes
const likesResult = await this.db
.select({ count: sql<number>`count(*)::int` })
.from(schema.imageLikes)
.where(eq(schema.imageLikes.userId, userId));
const likesCount = likesResult[0]?.count ?? 0;
// Get last activity
const lastImage = await this.db
.select({ updatedAt: schema.images.updatedAt })
.from(schema.images)
.where(eq(schema.images.userId, userId))
.orderBy(desc(schema.images.updatedAt))
.limit(1);
const lastActivityAt = lastImage[0]?.updatedAt?.toISOString();
const entities: EntityCount[] = [
{ entity: 'images', count: imagesCount, label: 'Images' },
{ entity: 'image_generations', count: generationsCount, label: 'Image Generations' },
{ entity: 'boards', count: boardsCount, label: 'Boards' },
{ entity: 'image_likes', count: likesCount, label: 'Image Likes' },
];
const totalCount = imagesCount + generationsCount + boardsCount + likesCount;
return { entities, totalCount, lastActivityAt };
}
async deleteUserData(userId: string): Promise<DeleteUserDataResponse> {
this.logger.log(`Deleting user data for userId: ${userId}`);
const deletedCounts: EntityCount[] = [];
let totalDeleted = 0;
// Delete image likes
const deletedLikes = await this.db
.delete(schema.imageLikes)
.where(eq(schema.imageLikes.userId, userId))
.returning();
deletedCounts.push({ entity: 'image_likes', count: deletedLikes.length, label: 'Image Likes' });
totalDeleted += deletedLikes.length;
// Delete board items (through boards)
const userBoards = await this.db
.select({ id: schema.boards.id })
.from(schema.boards)
.where(eq(schema.boards.userId, userId));
if (userBoards.length > 0) {
const boardIds = userBoards.map((b) => b.id);
const deletedBoardItems = await this.db
.delete(schema.boardItems)
.where(sql`${schema.boardItems.boardId} IN (${sql.join(boardIds, sql`, `)})`)
.returning();
deletedCounts.push({
entity: 'board_items',
count: deletedBoardItems.length,
label: 'Board Items',
});
totalDeleted += deletedBoardItems.length;
}
// Delete boards
const deletedBoards = await this.db
.delete(schema.boards)
.where(eq(schema.boards.userId, userId))
.returning();
deletedCounts.push({ entity: 'boards', count: deletedBoards.length, label: 'Boards' });
totalDeleted += deletedBoards.length;
// Delete batch generations
const deletedBatchGenerations = await this.db
.delete(schema.batchGenerations)
.where(eq(schema.batchGenerations.userId, userId))
.returning();
deletedCounts.push({
entity: 'batch_generations',
count: deletedBatchGenerations.length,
label: 'Batch Generations',
});
totalDeleted += deletedBatchGenerations.length;
// Delete image generations
const deletedGenerations = await this.db
.delete(schema.imageGenerations)
.where(eq(schema.imageGenerations.userId, userId))
.returning();
deletedCounts.push({
entity: 'image_generations',
count: deletedGenerations.length,
label: 'Image Generations',
});
totalDeleted += deletedGenerations.length;
// Delete images
const deletedImages = await this.db
.delete(schema.images)
.where(eq(schema.images.userId, userId))
.returning();
deletedCounts.push({ entity: 'images', count: deletedImages.length, label: 'Images' });
totalDeleted += deletedImages.length;
// Delete profiles (profile ID is the user ID)
const deletedProfiles = await this.db
.delete(schema.profiles)
.where(eq(schema.profiles.id, userId))
.returning();
deletedCounts.push({ entity: 'profiles', count: deletedProfiles.length, label: 'Profiles' });
totalDeleted += deletedProfiles.length;
this.logger.log(`Deleted ${totalDeleted} records for userId: ${userId}`);
return { success: true, deletedCounts, totalDeleted };
}
}

View file

@ -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;
}

View file

@ -0,0 +1,36 @@
import {
Injectable,
CanActivate,
ExecutionContext,
UnauthorizedException,
Logger,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Request } from 'express';
@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;
}
}

View file

@ -13,6 +13,7 @@ import { GenerateModule } from './generate/generate.module';
import { ExploreModule } from './explore/explore.module';
import { ProfileModule } from './profile/profile.module';
import { BatchModule } from './batch/batch.module';
import { AdminModule } from './admin/admin.module';
@Module({
imports: [
@ -42,6 +43,7 @@ import { BatchModule } from './batch/batch.module';
ExploreModule,
ProfileModule,
BatchModule,
AdminModule,
],
})
export class AppModule {}