Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | 12x 12x 12x 18x 18x 11x 11x 11x 11x 11x 1x 1x 10x 1x 1x 9x 9x 1x 1x 8x 1x 1x 7x 3x 4x 4x 3x 3x 1x | import { CanActivate, ExecutionContext, Injectable, NotFoundException, ForbiddenException, Logger } from '@nestjs/common';
import { PrismaService } from '@app/modules/prisma/prisma.service';
@Injectable()
export class ListingOwnerGuard implements CanActivate {
private readonly logger = new Logger(ListingOwnerGuard.name);
constructor(private readonly prisma: PrismaService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const user = request.user;
const listingIdRaw = request.params?.id;
const listingId = Number(listingIdRaw);
// Validate user context
if (!user || !user.id) {
this.logger.warn('ListingOwnerGuard: No authenticated user');
throw new ForbiddenException('Authentication required');
}
// Validate listing ID
if (!listingId || isNaN(listingId)) {
this.logger.warn('ListingOwnerGuard: Invalid listing ID');
throw new ForbiddenException('Invalid listing ID');
}
// Fetch listing with ownership info
const listing = await this.prisma.client.listing.findUnique({
where: { id: listingId },
select: {
userId: true,
deletedAt: true,
}
});
if (!listing) {
this.logger.warn(`ListingOwnerGuard: Listing ${listingId} not found`);
throw new NotFoundException('Listing not found');
}
// Don't allow operations on soft-deleted listings (unless admin)
if (listing.deletedAt && user.role !== 'ADMIN' && user.role !== 'MODERATOR') {
this.logger.warn(`ListingOwnerGuard: Attempted access to deleted listing ${listingId}`);
throw new ForbiddenException('This listing has been deleted');
}
// Admin/Moderator has full access
if (user.role === 'ADMIN' || user.role === 'MODERATOR') {
return true;
}
// Check ownership
const userId = user.userId ?? user.id;
if (listing.userId !== userId) {
this.logger.warn(
`ListingOwnerGuard: User ${userId} attempted to access listing ${listingId} owned by ${listing.userId}`
);
throw new ForbiddenException('You do not have permission to access this listing');
}
return true;
}
}
|