Coverage for girder/models/group: 88%

# Coverage for girder/models/group : 88%

## 163 statements 144 run 19 missing 3 excluded

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

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 | #!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright 2013 Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### import datetime from .model_base import AccessControlledModel,\ ValidationException,\ AccessException from girder.constants import AccessType class Group(AccessControlledModel): """ Groups are simply groups of users. The primary use of grouping users is to simplify access control for resources in the system, but they can be used for other purposes that require groupings of users as well. Group membership is stored in the database on the user document only; there is no "users" field in this model. This is to optimize for the most common use case for querying membership, which involves checking access control policies, which is always done relative to a specific user. The task of querying all members within a group is much less common and typically only performed on a single group at a time, so doing a find on the indexed group list in the user collection is sufficiently fast. Users with READ access on the group can see the group and its members. Users with WRITE access on the group can add and remove members and change the name or description. Users with ADMIN access can promote group members to grant them WRITE or ADMIN access, and can also delete the entire group. This model uses a custom implementation of the access control methods, because it uses only a subset of its capabilities and provides a more optimized implementation for that subset. Specifically: read access is implied by membership in the group or having an invitation to join the group, so we don't store read access in the access document as normal. Another constraint is that write and admin access on the group can only be granted to members of the group. Also, group permissions are not allowed on groups for the sake of simplicity. """ def initialize(self): self.name = 'group' self.ensureIndices(['lowerName']) self.ensureTextIndex({ 'name': 10, 'description': 1 }) def filter(self, group, user, accessList=False, requests=False): """ Filter a group document for display to the user. :param group: The document to filter. :type group: dict :param user: The current user. :type user: dict :param accessList: Whether to include the access control list field. :type accessList: bool :param requests: Whether to include the requests list field. :type requests: bool :returns: The filtered group document. """ keys = ['_id', 'name', 'public', 'description', 'created', 'updated'] if requests: keys.append('requests') accessLevel = self.getAccessLevel(group, user) if accessList: keys.append('access') group = self.filterDocument(group, allow=keys) group['_accessLevel'] = accessLevel if accessList: group['access'] = self.getFullAccessList(group) if requests: group['requests'] = self.getFullRequestList(group) return group def validate(self, doc): doc['name'] = doc['name'].strip() doc['lowerName'] = doc['name'].lower() doc['description'] = doc['description'].strip() if not doc['name']: raise ValidationException('Group name must not be empty.', 'name') q = { 'lowerName': doc['lowerName'], } if '_id' in doc: q['_id'] = {'$ne': doc['_id']} duplicates = self.find(q, limit=1, fields=['_id']) if duplicates.count() != 0: raise ValidationException('A group with that name already' 'exists.', 'name') return doc def list(self, user=None, limit=50, offset=0, sort=None): """ Search for groups or simply list all visible groups. :param text: Pass this to perform a text search of all groups. :param user: The user to search as. :param limit: Result set size limit. :param offset: Offset into the results. :param sort: The sort direction. """ # Perform the find; we'll do access-based filtering of the result # set afterward. cursor = self.find({}, limit=0, sort=sort) for r in self.filterResultsByPermission(cursor=cursor, user=user, level=AccessType.READ, limit=limit, offset=offset): yield r def listMembers(self, group, offset=0, limit=50, sort=None): """ List members of the group, with names, ids, and logins. """ fields = ['_id', 'firstName', 'lastName', 'login'] return self.model('user').find({ 'groups': group['_id'] }, fields=fields, limit=limit, offset=offset, sort=sort) def remove(self, group): """ Delete a group, and all references to it in the database. :param group: The group document to delete. :type group: dict """ # Remove references to this group from user group membership lists self.model('user').update({ 'groups': group['_id'] }, { '$pull': {'groups': group['_id']} }) acQuery = { 'access.groups.id': group['_id'] } acUpdate = { '$pull': { 'access.groups': {'id': group['_id']} } } # Remove references to this group from access-controlled collections. self.update(acQuery, acUpdate) self.model('collection').update(acQuery, acUpdate) self.model('folder').update(acQuery, acUpdate) self.model('user').update(acQuery, acUpdate) # Finally, delete the document itself AccessControlledModel.remove(self, group) def getMembers(self, group, offset=0, limit=50, sort=None): """ Return the list of all users who belong to this group. :param group: The group to list members on. :param offset: Offset into the result set of users. :param limit: Result set size limit. :param sort: Sort parameter for the find query. :returns: List of user documents. """ q = { 'groups': group['_id'] } cursor = self.model('user').find( q, offset=offset, limit=limit, sort=sort) users = [] for user in cursor: users.append(user) return users def addUser(self, group, user, level=AccessType.READ): """ Add the user to the group. Records membership in the group in the user document, and also grants the specified access level on the group itself to the user. Any group member has at least read access on the group. If the user already belongs to the group, this method can be used to change their access level within it. """ if 'groups' not in user: user['groups'] = [] if not group['_id'] in user['groups']: user['groups'].append(group['_id']) self.model('user').save(user, validate=False) # Delete outstanding request if one exists self._deleteRequest(group, user) self.setUserAccess(group, user, level, save=True) return group def _deleteRequest(self, group, user): """ Helper method to delete a request for the given user. """ if user['_id'] in group.get('requests', []): group['requests'].remove(user['_id']) self.save(group, validate=False) def joinGroup(self, group, user): """ This method either accepts an invitation to join a group, or if the given user has not been invited to the group, this will create an invitation request that moderators and admins may grant or deny later. """ if 'groupInvites' not in user: user['groupInvites'] = [] for invite in user['groupInvites']: if invite['groupId'] == group['_id']: self.addUser(group, user, level=invite['level']) user['groupInvites'].remove(invite) self.model('user').save(user, validate=False) break else: if 'requests' not in group: group['requests'] = [] if not user['_id'] in group['requests']: group['requests'].append(user['_id']) self.save(group, validate=False) return group def inviteUser(self, group, user, level=AccessType.READ): """ Invite a user to join the group. Inviting them automatically grants the user read access to the group so that they can see it. Once they accept the invitation, they will be given the specified level of access. If the user has requested an invitation to this group, calling this will accept their request and add them to the group at the access level specified. """ if group['_id'] in user.get('groups', []): raise ValidationException('User is already in this group.') # If there is an outstanding request to join from this user, we # just add them to the group instead of invite them. if user['_id'] in group.get('requests', []): return self.addUser(group, user, level) if 'groupInvites' not in user: user['groupInvites'] = [] for invite in user['groupInvites']: if invite['groupId'] == group['_id']: invite['level'] = level break else: user['groupInvites'].append({ 'groupId': group['_id'], 'level': level }) return self.model('user').save(user, validate=False) def getInvites(self, group, limit=50, offset=0, sort=None): """ Return a page of outstanding invitations to a group. This is simply a list of users invited to the group currently. :param group: The group to find invitations for. :param limit: Result set size limit. :param offset: Offset into the results. :param sort: The sort field. """ cursor = self.model('user').find( {'groupInvites.groupId': group['_id']}, limit=limit, offset=offset, sort=sort, fields=[ '_id', 'firstName', 'lastName', 'login' ]) return [result for result in cursor] def removeUser(self, group, user): """ Remove the user from the group. If the user is not in the group but has an outstanding invitation to the group, the invitation will be revoked. If the user has requested an invitation, calling this will deny that request, thereby deleting it. """ # Remove group membership for this user. if 'groups' in user and group['_id'] in user['groups']: user['groups'].remove(group['_id']) # Remove outstanding requests from this user self._deleteRequest(group, user) # Remove any outstanding invitations for this group l = lambda inv: not inv['groupId'] == group['_id'] user['groupInvites'] = filter(l, user.get('groupInvites', [])) self.model('user').save(user, validate=False) # Remove all group access for this user on this group. self.setUserAccess(group, user, level=None, save=True) return group def createGroup(self, name, creator, description='', public=True): """ Create a new group. The creator will be given admin access to it. :param name: The name of the folder. :type name: str :param description: Description for the folder. :type description: str :param public: Whether the group is publicly visible. :type public: bool :param creator: User document representing the creator of the group. :type creator: dict :returns: The group document that was created. """ assert type(public) is bool now = datetime.datetime.now() group = { 'name': name, 'description': description, 'created': now, 'updated': now, 'requests': [] } self.setPublic(group, public=public) # Now validate and save the group self.save(group) # We make the creator a member of this group and also grant them # admin access over the group. self.addUser(group, creator, level=AccessType.ADMIN) return group def updateGroup(self, group): """ Updates a group. :param group: The group document to update :type group: dict :returns: The group document that was edited. """ group['updated'] = datetime.datetime.now() # Validate and save the group return self.save(group) def getFullRequestList(self, group): """ Return the set of all outstanding requests, filled in with the login and full names of the corresponding users. :param group: The group to get requests for. :type group: dict """ reqList = [] for userId in group.get('requests', []): user = self.model('user').load( userId, force=True, fields=['firstName', 'lastName', 'login']) reqList.append({ 'id': userId, 'login': user['login'], 'name': '{} {}'.format(user['firstName'], user['lastName']) }) return reqList def hasAccess(self, doc, user=None, level=AccessType.READ): """ This overrides the default AccessControlledModel behavior for checking access to perform an optimized subset of the access control behavior. :param doc: The group to check permission on. :type doc: dict :param user: The user to check against. :type user: dict :param level: The access level. :type level: AccessType :returns: Whether the access is granted. """ if user is None: # Short-circuit the case of anonymous users return level == AccessType.READ and doc.get('public', False) is True elif user.get('admin', False) is True: # Short-circuit the case of admins return True elif level == AccessType.READ: # For read access, just check user document for membership or public return doc.get('public', False) is True or\ doc['_id'] in user.get('groups', []) or\ doc['_id'] in [i['groupId'] for i in user.get('groupInvites', [])] else: # Check the actual permissions document for >=WRITE access return self._hasUserAccess(doc.get('access', {}).get('users', []), user['_id'], level) def getAccessLevel(self, doc, user): """ Return the maximum access level for a given user on the group. :param doc: The group to check access on. :param user: The user to get the access level for. :returns: The max AccessType available for the user on the object. """ if user is None: if doc.get('public', False): return AccessType.READ else: return AccessType.NONE elif user.get('admin', False): return AccessType.ADMIN else: access = doc.get('access', {}) level = AccessType.NONE if doc['_id'] in user.get('groups', []): level = AccessType.READ elif doc['_id'] in [i['groupId'] for i in user.get('groupInvites', [])]: return AccessType.READ for userAccess in access.get('users', []): if userAccess['id'] == user['_id']: level = max(level, userAccess['level']) if level == AccessType.ADMIN: return level return level def setAccessList(self, doc, access, save=False): raise Exception('Not implemented.') # pragma: no cover def setGroupAccess(self, doc, group, level, save=False): raise Exception('Not implemented.') # pragma: no cover def copyAccessPolicies(self, src, dest, save=False): raise Exception('Not implemented.') # pragma: no cover def setUserAccess(self, doc, user, level, save=False): """ This override is used because we only need to augment the access field in the case of WRITE access and above since READ access is implied by membership or invitation. """ if level > AccessType.READ: doc = AccessControlledModel.setUserAccess( self, doc, user, level, save=True) else: doc = AccessControlledModel.setUserAccess( self, doc, user, level=None, save=True) return doc