UserGroupMembership.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OCA\WorkflowEngine\Check;
  7. use OCP\IGroupManager;
  8. use OCP\IL10N;
  9. use OCP\IUser;
  10. use OCP\IUserSession;
  11. use OCP\WorkflowEngine\ICheck;
  12. use OCP\WorkflowEngine\IManager;
  13. class UserGroupMembership implements ICheck {
  14. /** @var string */
  15. protected $cachedUser;
  16. /** @var string[] */
  17. protected $cachedGroupMemberships;
  18. /**
  19. * @param IUserSession $userSession
  20. * @param IGroupManager $groupManager
  21. * @param IL10N $l
  22. */
  23. public function __construct(
  24. protected IUserSession $userSession,
  25. protected IGroupManager $groupManager,
  26. protected IL10N $l,
  27. ) {
  28. }
  29. /**
  30. * @param string $operator
  31. * @param string $value
  32. * @return bool
  33. */
  34. public function executeCheck($operator, $value) {
  35. $user = $this->userSession->getUser();
  36. if ($user instanceof IUser) {
  37. $groupIds = $this->getUserGroups($user);
  38. return ($operator === 'is') === in_array($value, $groupIds);
  39. } else {
  40. return $operator !== 'is';
  41. }
  42. }
  43. /**
  44. * @param string $operator
  45. * @param string $value
  46. * @throws \UnexpectedValueException
  47. */
  48. public function validateCheck($operator, $value) {
  49. if (!in_array($operator, ['is', '!is'])) {
  50. throw new \UnexpectedValueException($this->l->t('The given operator is invalid'), 1);
  51. }
  52. if (!$this->groupManager->groupExists($value)) {
  53. throw new \UnexpectedValueException($this->l->t('The given group does not exist'), 2);
  54. }
  55. }
  56. /**
  57. * @param IUser $user
  58. * @return string[]
  59. */
  60. protected function getUserGroups(IUser $user) {
  61. $uid = $user->getUID();
  62. if ($this->cachedUser !== $uid) {
  63. $this->cachedUser = $uid;
  64. $this->cachedGroupMemberships = $this->groupManager->getUserGroupIds($user);
  65. }
  66. return $this->cachedGroupMemberships;
  67. }
  68. public function supportedEntities(): array {
  69. // universal by default
  70. return [];
  71. }
  72. public function isAvailableForScope(int $scope): bool {
  73. // admin only by default
  74. return $scope === IManager::SCOPE_ADMIN;
  75. }
  76. }