feat: implement user-specific inventory management with security checks
Test Suite / test (24.15.0) (push) Has been cancelled
Test Suite / test (24.15.0) (push) Has been cancelled
This commit is contained in:
@@ -13,6 +13,7 @@ import { CreateInventoryDto } from './dto/create-inventory.dto';
|
||||
import { UpdateInventoryDto } from './dto/update-inventory.dto';
|
||||
import { InventoryService } from './inventory.service';
|
||||
import { ConsumeInventoryDto } from './dto/consume-inventory.dto';
|
||||
import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||
|
||||
@Controller('inventory')
|
||||
export class InventoryController {
|
||||
@@ -20,45 +21,57 @@ export class InventoryController {
|
||||
|
||||
@Post(':id/consume')
|
||||
consume(
|
||||
@CurrentUser() user: { userId: number },
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body() body: ConsumeInventoryDto,
|
||||
) {
|
||||
return this.inventoryService.consume(id, body);
|
||||
return this.inventoryService.consume(id, user.userId, body);
|
||||
}
|
||||
|
||||
@Get(':id/consumption-history')
|
||||
findConsumptionHistory(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.inventoryService.findConsumptionHistory(id);
|
||||
findConsumptionHistory(
|
||||
@CurrentUser() user: { userId: number },
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
) {
|
||||
return this.inventoryService.findConsumptionHistory(id, user.userId);
|
||||
}
|
||||
|
||||
@Get()
|
||||
findAll(
|
||||
@CurrentUser() user: { userId: number },
|
||||
@Query('location') location?: string,
|
||||
@Query('sort') sort?: string,
|
||||
) {
|
||||
return this.inventoryService.findAll({ location, sort });
|
||||
return this.inventoryService.findAll(user.userId, { location, sort });
|
||||
}
|
||||
|
||||
@Get('expiring')
|
||||
findExpiring() {
|
||||
return this.inventoryService.findExpiring();
|
||||
findExpiring(@CurrentUser() user: { userId: number }) {
|
||||
return this.inventoryService.findExpiring(user.userId);
|
||||
}
|
||||
|
||||
@Post()
|
||||
create(@Body() body: CreateInventoryDto) {
|
||||
return this.inventoryService.create(body);
|
||||
create(
|
||||
@CurrentUser() user: { userId: number },
|
||||
@Body() body: CreateInventoryDto,
|
||||
) {
|
||||
return this.inventoryService.create(user.userId, body);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
update(
|
||||
@CurrentUser() user: { userId: number },
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body() body: UpdateInventoryDto,
|
||||
) {
|
||||
return this.inventoryService.update(id, body);
|
||||
return this.inventoryService.update(id, user.userId, body);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
remove(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.inventoryService.remove(id);
|
||||
remove(
|
||||
@CurrentUser() user: { userId: number },
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
) {
|
||||
return this.inventoryService.remove(id, user.userId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { ForbiddenException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { InventoryService } from './inventory.service';
|
||||
|
||||
describe('InventoryService security', () => {
|
||||
const prismaMock = {
|
||||
inventoryItem: {
|
||||
findUnique: jest.fn(),
|
||||
findMany: jest.fn(),
|
||||
create: jest.fn(),
|
||||
update: jest.fn(),
|
||||
delete: jest.fn(),
|
||||
},
|
||||
inventoryConsumption: {
|
||||
findMany: jest.fn(),
|
||||
create: jest.fn(),
|
||||
},
|
||||
product: {
|
||||
findFirst: jest.fn(),
|
||||
},
|
||||
$transaction: jest.fn(),
|
||||
};
|
||||
|
||||
const service = new InventoryService(prismaMock as any);
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('scopar findAll till userId', async () => {
|
||||
prismaMock.inventoryItem.findMany.mockResolvedValue([]);
|
||||
|
||||
await service.findAll(42, { location: 'fridge', sort: 'bestBeforeAsc' });
|
||||
|
||||
expect(prismaMock.inventoryItem.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({ userId: 42, location: 'fridge' }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('sätter userId vid create', async () => {
|
||||
prismaMock.product.findFirst.mockResolvedValue({ id: 99, ownerId: 42 });
|
||||
prismaMock.inventoryItem.create.mockResolvedValue({ id: 1 });
|
||||
|
||||
await service.create(42, {
|
||||
productId: 99,
|
||||
quantity: 2,
|
||||
unit: 'st',
|
||||
} as any);
|
||||
|
||||
expect(prismaMock.inventoryItem.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({ userId: 42, productId: 99 }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('nekar update om inventoryItem tillhör annan användare', async () => {
|
||||
prismaMock.inventoryItem.findUnique.mockResolvedValue({
|
||||
id: 10,
|
||||
userId: 7,
|
||||
quantity: new Prisma.Decimal(1),
|
||||
});
|
||||
|
||||
await expect(service.update(10, 42, {} as any)).rejects.toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it('nekar remove om inventoryItem tillhör annan användare', async () => {
|
||||
prismaMock.inventoryItem.findUnique.mockResolvedValue({
|
||||
id: 11,
|
||||
userId: 7,
|
||||
quantity: new Prisma.Decimal(1),
|
||||
});
|
||||
|
||||
await expect(service.remove(11, 42)).rejects.toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it('nekar consumption-history om inventoryItem tillhör annan användare', async () => {
|
||||
prismaMock.inventoryItem.findUnique.mockResolvedValue({
|
||||
id: 12,
|
||||
userId: 7,
|
||||
quantity: new Prisma.Decimal(1),
|
||||
});
|
||||
|
||||
await expect(service.findConsumptionHistory(12, 42)).rejects.toThrow(ForbiddenException);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ConsumeInventoryDto } from './dto/consume-inventory.dto';
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { CreateInventoryDto } from './dto/create-inventory.dto';
|
||||
@@ -32,24 +32,27 @@ export class InventoryService {
|
||||
throw new NotFoundException(`Inventory item with id ${id} not found`);
|
||||
}
|
||||
|
||||
private async findInventoryItemByIdOrThrow(id: number) {
|
||||
private async findInventoryItemByIdOrThrow(id: number, userId: number) {
|
||||
const existing = await this.prisma.inventoryItem.findUnique({ where: { id } });
|
||||
if (!existing) {
|
||||
this.throwInventoryItemNotFound(id);
|
||||
}
|
||||
if (existing.userId !== userId) {
|
||||
throw new ForbiddenException(`Inventory item with id ${id} does not belong to current user`);
|
||||
}
|
||||
return existing;
|
||||
}
|
||||
|
||||
private async ensureProductExists(productId: number) {
|
||||
const product = await this.prisma.product.findUnique({ where: { id: productId } });
|
||||
private async ensureProductExists(productId: number, userId: number) {
|
||||
const product = await this.prisma.product.findFirst({ where: { id: productId, ownerId: userId } });
|
||||
if (!product) {
|
||||
throw new NotFoundException('Product not found');
|
||||
throw new NotFoundException('Product not found for current user');
|
||||
}
|
||||
return product;
|
||||
}
|
||||
|
||||
async findAll(query?: InventoryQuery) {
|
||||
const where: Prisma.InventoryItemWhereInput = {};
|
||||
async findAll(userId: number, query?: InventoryQuery) {
|
||||
const where: Prisma.InventoryItemWhereInput = { userId };
|
||||
const orderBy: Prisma.InventoryItemOrderByWithRelationInput[] = [];
|
||||
|
||||
if (query?.location) {
|
||||
@@ -79,8 +82,8 @@ export class InventoryService {
|
||||
});
|
||||
}
|
||||
|
||||
async consume(id: number, data: ConsumeInventoryDto) {
|
||||
const existing = await this.findInventoryItemByIdOrThrow(id);
|
||||
async consume(id: number, userId: number, data: ConsumeInventoryDto) {
|
||||
const existing = await this.findInventoryItemByIdOrThrow(id, userId);
|
||||
|
||||
const currentQuantity = Number(existing.quantity);
|
||||
const newQuantity = Math.max(0, currentQuantity - data.amountUsed);
|
||||
@@ -108,8 +111,8 @@ export class InventoryService {
|
||||
});
|
||||
}
|
||||
|
||||
async findConsumptionHistory(id: number) {
|
||||
await this.findInventoryItemByIdOrThrow(id);
|
||||
async findConsumptionHistory(id: number, userId: number) {
|
||||
await this.findInventoryItemByIdOrThrow(id, userId);
|
||||
|
||||
return this.prisma.inventoryConsumption.findMany({
|
||||
where: {
|
||||
@@ -130,11 +133,12 @@ export class InventoryService {
|
||||
},
|
||||
});
|
||||
}
|
||||
async findExpiring() {
|
||||
async findExpiring(userId: number) {
|
||||
const now = new Date();
|
||||
|
||||
return this.prisma.inventoryItem.findMany({
|
||||
where: {
|
||||
userId,
|
||||
bestBeforeDate: {
|
||||
not: null,
|
||||
gte: now,
|
||||
@@ -147,12 +151,13 @@ export class InventoryService {
|
||||
});
|
||||
}
|
||||
|
||||
async create(data: CreateInventoryDto) {
|
||||
await this.ensureProductExists(data.productId);
|
||||
async create(userId: number, data: CreateInventoryDto) {
|
||||
await this.ensureProductExists(data.productId, userId);
|
||||
|
||||
return this.prisma.inventoryItem.create({
|
||||
data: {
|
||||
...data,
|
||||
userId,
|
||||
quantity: new Prisma.Decimal(data.quantity),
|
||||
location: data.location?.trim() || undefined,
|
||||
brand: data.brand?.trim() || undefined,
|
||||
@@ -173,11 +178,11 @@ export class InventoryService {
|
||||
});
|
||||
}
|
||||
|
||||
async update(id: number, data: UpdateInventoryDto) {
|
||||
await this.findInventoryItemByIdOrThrow(id);
|
||||
async update(id: number, userId: number, data: UpdateInventoryDto) {
|
||||
await this.findInventoryItemByIdOrThrow(id, userId);
|
||||
|
||||
if (typeof data.productId === 'number') {
|
||||
await this.ensureProductExists(data.productId);
|
||||
await this.ensureProductExists(data.productId, userId);
|
||||
}
|
||||
|
||||
const updateData: Prisma.InventoryItemUpdateInput = {};
|
||||
@@ -241,8 +246,8 @@ export class InventoryService {
|
||||
});
|
||||
}
|
||||
|
||||
async remove(id: number) {
|
||||
await this.findInventoryItemByIdOrThrow(id);
|
||||
async remove(id: number, userId: number) {
|
||||
await this.findInventoryItemByIdOrThrow(id, userId);
|
||||
return this.prisma.inventoryItem.delete({ where: { id } });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user