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,46 @@
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 cross-service user data management
* All endpoints require service key authentication (X-Service-Key header)
*/
@Controller('api/v1/admin')
@UseGuards(ServiceAuthGuard)
export class AdminController {
private readonly logger = new Logger(AdminController.name);
constructor(private readonly adminService: AdminService) {}
/**
* Get user data summary for this backend
* Called by mana-core-auth admin service to aggregate cross-project data
*/
@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 from this backend (GDPR right to be forgotten)
* Called by mana-core-auth admin service during cross-project deletion
*/
@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 { ServiceAuthGuard } from './guards/service-auth.guard';
@Module({
imports: [ConfigModule],
controllers: [AdminController],
providers: [AdminService, ServiceAuthGuard],
})
export class AdminModule {}

View file

@ -0,0 +1,126 @@
import { Injectable, Logger, Inject } from '@nestjs/common';
import { eq, sql, desc, inArray } from 'drizzle-orm';
import { DATABASE_CONNECTION } from '../db/database.module';
import type { Database } from '../db/connection';
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: Database
) {}
async getUserData(userId: string): Promise<UserDataResponse> {
this.logger.log(`Getting user data for userId: ${userId}`);
// Count decks
const decksResult = await this.db
.select({ count: sql<number>`count(*)::int` })
.from(schema.decks)
.where(eq(schema.decks.userId, userId));
const decksCount = decksResult[0]?.count ?? 0;
// Count slides (through decks)
const userDecks = await this.db
.select({ id: schema.decks.id })
.from(schema.decks)
.where(eq(schema.decks.userId, userId));
let slidesCount = 0;
if (userDecks.length > 0) {
const deckIds = userDecks.map((d) => d.id);
const slidesResult = await this.db
.select({ count: sql<number>`count(*)::int` })
.from(schema.slides)
.where(inArray(schema.slides.deckId, deckIds));
slidesCount = slidesResult[0]?.count ?? 0;
}
// Count shared decks (through decks)
let sharedDecksCount = 0;
if (userDecks.length > 0) {
const deckIds = userDecks.map((d) => d.id);
const sharedResult = await this.db
.select({ count: sql<number>`count(*)::int` })
.from(schema.sharedDecks)
.where(inArray(schema.sharedDecks.deckId, deckIds));
sharedDecksCount = sharedResult[0]?.count ?? 0;
}
// Get last activity
const lastDeck = await this.db
.select({ updatedAt: schema.decks.updatedAt })
.from(schema.decks)
.where(eq(schema.decks.userId, userId))
.orderBy(desc(schema.decks.updatedAt))
.limit(1);
const lastActivityAt = lastDeck[0]?.updatedAt?.toISOString();
const entities: EntityCount[] = [
{ entity: 'decks', count: decksCount, label: 'Decks' },
{ entity: 'slides', count: slidesCount, label: 'Slides' },
{ entity: 'shared_decks', count: sharedDecksCount, label: 'Shared Links' },
];
const totalCount = decksCount + slidesCount + sharedDecksCount;
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;
// Get user's decks first
const userDecks = await this.db
.select({ id: schema.decks.id })
.from(schema.decks)
.where(eq(schema.decks.userId, userId));
if (userDecks.length > 0) {
const deckIds = userDecks.map((d) => d.id);
// Delete shared decks
const deletedShared = await this.db
.delete(schema.sharedDecks)
.where(inArray(schema.sharedDecks.deckId, deckIds))
.returning();
deletedCounts.push({
entity: 'shared_decks',
count: deletedShared.length,
label: 'Shared Links',
});
totalDeleted += deletedShared.length;
// Delete slides (cascade should handle this, but let's be explicit)
const deletedSlides = await this.db
.delete(schema.slides)
.where(inArray(schema.slides.deckId, deckIds))
.returning();
deletedCounts.push({ entity: 'slides', count: deletedSlides.length, label: 'Slides' });
totalDeleted += deletedSlides.length;
}
// Delete decks
const deletedDecks = await this.db
.delete(schema.decks)
.where(eq(schema.decks.userId, userId))
.returning();
deletedCounts.push({ entity: 'decks', count: deletedDecks.length, label: 'Decks' });
totalDeleted += deletedDecks.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,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;
}
}

View file

@ -5,6 +5,7 @@ import { DeckModule } from './deck/deck.module';
import { SlideModule } from './slide/slide.module';
import { ThemeModule } from './theme/theme.module';
import { ShareModule } from './share/share.module';
import { AdminModule } from './admin/admin.module';
import { HealthModule } from '@manacore/shared-nestjs-health';
@Module({
@ -18,6 +19,7 @@ import { HealthModule } from '@manacore/shared-nestjs-health';
SlideModule,
ThemeModule,
ShareModule,
AdminModule,
HealthModule.forRoot({ serviceName: 'presi-backend' }),
],
})

View file

@ -0,0 +1,20 @@
-- Migration: Change user_id from UUID to TEXT
-- This allows compatibility with Better Auth nanoid-based user IDs
-- Step 1: Add a temporary column with the new type
ALTER TABLE decks ADD COLUMN user_id_new TEXT;
-- Step 2: Copy and convert existing data (UUID to TEXT)
UPDATE decks SET user_id_new = user_id::text WHERE user_id IS NOT NULL;
-- Step 3: Drop the old column
ALTER TABLE decks DROP COLUMN user_id;
-- Step 4: Rename the new column
ALTER TABLE decks RENAME COLUMN user_id_new TO user_id;
-- Step 5: Add NOT NULL constraint
ALTER TABLE decks ALTER COLUMN user_id SET NOT NULL;
-- Step 6: Add index for performance
CREATE INDEX IF NOT EXISTS decks_user_id_idx ON decks(user_id);

View file

@ -6,7 +6,7 @@ import { sharedDecks } from './shared-decks.schema';
export const decks = pgTable('decks', {
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id').notNull(),
userId: text('user_id').notNull(), // TEXT for Better Auth nanoid user IDs
title: text('title').notNull(),
description: text('description'),
themeId: uuid('theme_id').references(() => themes.id),