Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ GEOCODING_USER_AGENT=PropChain-Backend/1.0 (geocoding)
GEOCODING_TIMEOUT_MS=5000
# GOOGLE_GEOCODING_API_KEY=

# CAPTCHA Configuration
# Set to 'true' only in development environments to bypass CAPTCHA verification
CAPTCHA_BYPASS=false

# Redis (used by Docker Compose and cache module)
REDIS_HOST=localhost
REDIS_PORT=6379
Expand Down
18 changes: 18 additions & 0 deletions pr_body.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
## Changes

### Add proper CSP headers and security middleware (#870)
- Content-Security-Policy, X-Frame-Options, X-Content-Type-Options, Strict-Transport-Security, Referrer-Policy, Permissions-Policy

### Implement proper CORS configuration (#869)
- Use CORS_ORIGINS env var instead of wildcard
- Refuse wildcard origins in production mode

### Fix CAPTCHA verification bypass in non-production mode (#868)
- Require CAPTCHA by default in all environments
- Add CAPTCHA_BYPASS env var for development-only bypass
- Log warning when CAPTCHA is bypassed

### Add distributed tracing via OpenTelemetry TraceInterceptor (#808)
- UUID trace IDs for request tracking
- Request start/completion/failure logging with duration
- Global interceptor for all HTTP requests
102 changes: 85 additions & 17 deletions src/admin/admin.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
// @ts-nocheck

import { Injectable, NotFoundException } from '@nestjs/common';
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../database/prisma.service';
import { BackupService } from '../backup/backup.service';
import { UpdateBackupScheduleDto } from '../backup/dto/backup.dto';
Expand All @@ -22,6 +20,8 @@ import { FraudService } from '../fraud/fraud.service';
import { SessionsService } from '../sessions/sessions.service';
import { TransactionsService } from '../transactions/transactions.service';

const logger = new Logger('AdminService');

@Injectable()
export class AdminService {
constructor(
Expand Down Expand Up @@ -109,9 +109,11 @@ export class AdminService {
async listUsers(query: AdminUsersQueryDto) {
const page = query.page ?? 1;
const limit = query.limit ?? 20;
const skip = (page - 1) * limit;
const skip = (query as any).cursor
? undefined
: (page - 1) * limit;

const where = {
const where: any = {
role: query.role,
OR: query.search
? [
Expand All @@ -122,10 +124,14 @@ export class AdminService {
: undefined,
};

if ((query as any).cursor) {
where.createdAt = { lt: new Date(Buffer.from((query as any).cursor, 'base64').toString()) };
}

const [items, total] = await Promise.all([
this.prisma.user.findMany({
where,
skip,
...(skip !== undefined ? { skip } : {}),
take: limit,
orderBy: { createdAt: 'desc' },
select: {
Expand All @@ -142,13 +148,17 @@ export class AdminService {
this.prisma.user.count({ where }),
]);

return { total, page, limit, items };
const nextCursor = items.length === limit
? Buffer.from((items[items.length - 1] as any).createdAt.toISOString()).toString('base64')
: null;

return { total, page, limit, items, nextCursor, previousCursor: (query as any).cursor || null };
}

async updateUser(userId: string, payload: AdminUpdateUserDto) {
async updateUser(userId: string, payload: AdminUpdateUserDto, actorId?: string) {
const existingUser = await this.prisma.user.findUnique({
where: { id: userId },
select: { role: true },
select: { role: true, email: true },
});

if (!existingUser) {
Expand All @@ -171,10 +181,48 @@ export class AdminService {
},
});

// Audit log for role changes (#886)
if (payload.role && payload.role !== existingUser.role) {
await this.prisma.activityLog
.create({
data: {
userId: actorId ?? 'system',
action: 'ROLE_CHANGE',
entityType: 'USER',
entityId: userId,
description: `Role changed from ${existingUser.role} to ${payload.role} for user ${existingUser.email}`,
metadata: {
previousRole: existingUser.role,
newRole: payload.role,
targetUserId: userId,
},
},
})
.catch((err: unknown) => {
logger.error(`Failed to audit-log role change for ${userId}: ${err}`);
});

await this.sessionsService.revokeAllSessions(userId);
}

// Audit log for block state changes
if (payload.isBlocked !== undefined) {
await this.prisma.activityLog
.create({
data: {
userId: actorId ?? 'system',
action: payload.isBlocked ? 'USER_BLOCKED' : 'USER_UNBLOCKED',
entityType: 'USER',
entityId: userId,
description: `User ${existingUser.email} ${payload.isBlocked ? 'blocked' : 'unblocked'}`,
metadata: { targetUserId: userId, isBlocked: payload.isBlocked },
},
})
.catch((err: unknown) => {
logger.error(`Failed to audit-log block state for ${userId}: ${err}`);
});
}

return updatedUser;
}

Expand All @@ -193,16 +241,22 @@ export class AdminService {
async getModerationQueue(query: ModerationQueueQueryDto) {
const page = query.page ?? 1;
const limit = query.limit ?? 20;
const skip = (page - 1) * limit;
const skip = (query as any).cursor
? undefined
: (page - 1) * limit;

const where = {
const where: any = {
status: query.status ?? PropertyStatus.PENDING,
};

if ((query as any).cursor) {
where.createdAt = { lt: new Date(Buffer.from((query as any).cursor, 'base64').toString()) };
}

const [items, total] = await Promise.all([
this.prisma.property.findMany({
where,
skip,
...(skip !== undefined ? { skip } : {}),
take: limit,
orderBy: { createdAt: 'asc' },
include: {
Expand All @@ -219,7 +273,11 @@ export class AdminService {
this.prisma.property.count({ where }),
]);

return { total, page, limit, items };
const nextCursor = items.length === limit
? Buffer.from((items[items.length - 1] as any).createdAt.toISOString()).toString('base64')
: null;

return { total, page, limit, items, nextCursor, previousCursor: (query as any).cursor || null };
}

async approveProperty(propertyId: string) {
Expand Down Expand Up @@ -292,18 +350,24 @@ export class AdminService {
async monitorTransactions(query: TransactionMonitoringQueryDto) {
const page = query.page ?? 1;
const limit = query.limit ?? 20;
const skip = (page - 1) * limit;
const skip = (query as any).cursor
? undefined
: (page - 1) * limit;

const where = {
const where: any = {
status: query.status,
type: query.type,
propertyId: query.propertyId,
};

if ((query as any).cursor) {
where.createdAt = { lt: new Date(Buffer.from((query as any).cursor, 'base64').toString()) };
}

const [items, total] = await Promise.all([
this.prisma.transaction.findMany({
where,
skip,
...(skip !== undefined ? { skip } : {}),
take: limit,
orderBy: { createdAt: 'desc' },
include: {
Expand All @@ -321,7 +385,11 @@ export class AdminService {
this.prisma.transaction.count({ where }),
]);

return { total, page, limit, items };
const nextCursor = items.length === limit
? Buffer.from((items[items.length - 1] as any).createdAt.toISOString()).toString('base64')
: null;

return { total, page, limit, items, nextCursor, previousCursor: (query as any).cursor || null };
}

async transactionMonitoringSummary() {
Expand Down
3 changes: 3 additions & 0 deletions src/admin/dto/admin.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ export class AdminUpdateUserDto {

@IsOptional()
isVerified?: boolean;

@IsOptional()
isBlocked?: boolean;
}

export class ModerationQueueQueryDto {
Expand Down
Loading
Loading