/
h0tnanny
/
IotPlatform
Обзор
Документация
Войти
/
h0tnanny
/
IotPlatform
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
develop
src/api/controllers/PermissionController.ts
149 строк
5 KB
h0tnanny
refactoring users group
02 фев 2026, 01:00
02 фев 2026, 01:00
c74c0a6
Код
Авторство
О чём код?
import { Response } from 'express'; import { PermissionRepository } from '../../repositories/PermissionRepository'; import { GroupRepository } from '../../repositories/GroupRepository'; import { AuthRequest } from '../../middleware/auth'; export class PermissionController { private readonly permRepo: PermissionRepository; private readonly groupRepo: GroupRepository; constructor() { this.permRepo = new PermissionRepository(); this.groupRepo = new GroupRepository(); } /** * GET /permissions/my-resources — мои ресурсы (где я владелец) */ getMyResources = async (req: AuthRequest, res: Response): Promise<void> => { const resources = await this.permRepo.getResourcesByOwner(req.user!.userId); // Для каждого ресурса загружаем шаринги const result = await Promise.all( resources.map(async (resource) => { const shares = await this.permRepo.getSharesForResource( resource.resource_type, resource.resource_id ); return { ...resource, shares }; }) ); res.json({ data: result }); }; /** * GET /permissions/shared-with-me — ресурсы, расшаренные мне */ getSharedWithMe = async (req: AuthRequest, res: Response): Promise<void> => { const shares = await this.permRepo.getSharedWithUser(req.user!.userId); res.json({ data: shares }); }; /** * POST /permissions/share — поделиться ресурсом */ shareResource = async (req: AuthRequest, res: Response): Promise<void> => { const { resourceType, resourceId, sharedWithType, sharedWithId, permission } = req.body; if (!resourceType || !resourceId || !sharedWithType || !sharedWithId) { res.status(400).json({ error: { code: 'VALIDATION_ERROR', message: 'Необходимы поля: resourceType, resourceId, sharedWithType, sharedWithId', }, }); return; } if (!['workflow', 'equipment'].includes(resourceType)) { res.status(400).json({ error: { code: 'VALIDATION_ERROR', message: 'resourceType должен быть "workflow" или "equipment"' }, }); return; } if (!['user', 'group'].includes(sharedWithType)) { res.status(400).json({ error: { code: 'VALIDATION_ERROR', message: 'sharedWithType должен быть "user" или "group"' }, }); return; } // Проверяем, что пользователь — владелец ресурса или admin const ownerId = await this.permRepo.getOwner(resourceType, resourceId); if (ownerId !== req.user!.userId && req.user!.role !== 'admin') { res.status(403).json({ error: { code: 'FORBIDDEN', message: 'Только владелец может делиться ресурсом' }, }); return; } let perm: 'viewer' | 'editor'; if (sharedWithType === 'group') { const group = await this.groupRepo.findById(sharedWithId); if (!group) { res.status(404).json({ error: { code: 'NOT_FOUND', message: 'Группа не найдена' }, }); return; } if (group.owner_id !== req.user!.userId && req.user!.role !== 'admin') { res.status(403).json({ error: { code: 'FORBIDDEN', message: 'Делиться можно только с группами, которыми вы владеете' }, }); return; } // Уровень доступа при доступе через группу задаётся ролью участника в группе, в resource_shares храним заглушку perm = 'viewer'; } else { perm = permission && ['viewer', 'editor'].includes(permission) ? permission : 'viewer'; } const share = await this.permRepo.shareResource( resourceType, resourceId, sharedWithType, sharedWithId, perm ); res.status(201).json({ data: share }); }; /** * DELETE /permissions/share/:id — отозвать доступ */ removeShare = async (req: AuthRequest, res: Response): Promise<void> => { const { id } = req.params; const success = await this.permRepo.removeShare(id); if (!success) { res.status(404).json({ error: { code: 'NOT_FOUND', message: 'Разрешение не найдено' }, }); return; } res.json({ data: { message: 'Доступ отозван' } }); }; /** * GET /permissions/resource/:type/:id/shares — шаринги конкретного ресурса */ getResourceShares = async (req: AuthRequest, res: Response): Promise<void> => { const { type, id } = req.params; // Проверяем права const ownerId = await this.permRepo.getOwner(type, id); if (ownerId !== req.user!.userId && req.user!.role !== 'admin') { res.status(403).json({ error: { code: 'FORBIDDEN', message: 'Нет прав для просмотра разрешений' }, }); return; } const shares = await this.permRepo.getSharesForResource(type, id); res.json({ data: shares }); }; }