Passed
Push — master ( f5d7fd...3b403d )
by Julius
02:46
created

PermissionService::getPermissions()   A

Complexity

Conditions 6
Paths 24

Size

Total Lines 11

Duplication

Lines 11
Ratio 100 %

Importance

Changes 0
Metric Value
dl 11
loc 11
rs 9.2222
c 0
b 0
f 0
cc 6
nc 24
nop 1
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016 Julius Härtl <[email protected]>
4
 *
5
 * @author Julius Härtl <[email protected]>
6
 *
7
 * @license GNU AGPL version 3 or any later version
8
 *
9
 *  This program is free software: you can redistribute it and/or modify
10
 *  it under the terms of the GNU Affero General Public License as
11
 *  published by the Free Software Foundation, either version 3 of the
12
 *  License, or (at your option) any later version.
13
 *
14
 *  This program is distributed in the hope that it will be useful,
15
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 *  GNU Affero General Public License for more details.
18
 *
19
 *  You should have received a copy of the GNU Affero General Public License
20
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
 *
22
 */
23
24
namespace OCA\Deck\Service;
25
26
use OCA\Deck\Db\Acl;
27
use OCA\Deck\Db\AclMapper;
28
use OCA\Deck\Db\Board;
29
use OCA\Deck\Db\BoardMapper;
30
use OCA\Deck\Db\IPermissionMapper;
31
use OCA\Deck\Db\User;
32
use OCA\Deck\NoPermissionException;
33
use OCP\AppFramework\Db\DoesNotExistException;
34
use OCP\AppFramework\Db\Entity;
35
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
36
use OCP\IConfig;
37
use OCP\IGroupManager;
38
use OCP\ILogger;
39
use OCP\IUserManager;
40
use OCP\Share\IManager;
41
42
43
class PermissionService {
44
45
	/** @var BoardMapper */
46
	private $boardMapper;
47
	/** @var AclMapper */
48
	private $aclMapper;
49
	/** @var ILogger */
50
	private $logger;
51
	/** @var IUserManager */
52
	private $userManager;
53
	/** @var IGroupManager */
54
	private $groupManager;
55
	/** @var IConfig */
56
	private $config;
57
	/** @var IManager */
58
	private $shareManager;
59
	/** @var string */
60
	private $userId;
61
	/** @var array */
62
	private $users = [];
63
64
	public function __construct(
65
		ILogger $logger,
66
		AclMapper $aclMapper,
67
		BoardMapper $boardMapper,
68
		IUserManager $userManager,
69
		IGroupManager $groupManager,
70
		IManager $shareManager,
71
		IConfig $config,
72
		$userId
73
	) {
74
		$this->aclMapper = $aclMapper;
75
		$this->boardMapper = $boardMapper;
76
		$this->logger = $logger;
77
		$this->userManager = $userManager;
78
		$this->groupManager = $groupManager;
79
		$this->shareManager = $shareManager;
80
		$this->config = $config;
81
		$this->userId = $userId;
82
	}
83
84
	/**
85
	 * Get current user permissions for a board by id
86
	 *
87
	 * @param $boardId
88
	 * @return bool|array
89
	 */
90 View Code Duplication
	public function getPermissions($boardId) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
91
		$owner = $this->userIsBoardOwner($boardId);
92
		$acls = $this->aclMapper->findAll($boardId);
93
		return [
94
			Acl::PERMISSION_READ => $owner || $this->userCan($acls, Acl::PERMISSION_READ),
95
			Acl::PERMISSION_EDIT => $owner || $this->userCan($acls, Acl::PERMISSION_EDIT),
96
			Acl::PERMISSION_MANAGE => $owner || $this->userCan($acls, Acl::PERMISSION_MANAGE),
97
			Acl::PERMISSION_SHARE => ($owner || $this->userCan($acls, Acl::PERMISSION_SHARE))
98
				&& (!$this->shareManager->sharingDisabledForUser($this->userId))
99
		];
100
	}
101
102
	/**
103
	 * Get current user permissions for a board
104
	 *
105
	 * @param Board|Entity $board
106
	 * @return array|bool
107
	 * @internal param $boardId
108
	 */
109 View Code Duplication
	public function matchPermissions(Board $board) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
110
		$owner = $this->userIsBoardOwner($board->getId());
111
		$acls = $board->getAcl();
112
		return [
113
			Acl::PERMISSION_READ => $owner || $this->userCan($acls, Acl::PERMISSION_READ),
114
			Acl::PERMISSION_EDIT => $owner || $this->userCan($acls, Acl::PERMISSION_EDIT),
115
			Acl::PERMISSION_MANAGE => $owner || $this->userCan($acls, Acl::PERMISSION_MANAGE),
116
			Acl::PERMISSION_SHARE => ($owner || $this->userCan($acls, Acl::PERMISSION_SHARE))
117
				&& (!$this->shareManager->sharingDisabledForUser($this->userId))
118
		];
119
	}
120
121
	/**
122
	 * check permissions for replacing dark magic middleware
123
	 *
124
	 * @param $mapper IPermissionMapper|null null if $id is a boardId
125
	 * @param $id int unique identifier of the Entity
126
	 * @param $permission int
127
	 * @return bool
128
	 * @throws NoPermissionException
129
	 */
130
	public function checkPermission($mapper, $id, $permission) {
131
		$boardId = $id;
132
		if ($mapper instanceof IPermissionMapper) {
133
			$boardId = $mapper->findBoardId($id);
134
		}
135
		if ($boardId === null) {
136
			// Throw NoPermission to not leak information about existing entries
137
			throw new NoPermissionException('Permission denied');
138
		}
139
140
		if ($permission === Acl::PERMISSION_SHARE && $this->shareManager->sharingDisabledForUser($this->userId)) {
141
			return false;
142
		}
143
144
		if ($this->userIsBoardOwner($boardId)) {
145
			return true;
146
		}
147
148
		$acls = $this->aclMapper->findAll($boardId);
149
		$result = $this->userCan($acls, $permission);
150
		if ($result) {
151
			return true;
152
		}
153
154
		// Throw NoPermission to not leak information about existing entries
155
		throw new NoPermissionException('Permission denied');
156
	}
157
158
	/**
159
	 * @param $boardId
160
	 * @return bool
161
	 */
162
	public function userIsBoardOwner($boardId) {
163
		try {
164
			$board = $this->boardMapper->find($boardId);
165
			return $board && $this->userId === $board->getOwner();
166
		} catch (DoesNotExistException $e) {
167
		} catch (MultipleObjectsReturnedException $e) {
168
			return false;
169
		}
170
	}
171
172
	/**
173
	 * Check if permission matches the acl rules for current user and groups
174
	 *
175
	 * @param Acl[] $acls
176
	 * @param $permission
177
	 * @return bool
178
	 */
179
	public function userCan(array $acls, $permission) {
180
		// check for users
181
		foreach ($acls as $acl) {
182
			if ($acl->getType() === Acl::PERMISSION_TYPE_USER && $acl->getParticipant() === $this->userId) {
183
				return $acl->getPermission($permission);
184
			}
185
		}
186
		// check for groups
187
		$hasGroupPermission = false;
188
		foreach ($acls as $acl) {
189
			if (!$hasGroupPermission && $acl->getType() === Acl::PERMISSION_TYPE_GROUP && $this->groupManager->isInGroup($this->userId, $acl->getParticipant())) {
190
				$hasGroupPermission = $acl->getPermission($permission);
191
			}
192
		}
193
		return $hasGroupPermission;
194
	}
195
196
	/**
197
	 * Find a list of all users (including the ones from groups)
198
	 * Required to allow assigning them to cards
199
	 *
200
	 * @param $boardId
201
	 * @return array
202
	 */
203
	public function findUsers($boardId) {
204
		// cache users of a board so we don't query them for every cards
205
		if (array_key_exists((string) $boardId, $this->users)) {
206
			return $this->users[(string) $boardId];
207
		}
208
		try {
209
			$board = $this->boardMapper->find($boardId);
210
		} catch (DoesNotExistException $e) {
211
			return [];
212
		} catch (MultipleObjectsReturnedException $e) {
213
			return [];
214
		}
215
216
		$owner = $this->userManager->get($board->getOwner());
217
		if ($owner === null) {
218
			$this->logger->info('No owner found for board ' . $board->getId());
219
		} else {
220
			$users = [];
221
			$users[$owner->getUID()] = new User($owner);
222
		}
223
		$acls = $this->aclMapper->findAll($boardId);
224
		/** @var Acl $acl */
225
		foreach ($acls as $acl) {
226 View Code Duplication
			if ($acl->getType() === Acl::PERMISSION_TYPE_USER) {
227
				$user = $this->userManager->get($acl->getParticipant());
228
				if ($user === null) {
229
					$this->logger->info('No user found for acl rule ' . $acl->getId());
230
					continue;
231
				}
232
				$users[$user->getUID()] = new User($user);
0 ignored issues
show
Bug introduced by
The variable $users does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
233
			}
234 View Code Duplication
			if ($acl->getType() === Acl::PERMISSION_TYPE_GROUP) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
235
				$group = $this->groupManager->get($acl->getParticipant());
236
				if ($group === null) {
237
					$this->logger->info('No group found for acl rule ' . $acl->getId());
238
					continue;
239
				}
240
				foreach ($group->getUsers() as $user) {
241
					$users[$user->getUID()] = new User($user);
242
				}
243
			}
244
		}
245
		$this->users[(string) $boardId] = $users;
246
		return $this->users[(string) $boardId];
247
	}
248
249
	public function canCreate() {
250
		$groups = $this->getGroupLimitList();
251
		foreach ($groups as $group) {
252
			if ($this->groupManager->isInGroup($this->userId, $group)) {
253
				return false;
254
			}
255
		}
256
		return true;
257
	}
258
259 View Code Duplication
	private function getGroupLimitList() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
260
		$value = $this->config->getAppValue('deck', 'groupLimit', '');
261
		$groups = explode(',', $value);
262
		if ($value === '') {
263
			return [];
264
		}
265
		return $groups;
266
	}
267
}
268