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
60 changes: 60 additions & 0 deletions server/__tests__/offices.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,64 @@ describe('PUT /api/offices/:officeId', () => {
expect(rows[0].name).toBe('Renamed Office');
expect(rows[0].address).toBe('addr2');
});

it('returns 403 when a different user tries to update someone else\'s office (IDOR)', async () => {
const owner = await registerDirector(app);
const stranger = await registerDirector(app);

const created = await request(app)
.post('/api/offices')
.set('Authorization', `Bearer ${owner.token}`)
.send({ name: 'Owner Office', address: 'private addr' });
const officeId = created.body.id;

const res = await request(app)
.put(`/api/offices/${officeId}`)
.set('Authorization', `Bearer ${stranger.token}`)
.send({ name: 'HACKED', address: 'evil addr' });

expect(res.status).toBe(403);

const [rows] = await db.query('SELECT name FROM offices WHERE id = ?', [officeId]);
expect(rows[0].name).toBe('Owner Office');
});
});

describe('DELETE /api/offices/:officeId', () => {
it('owner can delete own office', async () => {
const owner = await registerDirector(app);
const created = await request(app)
.post('/api/offices')
.set('Authorization', `Bearer ${owner.token}`)
.send({ name: 'To be deleted' });
const officeId = created.body.id;

const res = await request(app)
.delete(`/api/offices/${officeId}`)
.set('Authorization', `Bearer ${owner.token}`);

expect([200, 204]).toContain(res.status);
const [rows] = await db.query('SELECT id FROM offices WHERE id = ?', [officeId]);
expect(rows.length).toBe(0);
});

it('returns 403 when a stranger tries to delete someone else\'s office (IDOR)', async () => {
const owner = await registerDirector(app);
const stranger = await registerDirector(app);

const created = await request(app)
.post('/api/offices')
.set('Authorization', `Bearer ${owner.token}`)
.send({ name: 'Owner Office 2' });
const officeId = created.body.id;

const res = await request(app)
.delete(`/api/offices/${officeId}`)
.set('Authorization', `Bearer ${stranger.token}`);

expect(res.status).toBe(403);

const [rows] = await db.query('SELECT id FROM offices WHERE id = ?', [officeId]);
expect(rows.length).toBe(1);
});
});
35 changes: 31 additions & 4 deletions server/controllers/officeController.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,23 @@ const Office = require('../models/office');
const { formatOfficeResponse } = require('../utils/formatters');
const db = require('../db');

/**
* Проверяет, что текущий пользователь — владелец офиса.
* Возвращает true для системной роли 'owner' или если offices.owner_id === user.id.
* Используется для гейта операций PUT/DELETE на офисе.
*/
async function isOfficeOwner(user, officeId) {
if (!user || !user.id || !officeId) return false;
const role = String(user.role || '').toLowerCase();
if (role === 'owner') return true;
const [rows] = await db.query(
'SELECT owner_id FROM offices WHERE id = ? LIMIT 1',
[officeId]
);
if (!rows[0]) return false;
return Number(rows[0].owner_id) === Number(user.id);
}

const officeController = {
/**
* Получить данные о выручке офисов за указанный период
Expand Down Expand Up @@ -219,12 +236,17 @@ const officeController = {
try {
const { officeId } = req.params;
const { name, address, contact_phone, website } = req.body;

const existingOffice = await Office.getById(officeId);
if (!existingOffice) {
return res.status(404).json({ success: false, message: 'Офис не найден' });
}


const allowed = await isOfficeOwner(req.user, officeId);
if (!allowed) {
return res.status(403).json({ success: false, message: 'Доступ запрещён' });
}

if (!name) {
return res.status(400).json({ success: false, message: 'Название офиса обязательно' });
}
Expand All @@ -247,12 +269,17 @@ const officeController = {
async deleteOffice(req, res) {
try {
const { officeId } = req.params;

const office = await Office.getById(officeId);
if (!office) {
return res.status(404).json({ success: false, message: 'Офис не найден' });
}


const allowed = await isOfficeOwner(req.user, officeId);
if (!allowed) {
return res.status(403).json({ success: false, message: 'Доступ запрещён' });
}

await Office.delete(officeId);
return res.json({ success: true });
} catch (error) {
Expand Down
Loading