-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathMultiTenancyTrait.php
More file actions
797 lines (708 loc) · 27.9 KB
/
MultiTenancyTrait.php
File metadata and controls
797 lines (708 loc) · 27.9 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
<?php
/**
* Multi-Tenancy Trait
*
* This trait provides reusable multi-tenancy and RBAC functionality for mappers.
* It handles organisation filtering, permission checks, and security validation.
*
* @category Trait
* @package OCA\OpenRegister\Db
*
* @author Conduction Development Team <info@conduction.nl>
* @copyright 2024 Conduction B.V.
* @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12
*
* @version GIT: <git_id>
*
* @link https://www.OpenRegister.app
*/
namespace OCA\OpenRegister\Db;
use Exception;
use OCP\AppFramework\Db\Entity;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IAppConfig;
use OCP\Security\ISecureRandom;
use Psr\Log\LoggerInterface;
use DateTime;
use DateInterval;
use Symfony\Component\HttpFoundation\Response;
use OCP\AppFramework\Http\JSONResponse;
/**
* Trait MultiTenancyTrait
*
* Provides common multi-tenancy and RBAC functionality that can be mixed into mappers.
*
* Requirements for using this trait:
* - The entity must have an 'organisation' property (string UUID)
* - The mapper must inject OrganisationMapper ($this->organisationMapper)
* - The mapper must inject IGroupManager ($this->groupManager - for RBAC)
* - The mapper must inject IUserSession ($this->userSession - for current user)
* - The mapper must have access to IDBConnection via $this->db (from QBMapper parent)
*
* Optional dependencies for advanced features:
* - IAppConfig ($this->appConfig) - for multitenancy config settings
* Classes should define this property themselves if needed (e.g., private IAppConfig $appConfig)
* - LoggerInterface ($this->logger) - for debug logging
* Classes should define this property themselves if needed (e.g., private LoggerInterface $logger)
*
* Note: The trait does not declare the $appConfig and $logger properties to avoid conflicts.
* Classes using this trait should declare these properties with their preferred visibility
* (private/protected) and nullability. The trait methods check isset() before using them.
*
* @package OCA\OpenRegister\Db
*/
trait MultiTenancyTrait
{
/**
* Get the active organisation UUID from the session.
*
* Falls back to the default organisation from config if no active organisation is set.
* Automatically sets the default as active if user has no active organisation.
*
* @return string|null The active organisation UUID or default organisation UUID, or null if neither set
*/
protected function getActiveOrganisationUuid(): ?string
{
if (isset($this->logger) === true) {
$this->logger->info(
message: '[MultiTenancyTrait] 🔹 MultiTenancyTrait: getActiveOrganisationUuid called',
context: ['file' => __FILE__, 'line' => __LINE__]
);
}
// Get current user.
if (isset($this->userSession) === false) {
return null;
}
$user = $this->userSession->getUser();
if ($user === null) {
return $this->getDefaultOrganisationUuid();
}
// Use OrganisationMapper to get active org with automatic fallback to default.
if (isset($this->organisationMapper) === true) {
$organisationMapper = $this->organisationMapper;
if (isset($this->logger) === true) {
$this->logger->info(
message: '[MultiTenancyTrait] Calling getActiveOrganisationWithFallback for user: '.$user->getUID(),
context: ['file' => __FILE__, 'line' => __LINE__]
);
}
// @psalm-suppress UndefinedMethod
return $organisationMapper->getActiveOrganisationWithFallback($user->getUID());
}
// Fallback if mapper not available.
return $this->getDefaultOrganisationUuid();
}//end getActiveOrganisationUuid()
/**
* Get default organisation UUID from config
*
* This method provides a fallback for when OrganisationMapper is not available.
* Prefer using OrganisationMapper::getDefaultOrganisationFromConfig() when possible.
*
* @return string|null Default organisation UUID or null if not set
*/
protected function getDefaultOrganisationUuid(): ?string
{
// Prefer using OrganisationMapper if available.
if (isset($this->organisationMapper) === true) {
$organisationMapper = $this->organisationMapper;
// @psalm-suppress UndefinedMethod
return $organisationMapper->getDefaultOrganisationFromConfig();
}
// Fallback to direct config access if mapper not available.
if (isset($this->appConfig) === false) {
return null;
}
// Try direct config key (newer format).
$defaultOrg = $this->appConfig->getValueString('openregister', 'defaultOrganisation', '');
if (empty($defaultOrg) === false) {
return $defaultOrg;
}
// Try nested organisation config (legacy format).
$organisationConfig = $this->appConfig->getValueString('openregister', 'organisation', '');
if (empty($organisationConfig) === false) {
$storedData = json_decode($organisationConfig, true);
if (isset($storedData['default_organisation']) === true) {
return $storedData['default_organisation'];
}
}
return null;
}//end getDefaultOrganisationUuid()
/**
* Get active organisation UUIDs (active + all parents)
*
* Returns array of organisation UUIDs that the current user can access.
* Includes the active organisation and all parent organisations in the hierarchy.
* Falls back to default organisation if no active organisation is set.
* Used for filtering queries to allow access to parent resources.
*
* @return (mixed|null|string)[] Array of organisation UUIDs
*
* @psalm-return array{0?: mixed|null|string,...}
*/
protected function getActiveOrganisationUuids(): array
{
$activeOrgUuid = $this->getActiveOrganisationUuid();
if ($activeOrgUuid === null) {
return [];
}
// If we have OrganisationMapper, get the full hierarchy (active + parents).
if (isset($this->organisationMapper) === true) {
try {
$organisationMapper = $this->organisationMapper;
// @psalm-suppress UndefinedMethod
$uuids = $organisationMapper->getOrganisationHierarchy($activeOrgUuid);
if (empty($uuids) === false) {
return $uuids;
}
} catch (\Exception $e) {
// Fall back to just the active org.
if (isset($this->logger) === true) {
$this->logger->warning(
message: '[MultiTenancyTrait] Failed to get organisation hierarchy: '.$e->getMessage(),
context: ['file' => __FILE__, 'line' => __LINE__, 'activeOrgUuid' => $activeOrgUuid]
);
}
}
}//end if
// Fall back to just the active organisation.
return [$activeOrgUuid];
}//end getActiveOrganisationUuids()
/**
* Get the current user ID.
*
* @return string|null The current user ID or null if no user is logged in
*/
protected function getCurrentUserId(): ?string
{
if (isset($this->userSession) === false) {
return null;
}
$user = $this->userSession->getUser();
if (($user !== null) === false) {
return null;
}
return $user->getUID();
}//end getCurrentUserId()
/**
* Check if the current user is an admin.
*
* @return bool True if the current user is an admin, false otherwise
*/
protected function isCurrentUserAdmin(): bool
{
$userId = $this->getCurrentUserId();
if ($userId === null) {
return false;
}
if (isset($this->groupManager) === false) {
return false;
}
return $this->groupManager->isAdmin($userId);
}//end isCurrentUserAdmin()
/**
* Apply organisation filter to a query builder with advanced multi-tenancy support.
*
* This method provides comprehensive organisation filtering including:
* - Hierarchical organisation support (active org + all parents)
* - Published entity bypass for multi-tenancy (works for objects, schemas, registers)
* - Admin override capabilities
* - System default organisation special handling
* - NULL organisation legacy data access for admins
* - Unauthenticated request handling
*
* Features:
* 1. Hierarchical Access: Users see entities from their active org AND parent orgs
* 2. Published Entities: Can bypass multi-tenancy if configured (any table with published/depublished columns)
* 3. Admin Override: Admins can see all entities if enabled in config
* 4. Default Org: Special behavior for system-wide default organisation
* 5. Legacy Data: Admins can access NULL organisation entities
*
* Example hierarchy:
* - Organisation A (root)
* - Organisation B (parent: A)
* - Organisation C (parent: B)
* When C is active, entities from A, B, and C are visible.
*
* @param IQueryBuilder $qb The query builder
* @param string $columnName The column name for organisation
* @param bool $allowNullOrg Whether admins can see NULL organisation entities
* @param string $tableAlias Optional table alias
* @param bool $multiTenancyEnabled Whether multitenancy is enabled (default: true)
*
* @return void
*
* @SuppressWarnings(PHPMD.BooleanArgumentFlag) Flags control multitenancy filtering behavior
* @SuppressWarnings(PHPMD.NPathComplexity)
* NPath from parameter combinations
*/
protected function applyOrganisationFilter(
IQueryBuilder $qb,
string $columnName='organisation',
bool $allowNullOrg=false,
string $tableAlias='',
bool $multiTenancyEnabled=true
): void {
if ($this->shouldSkipFiltering(multiTenancyEnabled: $multiTenancyEnabled) === true) {
return;
}
$user = $this->getUserFromSession();
if ($user === null && isset($this->userSession) === false) {
return;
}
$activeOrgUuids = $this->getActiveOrganisationUuids();
$organisationColumn = $this->buildQualifiedColumnName(columnName: $columnName, tableAlias: $tableAlias);
if (empty($activeOrgUuids) === true) {
$this->applyNoActiveOrgFilter(
qb: $qb,
user: $user,
allowNullOrg: $allowNullOrg,
organisationColumn: $organisationColumn
);
return;
}
$this->applyActiveOrgFilter(
qb: $qb,
user: $user,
activeOrgUuids: $activeOrgUuids,
allowNullOrg: $allowNullOrg,
organisationColumn: $organisationColumn
);
}//end applyOrganisationFilter()
/**
* Check if filtering should be skipped entirely
*
* @param bool $multiTenancyEnabled Whether multitenancy is enabled via parameter
*
* @return bool True if filtering should be skipped
*/
private function shouldSkipFiltering(bool $multiTenancyEnabled): bool
{
if ($multiTenancyEnabled === false) {
return true;
}
if (isset($this->appConfig) === false) {
return false;
}
$multitenancyConfig = $this->appConfig->getValueString('openregister', 'multitenancy', '');
if (empty($multitenancyConfig) === true) {
return false;
}
$multitenancyData = json_decode($multitenancyConfig, true);
return ($multitenancyData['enabled'] ?? true) === false;
}//end shouldSkipFiltering()
/**
* Get the current user from the session
*
* @return mixed|null The user object or null
*/
private function getUserFromSession(): mixed
{
if (isset($this->userSession) === false) {
if (($this->logger ?? null) !== null) {
$this->logger->debug(
message: '[MultiTenancyTrait] UserSession not available, skipping filter',
context: ['file' => __FILE__, 'line' => __LINE__]
);
}
return null;
}
$user = $this->userSession->getUser();
if ($user === null && isset($this->logger) === true) {
$this->logger->debug(
message: '[MultiTenancyTrait] Unauthenticated request, no automatic access',
context: ['file' => __FILE__, 'line' => __LINE__]
);
}
return $user;
}//end getUserFromSession()
/**
* Build a qualified column name with optional table alias
*
* @param string $columnName Column name
* @param string $tableAlias Optional table alias
*
* @return string Qualified column name
*/
private function buildQualifiedColumnName(string $columnName, string $tableAlias): string
{
if ($tableAlias !== null && $tableAlias !== '') {
return $tableAlias.'.'.$columnName;
}
return $columnName;
}//end buildQualifiedColumnName()
/**
* Check if user is an admin
*
* @param mixed $user The user object
*
* @return bool True if user is admin
*/
private function isUserAdmin(mixed $user): bool
{
if ($user === null || isset($this->groupManager) === false) {
return false;
}
$userGroups = $this->groupManager->getUserGroupIds($user);
return in_array('admin', $userGroups);
}//end isUserAdmin()
/**
* Check if admin override is enabled
*
* @return bool True if admin override is enabled
*/
private function isAdminOverrideEnabled(): bool
{
if (isset($this->appConfig) === false) {
return false;
}
$multitenancyConfig = $this->appConfig->getValueString('openregister', 'multitenancy', '');
if (empty($multitenancyConfig) === true) {
return false;
}
$multitenancyData = json_decode($multitenancyConfig, true);
return $multitenancyData['adminOverride'] ?? false;
}//end isAdminOverrideEnabled()
/**
* Apply filter when no active organisation is set
*
* @param IQueryBuilder $qb Query builder
* @param mixed $user User object
* @param bool $allowNullOrg Allow NULL organisation
* @param string $organisationColumn Organisation column name
*
* @return void
*
* @SuppressWarnings(PHPMD.BooleanArgumentFlag) Flags control multitenancy filtering behavior
*/
private function applyNoActiveOrgFilter(
IQueryBuilder $qb,
mixed $user,
bool $allowNullOrg,
string $organisationColumn
): void {
$isAdmin = $this->isUserAdmin(user: $user);
if ($isAdmin === true && $this->isAdminOverrideEnabled() === true) {
return;
}
// Allow null organisation entities when explicitly permitted by the caller.
// This is used for system-wide resources like Registers and Schemas.
if ($allowNullOrg === true) {
$qb->andWhere($qb->expr()->isNull($organisationColumn));
return;
}
// No active org and no null-org permission: block all results.
$qb->andWhere('1 = 0');
}//end applyNoActiveOrgFilter()
/**
* Apply filter when active organisation(s) are set
*
* @param IQueryBuilder $qb Query builder
* @param mixed $user User object
* @param array $activeOrgUuids Active organisation UUIDs
* @param bool $allowNullOrg Allow NULL organisation
* @param string $organisationColumn Organisation column name
*
* @return void
*
* @SuppressWarnings(PHPMD.BooleanArgumentFlag) Flags control multitenancy filtering behavior
*/
private function applyActiveOrgFilter(
IQueryBuilder $qb,
mixed $user,
array $activeOrgUuids,
bool $allowNullOrg,
string $organisationColumn
): void {
$isAdmin = $this->isUserAdmin(user: $user);
if ($isAdmin === true && $this->isAdminOverrideEnabled() === true) {
return;
}
$orgConditions = $qb->expr()->orX();
$this->addOrganisationConditions(
qb: $qb,
orgConditions: $orgConditions,
activeOrgUuids: $activeOrgUuids,
organisationColumn: $organisationColumn
);
// Allow null organisation entities when explicitly permitted by the caller.
// This is used for system-wide resources like Registers and Schemas.
if ($allowNullOrg === true) {
$orgConditions->add($qb->expr()->isNull($organisationColumn));
}
$qb->andWhere($orgConditions);
}//end applyActiveOrgFilter()
/**
* Add organisation conditions to the query
*
* @param IQueryBuilder $qb Query builder
* @param mixed $orgConditions Organisation conditions object
* @param array $activeOrgUuids Active organisation UUIDs
* @param string $organisationColumn Organisation column name
*
* @return void
*/
private function addOrganisationConditions(
IQueryBuilder $qb,
mixed $orgConditions,
array $activeOrgUuids,
string $organisationColumn
): void {
$directActiveOrgUuid = $this->getActiveOrganisationUuid();
if ($directActiveOrgUuid !== null) {
$orgConditions->add(
$qb->expr()->eq(
$organisationColumn,
$qb->createNamedParameter($directActiveOrgUuid, IQueryBuilder::PARAM_STR)
)
);
$parentOrgs = array_filter(
$activeOrgUuids,
function ($uuid) use ($directActiveOrgUuid) {
return $uuid !== $directActiveOrgUuid;
}
);
if (count($parentOrgs) > 0) {
$orgConditions->add(
$qb->expr()->in(
$organisationColumn,
$qb->createNamedParameter($parentOrgs, IQueryBuilder::PARAM_STR_ARRAY)
)
);
}
return;
}//end if
$orgConditions->add(
$qb->expr()->in(
$organisationColumn,
$qb->createNamedParameter($activeOrgUuids, IQueryBuilder::PARAM_STR_ARRAY)
)
);
}//end addOrganisationConditions()
/**
* Set organisation on an entity during creation.
*
* SECURITY: Always overwrites the organisation with the active organisation UUID
* from the session, ignoring any value provided by the frontend.
* This ensures users can only create entities in their active organisation.
*
* @param Entity $entity The entity to set organisation on
*
* @return void
*/
protected function setOrganisationOnCreate(Entity $entity): void
{
// Only set organisation if the entity has an organisation property.
// Note: We use property_exists() instead of method_exists() because Nextcloud's Entity
// class uses magic methods (__call) for getters/setters, which method_exists() doesn't detect.
if (property_exists($entity, 'organisation') === false) {
return;
}
// SECURITY: Always use active organisation from session, ignore frontend input.
$activeOrgUuid = $this->getActiveOrganisationUuid();
if ($activeOrgUuid !== null) {
$entity->setOrganisation($activeOrgUuid);
return;
}
// Fall back to default organisation if no active organisation and entity has no org set.
if ($entity->getOrganisation() === null && isset($this->appConfig) === true) {
$defaultOrgUuid = $this->appConfig->getValueString('openregister', 'defaultOrganisation', '');
if (empty($defaultOrgUuid) === false) {
$entity->setOrganisation($defaultOrgUuid);
}
}
}//end setOrganisationOnCreate()
/**
* Set the owner field on entity creation from the current user session
*
* This method automatically sets the owner field to the current logged-in user
* when creating a new entity. It only sets the owner if:
* - The entity has owner getter/setter methods
* - The owner is not already set
* - A user is currently logged in
*
* @param Entity $entity The entity being created
*
* @return void
*/
protected function setOwnerOnCreate(Entity $entity): void
{
// Only set owner if the entity has an owner property.
if (method_exists($entity, 'getOwner') === false || method_exists($entity, 'setOwner') === false) {
return;
}
// Only set owner if not already set (allow explicit owner assignment).
if ($entity->getOwner() !== null && $entity->getOwner() !== '') {
return;
}
// Get current user from session.
if (isset($this->userSession) === false) {
return;
}
$user = $this->userSession->getUser();
if ($user !== null) {
$entity->setOwner($user->getUID());
}
}//end setOwnerOnCreate()
/**
* Verify that an entity belongs to the active organisation.
*
* Throws an exception if the entity's organisation doesn't match
* the active organisation. This applies to ALL users including admins.
*
* @param Entity $entity The entity to verify
*
* @return void
*
* @throws \Exception If organisation doesn't match
*/
protected function verifyOrganisationAccess(Entity $entity): void
{
// Check if entity has organisation property.
if (method_exists($entity, 'getOrganisation') === false) {
return;
}
$entityOrgUuid = $entity->getOrganisation();
$activeOrgUuid = $this->getActiveOrganisationUuid();
// If entity has no organisation set, allow it.
if ($entityOrgUuid === null) {
return;
}
// Verify the organisations match (applies to everyone including admins).
if ($entityOrgUuid !== $activeOrgUuid) {
throw new Exception(
'Security violation: You do not have permission to access this resource from a different organisation.',
Response::HTTP_FORBIDDEN
);
}
}//end verifyOrganisationAccess()
/**
* Check if the current user has permission to perform an action.
*
* Checks RBAC permissions from the active organisation's authorization configuration.
*
* Expected authorization structure in Organization entity:
* {
* "authorization": {
* "schema": {
* "create": ["group-name-1", "group-name-2"],
* "read": ["group-name-1"],
* "update": ["group-name-1"],
* "delete": []
* }
* }
* }
*
* @param string $action The action to check (create, read, update, delete)
* @param string $entityType The type of entity (e.g., 'schema', 'register', 'configuration')
*
* @return bool True if user has permission, false otherwise
*
* @SuppressWarnings(PHPMD.NPathComplexity) RBAC permission checking requires many conditional paths
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
protected function hasRbacPermission(string $action, string $entityType): bool
{
// Admins always have all permissions.
if ($this->isCurrentUserAdmin() === true) {
return true;
}
// Get current user.
$userId = $this->getCurrentUserId();
if ($userId === null) {
// No user logged in, deny access.
return false;
}
// Get active organisation.
if (isset($this->organisationService) === false) {
// No organisation service, allow access (backward compatibility).
return true;
}
$activeOrg = $this->organisationService->getActiveOrganisation();
if ($activeOrg === null) {
// CLI context — no active organisation is expected. Allow access.
if (PHP_SAPI === 'cli') {
return true;
}
// No active organisation, deny access.
return false;
}
// Check if user is in the organisation's users list.
$orgUsers = $activeOrg->getUserIds();
if (in_array($userId, $orgUsers) === true) {
// User is explicitly listed in the organisation - check authorization.
}
// Check if user has access via organisation membership.
// Note: $organisationUsers was intended for group-based access but is currently unused.
// Access is determined by $orgUsers check above.
// If (in_array($userId, $organisationUsers, true) === false) {
// Return false;
// }
// Get user's groups.
if (isset($this->groupManager) === false) {
// No group manager, allow access (backward compatibility).
return true;
}
$user = $this->userSession->getUser();
if ($user === null) {
// CLI context (occ commands, repair steps, cron jobs) — no user session exists.
// These are trusted system operations that must always succeed.
if (PHP_SAPI === 'cli') {
return true;
}
return false;
}
$userGroups = $this->groupManager->getUserGroupIds($user);
// Get organisation's authorization configuration.
$authorization = $activeOrg->getAuthorization();
if ($authorization === null || empty($authorization) === true) {
// No RBAC configured, allow access (backward compatibility).
return true;
}
// Check if the entity type exists in authorization.
if (isset($authorization[$entityType]) === false) {
// Entity type not in authorization, allow access (backward compatibility).
return true;
}
// Check if the action exists for this entity type.
if (isset($authorization[$entityType][$action]) === false) {
// Action not configured, allow access (backward compatibility).
return true;
}
$allowedGroups = $authorization[$entityType][$action];
// If the array is empty, it means no restrictions (allow all).
if (empty($allowedGroups) === true) {
return true;
}
// Check if user is in any of the allowed groups.
foreach ($userGroups as $groupId) {
if (in_array($groupId, $allowedGroups) === true) {
return true;
}
}
// Check for wildcard group.
if (in_array('*', $allowedGroups) === true) {
return true;
}
// No matching permission found.
return false;
}//end hasRbacPermission()
/**
* Verify RBAC permission and throw exception if denied.
*
* @param string $action The action to check (create, read, update, delete)
* @param string $entityType The type of entity
*
* @return void
*
* @throws \Exception If user doesn't have permission
*/
protected function verifyRbacPermission(string $action, string $entityType): void
{
if ($this->hasRbacPermission(action: $action, entityType: $entityType) === false) {
throw new Exception(
"Access denied: You do not have permission to {$action} {$entityType} entities.",
Response::HTTP_FORBIDDEN
);
}
}//end verifyRbacPermission()
}//end trait