Completed
Push — master ( a3a70f...f040df )
by Julius
11s
created

PermissionService::checkPermission()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 9.2408
c 0
b 0
f 0
cc 5
nc 8
nop 3
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\IGroupManager;
37
use OCP\ILogger;
38
use OCP\IUserManager;
39
40
41
class PermissionService {
42
43
	/** @var BoardMapper */
44
	private $boardMapper;
45
	/** @var AclMapper */
46
	private $aclMapper;
47
	/** @var ILogger */
48
	private $logger;
49
	/** @var IUserManager */
50
	private $userManager;
51
	/** @var IGroupManager */
52
	private $groupManager;
53
	/** @var string */
54
	private $userId;
55
	/** @var array */
56
	private $users = [];
57
58
	public function __construct(
59
		ILogger $logger,
60
		AclMapper $aclMapper,
61
		BoardMapper $boardMapper,
62
		IUserManager $userManager,
63
		IGroupManager $groupManager,
64
		$userId
65
	) {
66
		$this->aclMapper = $aclMapper;
67
		$this->boardMapper = $boardMapper;
68
		$this->logger = $logger;
69
		$this->userManager = $userManager;
70
		$this->groupManager = $groupManager;
71
		$this->userId = $userId;
72
	}
73
74
	/**
75
	 * Get current user permissions for a board by id
76
	 *
77
	 * @param $boardId
78
	 * @return bool|array
79
	 */
80 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...
81
		$owner = $this->userIsBoardOwner($boardId);
82
		$acls = $this->aclMapper->findAll($boardId);
83
		return [
84
			Acl::PERMISSION_READ => $owner || $this->userCan($acls, Acl::PERMISSION_READ),
85
			Acl::PERMISSION_EDIT => $owner || $this->userCan($acls, Acl::PERMISSION_EDIT),
86
			Acl::PERMISSION_MANAGE => $owner || $this->userCan($acls, Acl::PERMISSION_MANAGE),
87
			Acl::PERMISSION_SHARE => $owner || $this->userCan($acls, Acl::PERMISSION_SHARE),
88
		];
89
	}
90
91
	/**
92
	 * Get current user permissions for a board
93
	 *
94
	 * @param Board|Entity $board
95
	 * @return array|bool
96
	 * @internal param $boardId
97
	 */
98 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...
99
		$owner = $this->userIsBoardOwner($board->getId());
100
		$acls = $board->getAcl();
101
		return [
102
			Acl::PERMISSION_READ => $owner || $this->userCan($acls, Acl::PERMISSION_READ),
103
			Acl::PERMISSION_EDIT => $owner || $this->userCan($acls, Acl::PERMISSION_EDIT),
104
			Acl::PERMISSION_MANAGE => $owner || $this->userCan($acls, Acl::PERMISSION_MANAGE),
105
			Acl::PERMISSION_SHARE => $owner || $this->userCan($acls, Acl::PERMISSION_SHARE),
106
		];
107
	}
108
109
	/**
110
	 * check permissions for replacing dark magic middleware
111
	 *
112
	 * @param $mapper IPermissionMapper|null null if $id is a boardId
113
	 * @param $id int unique identifier of the Entity
114
	 * @param $permission int
115
	 * @return bool
116
	 * @throws NoPermissionException
117
	 */
118
	public function checkPermission($mapper, $id, $permission) {
119
		$boardId = $id;
120
		if ($mapper instanceof IPermissionMapper) {
121
			$boardId = $mapper->findBoardId($id);
122
		}
123
		if ($boardId === null) {
124
			// Throw NoPermission to not leak information about existing entries
125
			throw new NoPermissionException('Permission denied');
126
		}
127
128
		if ($this->userIsBoardOwner($boardId)) {
129
			return true;
130
		}
131
132
		$acls = $this->aclMapper->findAll($boardId);
133
		$result = $this->userCan($acls, $permission);
134
		if ($result) {
135
			return true;
136
		}
137
138
		// Throw NoPermission to not leak information about existing entries
139
		throw new NoPermissionException('Permission denied');
140
	}
141
142
	/**
143
	 * @param $boardId
144
	 * @return bool
145
	 */
146
	public function userIsBoardOwner($boardId) {
147
		try {
148
			$board = $this->boardMapper->find($boardId);
149
			return $board && $this->userId === $board->getOwner();
150
		} catch (DoesNotExistException $e) {
151
		} catch (MultipleObjectsReturnedException $e) {
152
			return false;
153
		}		
154
	}
155
156
	/**
157
	 * Check if permission matches the acl rules for current user and groups
158
	 *
159
	 * @param Acl[] $acls
160
	 * @param $permission
161
	 * @return bool
162
	 */
163
	public function userCan(array $acls, $permission) {
164
		// check for users
165
		foreach ($acls as $acl) {
166
			if ($acl->getType() === Acl::PERMISSION_TYPE_USER && $acl->getParticipant() === $this->userId) {
167
				return $acl->getPermission($permission);
168
			}
169
		}
170
		// check for groups
171
		$hasGroupPermission = false;
172
		foreach ($acls as $acl) {
173
			if (!$hasGroupPermission && $acl->getType() === Acl::PERMISSION_TYPE_GROUP && $this->groupManager->isInGroup($this->userId, $acl->getParticipant())) {
174
				$hasGroupPermission = $acl->getPermission($permission);
175
			}
176
		}
177
		return $hasGroupPermission;
178
	}
179
180
	/**
181
	 * Find a list of all users (including the ones from groups)
182
	 * Required to allow assigning them to cards
183
	 *
184
	 * @param $boardId
185
	 * @return array
186
	 */
187
	public function findUsers($boardId) {
188
		// cache users of a board so we don't query them for every cards
189
		if (array_key_exists((string) $boardId, $this->users)) {
190
			return $this->users[(string) $boardId];
191
		}
192
		try {
193
			$board = $this->boardMapper->find($boardId);
194
		} catch (DoesNotExistException $e) {
195
			return [];
196
		} catch (MultipleObjectsReturnedException $e) {
197
			return [];
198
		}
199
200
		$owner = $this->userManager->get($board->getOwner());
201
		if ($owner === null) {
202
			$this->logger->info('No owner found for board ' . $board->getId());
203
		} else {
204
			$users = [];
205
			$users[$owner->getUID()] = new User($owner);
206
		}
207
		$acls = $this->aclMapper->findAll($boardId);
208
		/** @var Acl $acl */
209
		foreach ($acls as $acl) {
210 View Code Duplication
			if ($acl->getType() === Acl::PERMISSION_TYPE_USER) {
211
				$user = $this->userManager->get($acl->getParticipant());
212
				if ($user === null) {
213
					$this->logger->info('No user found for acl rule ' . $acl->getId());
214
					continue;
215
				}
216
				$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...
217
			}
218 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...
219
				$group = $this->groupManager->get($acl->getParticipant());
220
				if ($group === null) {
221
					$this->logger->info('No group found for acl rule ' . $acl->getId());
222
					continue;
223
				}
224
				foreach ($group->getUsers() as $user) {
225
					$users[$user->getUID()] = new User($user);
226
				}
227
			}
228
		}
229
		$this->users[(string) $boardId] = $users;
230
		return $this->users[(string) $boardId];
231
	}
232
}