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,152 @@
import { Injectable, Logger } from '@nestjs/common';
import { Inject } from '@nestjs/common';
import { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { eq, sql, desc, inArray } 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 calendars
const calendarsResult = await this.db
.select({ count: sql<number>`count(*)::int` })
.from(schema.calendars)
.where(eq(schema.calendars.userId, userId));
const calendarsCount = calendarsResult[0]?.count ?? 0;
// Count events
const eventsResult = await this.db
.select({ count: sql<number>`count(*)::int` })
.from(schema.events)
.where(eq(schema.events.userId, userId));
const eventsCount = eventsResult[0]?.count ?? 0;
// Count reminders
const remindersResult = await this.db
.select({ count: sql<number>`count(*)::int` })
.from(schema.reminders)
.where(eq(schema.reminders.userId, userId));
const remindersCount = remindersResult[0]?.count ?? 0;
// Count calendar shares (invited by user)
const sharesResult = await this.db
.select({ count: sql<number>`count(*)::int` })
.from(schema.calendarShares)
.where(eq(schema.calendarShares.invitedBy, userId));
const sharesCount = sharesResult[0]?.count ?? 0;
// Count external calendars
const externalCalendarsResult = await this.db
.select({ count: sql<number>`count(*)::int` })
.from(schema.externalCalendars)
.where(eq(schema.externalCalendars.userId, userId));
const externalCalendarsCount = externalCalendarsResult[0]?.count ?? 0;
// Get last activity
const lastEvent = await this.db
.select({ updatedAt: schema.events.updatedAt })
.from(schema.events)
.where(eq(schema.events.userId, userId))
.orderBy(desc(schema.events.updatedAt))
.limit(1);
const lastActivityAt = lastEvent[0]?.updatedAt?.toISOString();
const entities: EntityCount[] = [
{ entity: 'calendars', count: calendarsCount, label: 'Calendars' },
{ entity: 'events', count: eventsCount, label: 'Events' },
{ entity: 'reminders', count: remindersCount, label: 'Reminders' },
{ entity: 'calendar_shares', count: sharesCount, label: 'Calendar Shares' },
{ entity: 'external_calendars', count: externalCalendarsCount, label: 'External Calendars' },
];
const totalCount =
calendarsCount + eventsCount + remindersCount + sharesCount + externalCalendarsCount;
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 reminders
const deletedReminders = await this.db
.delete(schema.reminders)
.where(eq(schema.reminders.userId, userId))
.returning();
deletedCounts.push({ entity: 'reminders', count: deletedReminders.length, label: 'Reminders' });
totalDeleted += deletedReminders.length;
// Delete calendar shares (where user invited)
const deletedShares = await this.db
.delete(schema.calendarShares)
.where(eq(schema.calendarShares.invitedBy, userId))
.returning();
deletedCounts.push({
entity: 'calendar_shares',
count: deletedShares.length,
label: 'Calendar Shares',
});
totalDeleted += deletedShares.length;
// Delete events (cascades from calendars but also direct)
const deletedEvents = await this.db
.delete(schema.events)
.where(eq(schema.events.userId, userId))
.returning();
deletedCounts.push({ entity: 'events', count: deletedEvents.length, label: 'Events' });
totalDeleted += deletedEvents.length;
// Delete external calendars
const deletedExternalCalendars = await this.db
.delete(schema.externalCalendars)
.where(eq(schema.externalCalendars.userId, userId))
.returning();
deletedCounts.push({
entity: 'external_calendars',
count: deletedExternalCalendars.length,
label: 'External Calendars',
});
totalDeleted += deletedExternalCalendars.length;
// Delete calendars
const deletedCalendars = await this.db
.delete(schema.calendars)
.where(eq(schema.calendars.userId, userId))
.returning();
deletedCounts.push({ entity: 'calendars', count: deletedCalendars.length, label: 'Calendars' });
totalDeleted += deletedCalendars.length;
// Delete device tokens
const deletedDeviceTokens = await this.db
.delete(schema.deviceTokens)
.where(eq(schema.deviceTokens.userId, userId))
.returning();
deletedCounts.push({
entity: 'device_tokens',
count: deletedDeviceTokens.length,
label: 'Device Tokens',
});
totalDeleted += deletedDeviceTokens.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

@ -15,6 +15,7 @@ import { SyncModule } from './sync/sync.module';
import { NetworkModule } from './network/network.module';
import { EmailModule } from './email/email.module';
import { NotificationModule } from './notification/notification.module';
import { AdminModule } from './admin/admin.module';
@Module({
imports: [
@ -48,6 +49,7 @@ import { NotificationModule } from './notification/notification.module';
ShareModule,
SyncModule,
NetworkModule,
AdminModule,
],
})
export class AppModule {}