Passed
Push — master ( aa725e...8615fe )
by Julius
03:34 queued 18s
created

PermissionService   C

Complexity

Total Complexity 54

Size/Duplication

Total Lines 247
Duplicated Lines 19.43 %

Coupling/Cohesion

Components 1
Dependencies 15

Importance

Changes 0
Metric Value
wmc 54
lcom 1
cbo 15
dl 48
loc 247
rs 6.4799
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 21 1
A getPermissions() 11 11 6
A matchPermissions() 11 11 6
B checkPermission() 0 27 7
A userIsBoardOwner() 0 12 5
C userCan() 0 28 12
B findUsers() 18 45 11
A canCreate() 0 12 4
A getGroupLimitList() 8 8 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like PermissionService often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use PermissionService, and based on these observations, apply Extract Interface, too.

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\AppFramework\QueryException;
37
use OCP\IConfig;
38
use OCP\IGroupManager;
39
use OCP\ILogger;
40
use OCP\IUserManager;
41
use OCP\Share\IManager;
42
43
44
class PermissionService {
45
46
	/** @var BoardMapper */
47
	private $boardMapper;
48
	/** @var AclMapper */
49
	private $aclMapper;
50
	/** @var ILogger */
51
	private $logger;
52
	/** @var IUserManager */
53
	private $userManager;
54
	/** @var IGroupManager */
55
	private $groupManager;
56
	/** @var IConfig */
57
	private $config;
58
	/** @var IManager */
59
	private $shareManager;
60
	/** @var string */
61
	private $userId;
62
	/** @var array */
63
	private $users = [];
64
65
	private $circlesEnabled = false;
66
67
	public function __construct(
68
		ILogger $logger,
69
		AclMapper $aclMapper,
70
		BoardMapper $boardMapper,
71
		IUserManager $userManager,
72
		IGroupManager $groupManager,
73
		IManager $shareManager,
74
		IConfig $config,
75
		$userId
76
	) {
77
		$this->aclMapper = $aclMapper;
78
		$this->boardMapper = $boardMapper;
79
		$this->logger = $logger;
80
		$this->userManager = $userManager;
81
		$this->groupManager = $groupManager;
82
		$this->shareManager = $shareManager;
83
		$this->config = $config;
84
		$this->userId = $userId;
85
86
		$this->circlesEnabled = \OC::$server->getAppManager()->isEnabledForUser('circles');
87
	}
88
89
	/**
90
	 * Get current user permissions for a board by id
91
	 *
92
	 * @param $boardId
93
	 * @return bool|array
94
	 */
95 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...
96
		$owner = $this->userIsBoardOwner($boardId);
97
		$acls = $this->aclMapper->findAll($boardId);
98
		return [
99
			Acl::PERMISSION_READ => $owner || $this->userCan($acls, Acl::PERMISSION_READ),
100
			Acl::PERMISSION_EDIT => $owner || $this->userCan($acls, Acl::PERMISSION_EDIT),
101
			Acl::PERMISSION_MANAGE => $owner || $this->userCan($acls, Acl::PERMISSION_MANAGE),
102
			Acl::PERMISSION_SHARE => ($owner || $this->userCan($acls, Acl::PERMISSION_SHARE))
103
				&& (!$this->shareManager->sharingDisabledForUser($this->userId))
104
		];
105
	}
106
107
	/**
108
	 * Get current user permissions for a board
109
	 *
110
	 * @param Board|Entity $board
111
	 * @return array|bool
112
	 * @internal param $boardId
113
	 */
114 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...
115
		$owner = $this->userIsBoardOwner($board->getId());
116
		$acls = $board->getAcl();
117
		return [
118
			Acl::PERMISSION_READ => $owner || $this->userCan($acls, Acl::PERMISSION_READ),
119
			Acl::PERMISSION_EDIT => $owner || $this->userCan($acls, Acl::PERMISSION_EDIT),
120
			Acl::PERMISSION_MANAGE => $owner || $this->userCan($acls, Acl::PERMISSION_MANAGE),
121
			Acl::PERMISSION_SHARE => ($owner || $this->userCan($acls, Acl::PERMISSION_SHARE))
122
				&& (!$this->shareManager->sharingDisabledForUser($this->userId))
123
		];
124
	}
125
126
	/**
127
	 * check permissions for replacing dark magic middleware
128
	 *
129
	 * @param $mapper IPermissionMapper|null null if $id is a boardId
130
	 * @param $id int unique identifier of the Entity
131
	 * @param $permission int
132
	 * @return bool
133
	 * @throws NoPermissionException
134
	 */
135
	public function checkPermission($mapper, $id, $permission, $userId = null) {
136
		$boardId = $id;
137
		if ($mapper instanceof IPermissionMapper) {
138
			$boardId = $mapper->findBoardId($id);
139
		}
140
		if ($boardId === null) {
141
			// Throw NoPermission to not leak information about existing entries
142
			throw new NoPermissionException('Permission denied');
143
		}
144
145
		if ($permission === Acl::PERMISSION_SHARE && $this->shareManager->sharingDisabledForUser($this->userId)) {
146
			return false;
147
		}
148
149
		if ($this->userIsBoardOwner($boardId, $userId)) {
150
			return true;
151
		}
152
153
		$acls = $this->aclMapper->findAll($boardId);
154
		$result = $this->userCan($acls, $permission, $userId);
155
		if ($result) {
156
			return true;
157
		}
158
159
		// Throw NoPermission to not leak information about existing entries
160
		throw new NoPermissionException('Permission denied');
161
	}
162
163
	/**
164
	 * @param $boardId
165
	 * @return bool
166
	 */
167
	public function userIsBoardOwner($boardId, $userId = null) {
168
		if ($userId === null) {
169
			$userId = $this->userId;
170
		}
171
		try {
172
			$board = $this->boardMapper->find($boardId);
173
			return $board && $userId === $board->getOwner();
174
		} catch (DoesNotExistException $e) {
175
		} catch (MultipleObjectsReturnedException $e) {
176
			return false;
177
		}
178
	}
179
180
	/**
181
	 * Check if permission matches the acl rules for current user and groups
182
	 *
183
	 * @param Acl[] $acls
184
	 * @param $permission
185
	 * @return bool
186
	 */
187
	public function userCan(array $acls, $permission, $userId = null) {
188
		if ($userId === null) {
189
			$userId = $this->userId;
190
		}
191
		// check for users
192
		foreach ($acls as $acl) {
193
			if ($acl->getType() === Acl::PERMISSION_TYPE_USER && $acl->getParticipant() === $userId) {
194
				return $acl->getPermission($permission);
195
			}
196
197
			if ($this->circlesEnabled && $acl->getType() === Acl::PERMISSION_TYPE_CIRCLE) {
198
				try {
199
					\OCA\Circles\Api\v1\Circles::getMember($acl->getParticipant(), $this->userId, 1, true);
200
					return $acl->getPermission($permission);
201
				} catch (\Exception $e) {
202
					$this->logger->info('Member not found in circle that was accessed. This should not happen.');
203
				}
204
			}
205
		}
206
		// check for groups
207
		$hasGroupPermission = false;
208
		foreach ($acls as $acl) {
209
			if (!$hasGroupPermission && $acl->getType() === Acl::PERMISSION_TYPE_GROUP && $this->groupManager->isInGroup($userId, $acl->getParticipant())) {
210
				$hasGroupPermission = $acl->getPermission($permission);
211
			}
212
		}
213
		return $hasGroupPermission;
214
	}
215
216
	/**
217
	 * Find a list of all users (including the ones from groups)
218
	 * Required to allow assigning them to cards
219
	 *
220
	 * @param $boardId
221
	 * @return array
222
	 */
223
	public function findUsers($boardId) {
224
		// cache users of a board so we don't query them for every cards
225
		if (array_key_exists((string) $boardId, $this->users)) {
226
			return $this->users[(string) $boardId];
227
		}
228
		try {
229
			$board = $this->boardMapper->find($boardId);
230
		} catch (DoesNotExistException $e) {
231
			return [];
232
		} catch (MultipleObjectsReturnedException $e) {
233
			return [];
234
		}
235
236
		$owner = $this->userManager->get($board->getOwner());
237
		if ($owner === null) {
238
			$this->logger->info('No owner found for board ' . $board->getId());
239
		} else {
240
			$users = [];
241
			$users[$owner->getUID()] = new User($owner);
242
		}
243
		$acls = $this->aclMapper->findAll($boardId);
244
		/** @var Acl $acl */
245
		foreach ($acls as $acl) {
246 View Code Duplication
			if ($acl->getType() === Acl::PERMISSION_TYPE_USER) {
247
				$user = $this->userManager->get($acl->getParticipant());
248
				if ($user === null) {
249
					$this->logger->info('No user found for acl rule ' . $acl->getId());
250
					continue;
251
				}
252
				$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...
253
			}
254 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...
255
				$group = $this->groupManager->get($acl->getParticipant());
256
				if ($group === null) {
257
					$this->logger->info('No group found for acl rule ' . $acl->getId());
258
					continue;
259
				}
260
				foreach ($group->getUsers() as $user) {
261
					$users[$user->getUID()] = new User($user);
262
				}
263
			}
264
		}
265
		$this->users[(string) $boardId] = $users;
266
		return $this->users[(string) $boardId];
267
	}
268
269
	public function canCreate() {
270
		$groups = $this->getGroupLimitList();
271
		if (count($groups) === 0) {
272
			return true;
273
		}
274
		foreach ($groups as $group) {
275
			if ($this->groupManager->isInGroup($this->userId, $group)) {
276
				return true;
277
			}
278
		}
279
		return false;
280
	}
281
282 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...
283
		$value = $this->config->getAppValue('deck', 'groupLimit', '');
284
		$groups = explode(',', $value);
285
		if ($value === '') {
286
			return [];
287
		}
288
		return $groups;
289
	}
290
}
291