mirror of
https://github.com/Memo-2023/mana-monorepo.git
synced 2026-05-20 00:41:26 +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
34
apps/contacts/apps/backend/src/admin/admin.controller.ts
Normal file
34
apps/contacts/apps/backend/src/admin/admin.controller.ts
Normal 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);
|
||||
}
|
||||
}
|
||||
12
apps/contacts/apps/backend/src/admin/admin.module.ts
Normal file
12
apps/contacts/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 {}
|
||||
152
apps/contacts/apps/backend/src/admin/admin.service.ts
Normal file
152
apps/contacts/apps/backend/src/admin/admin.service.ts
Normal 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 contacts
|
||||
const contactsResult = await this.db
|
||||
.select({ count: sql<number>`count(*)::int` })
|
||||
.from(schema.contacts)
|
||||
.where(eq(schema.contacts.userId, userId));
|
||||
const contactsCount = contactsResult[0]?.count ?? 0;
|
||||
|
||||
// Count tags
|
||||
const tagsResult = await this.db
|
||||
.select({ count: sql<number>`count(*)::int` })
|
||||
.from(schema.contactTags)
|
||||
.where(eq(schema.contactTags.userId, userId));
|
||||
const tagsCount = tagsResult[0]?.count ?? 0;
|
||||
|
||||
// Count notes
|
||||
const notesResult = await this.db
|
||||
.select({ count: sql<number>`count(*)::int` })
|
||||
.from(schema.contactNotes)
|
||||
.where(eq(schema.contactNotes.userId, userId));
|
||||
const notesCount = notesResult[0]?.count ?? 0;
|
||||
|
||||
// Count activities
|
||||
const activitiesResult = await this.db
|
||||
.select({ count: sql<number>`count(*)::int` })
|
||||
.from(schema.contactActivities)
|
||||
.where(eq(schema.contactActivities.userId, userId));
|
||||
const activitiesCount = activitiesResult[0]?.count ?? 0;
|
||||
|
||||
// Get last activity
|
||||
const lastContact = await this.db
|
||||
.select({ updatedAt: schema.contacts.updatedAt })
|
||||
.from(schema.contacts)
|
||||
.where(eq(schema.contacts.userId, userId))
|
||||
.orderBy(desc(schema.contacts.updatedAt))
|
||||
.limit(1);
|
||||
const lastActivityAt = lastContact[0]?.updatedAt?.toISOString();
|
||||
|
||||
const entities: EntityCount[] = [
|
||||
{ entity: 'contacts', count: contactsCount, label: 'Contacts' },
|
||||
{ entity: 'tags', count: tagsCount, label: 'Tags' },
|
||||
{ entity: 'notes', count: notesCount, label: 'Notes' },
|
||||
{ entity: 'activities', count: activitiesCount, label: 'Activities' },
|
||||
];
|
||||
|
||||
const totalCount = contactsCount + tagsCount + notesCount + activitiesCount;
|
||||
|
||||
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 activities
|
||||
const deletedActivities = await this.db
|
||||
.delete(schema.contactActivities)
|
||||
.where(eq(schema.contactActivities.userId, userId))
|
||||
.returning();
|
||||
deletedCounts.push({
|
||||
entity: 'activities',
|
||||
count: deletedActivities.length,
|
||||
label: 'Activities',
|
||||
});
|
||||
totalDeleted += deletedActivities.length;
|
||||
|
||||
// Delete notes
|
||||
const deletedNotes = await this.db
|
||||
.delete(schema.contactNotes)
|
||||
.where(eq(schema.contactNotes.userId, userId))
|
||||
.returning();
|
||||
deletedCounts.push({ entity: 'notes', count: deletedNotes.length, label: 'Notes' });
|
||||
totalDeleted += deletedNotes.length;
|
||||
|
||||
// Get contact IDs for tag deletion
|
||||
const userContacts = await this.db
|
||||
.select({ id: schema.contacts.id })
|
||||
.from(schema.contacts)
|
||||
.where(eq(schema.contacts.userId, userId));
|
||||
const contactIds = userContacts.map((c) => c.id);
|
||||
|
||||
// Delete contact_to_tags
|
||||
if (contactIds.length > 0) {
|
||||
const deletedContactToTags = await this.db
|
||||
.delete(schema.contactToTags)
|
||||
.where(inArray(schema.contactToTags.contactId, contactIds))
|
||||
.returning();
|
||||
deletedCounts.push({
|
||||
entity: 'contact_to_tags',
|
||||
count: deletedContactToTags.length,
|
||||
label: 'Contact Tags',
|
||||
});
|
||||
totalDeleted += deletedContactToTags.length;
|
||||
}
|
||||
|
||||
// Delete tags
|
||||
const deletedTags = await this.db
|
||||
.delete(schema.contactTags)
|
||||
.where(eq(schema.contactTags.userId, userId))
|
||||
.returning();
|
||||
deletedCounts.push({ entity: 'tags', count: deletedTags.length, label: 'Tags' });
|
||||
totalDeleted += deletedTags.length;
|
||||
|
||||
// Delete contacts
|
||||
const deletedContacts = await this.db
|
||||
.delete(schema.contacts)
|
||||
.where(eq(schema.contacts.userId, userId))
|
||||
.returning();
|
||||
deletedCounts.push({ entity: 'contacts', count: deletedContacts.length, label: 'Contacts' });
|
||||
totalDeleted += deletedContacts.length;
|
||||
|
||||
// Delete connected accounts
|
||||
const deletedConnectedAccounts = await this.db
|
||||
.delete(schema.connectedAccounts)
|
||||
.where(eq(schema.connectedAccounts.userId, userId))
|
||||
.returning();
|
||||
deletedCounts.push({
|
||||
entity: 'connected_accounts',
|
||||
count: deletedConnectedAccounts.length,
|
||||
label: 'Connected Accounts',
|
||||
});
|
||||
totalDeleted += deletedConnectedAccounts.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,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;
|
||||
}
|
||||
}
|
||||
|
|
@ -14,6 +14,7 @@ import { DuplicatesModule } from './duplicates/duplicates.module';
|
|||
import { PhotoModule } from './photo/photo.module';
|
||||
import { BatchModule } from './batch/batch.module';
|
||||
import { NetworkModule } from './network/network.module';
|
||||
import { AdminModule } from './admin/admin.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
|
|
@ -38,6 +39,7 @@ import { NetworkModule } from './network/network.module';
|
|||
PhotoModule,
|
||||
BatchModule,
|
||||
NetworkModule,
|
||||
AdminModule,
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue