Coverage for girder/api/v1/group: 97%

# Coverage for girder/api/v1/group : 97%

## 119 statements 116 run 3 missing 0 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 | #!/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. ############################################################################### from ..describe import Description from ..rest import Resource, RestException, loadmodel from ...models.model_base import ValidationException, AccessException from ...constants import AccessType from girder.utility import mail_utils class Group(Resource): """API Endpoint for groups.""" def __init__(self): self.resourceName = 'group' self.route('DELETE', (':id',), self.deleteGroup) self.route('DELETE', (':id', 'member'), self.removeFromGroup) self.route('DELETE', (':id', 'moderator'), self.demote) self.route('DELETE', (':id', 'admin'), self.demote) self.route('GET', (), self.find) self.route('GET', (':id',), self.getGroup) self.route('GET', (':id', 'access'), self.getGroupAccess) self.route('GET', (':id', 'invitation'), self.getGroupInvitations) self.route('GET', (':id', 'member'), self.listMembers) self.route('POST', (), self.createGroup) self.route('POST', (':id', 'invitation'), self.inviteToGroup) self.route('POST', (':id', 'member'), self.joinGroup) self.route('POST', (':id', 'moderator'), self.promoteToModerator) self.route('POST', (':id', 'admin'), self.promoteToAdmin) self.route('PUT', (':id',), self.updateGroup) def find(self, params): """ List or search for groups. :param params: Request query parameters. :type params: dict :returns: A page of matching Group documents. """ limit, offset, sort = self.getPagingParameters(params, 'name') user = self.getCurrentUser() groupList = self.model('group').list(user=user, offset=offset, limit=limit, sort=sort) return [self.model('group').filter(group, user) for group in groupList] find.description = ( Description('Search for groups or list all groups.') .param('text', "Pass this to perform a full-text search for groups.", required=False) .param('limit', "Result set size limit (default=50).", required=False, dataType='int') .param('offset', "Offset into result set (default=0).", required=False, dataType='int') .param('sort', "Field to sort the group list by (default=name)", required=False) .param('sortdir', "1 for ascending, -1 for descending (default=1)", required=False, dataType='int') .errorResponse()) def createGroup(self, params): """ Create a new group. :param params: Request query parameters. :type params: dict :returns: The created group document. """ self.requireParams(('name',), params) name = params['name'].strip() description = params.get('description', '').strip() public = params.get('public', '').lower() == 'true' user = self.getCurrentUser() if user is None: raise AccessException('Must be logged in to create a group.') group = self.model('group').createGroup( name=name, creator=user, description=description, public=public) return self.model('group').filter(group, user) createGroup.description = ( Description('Create a new group.') .responseClass('Group') .notes('Must be logged in.') .param('name', 'Unique name for the group.') .param('description', 'Description of the group.', required=False) .param('public', """Whether the group should be public or private. The default is private.""", required=False, dataType='boolean') .errorResponse() .errorResponse('Write access was denied on the parent', 403)) @loadmodel(map={'id': 'group'}, model='group', level=AccessType.READ) def getGroup(self, group, params): user = self.getCurrentUser() return self.model('group').filter(group, user) getGroup.description = ( Description('Get a group by ID.') .responseClass('Group') .param('id', 'The ID of the group.', paramType='path') .errorResponse('ID was invalid.') .errorResponse('Read access was denied for the group.', 403)) @loadmodel(map={'id': 'group'}, model='group', level=AccessType.READ) def getGroupAccess(self, group, params): user = self.getCurrentUser() return self.model('group').filter(group, user, accessList=True, requests=True) getGroupAccess.description = ( Description('Get the access control list for a group.') .responseClass('Group') .param('id', 'The ID of the group.', paramType='path') .errorResponse('ID was invalid.') .errorResponse('Read access was denied for the group.', 403)) @loadmodel(map={'id': 'group'}, model='group', level=AccessType.READ) def getGroupInvitations(self, group, params): limit, offset, sort = self.getPagingParameters(params, 'lastName') return self.model('group').getInvites(group, limit, offset, sort) getGroupInvitations.description = ( Description('Show outstanding invitations for a group.') .responseClass('Group') .param('id', 'The ID of the group.', paramType='path') .param('limit', "Result set size limit (default=50).", required=False, dataType='int') .param('offset', "Offset into result set (default=0).", required=False, dataType='int') .param('sort', "Field to sort the invitee list by (default=lastName)", required=False) .param('sortdir', "1 for ascending, -1 for descending (default=1)", required=False, dataType='int') .errorResponse() .errorResponse('Read access was denied for the group.', 403)) @loadmodel(map={'id': 'group'}, model='group', level=AccessType.WRITE) def updateGroup(self, group, params): user = self.getCurrentUser() public = params.get('public', 'false').lower() == 'true' self.model('group').setPublic(group, public) group['name'] = params.get('name', group['name']).strip() group['description'] = params.get( 'description', group['description']).strip() group = self.model('group').updateGroup(group) return self.model('group').filter(group, user) updateGroup.description = ( Description('Update a group by ID.') .param('id', 'The ID of the group.', paramType='path') .param('name', 'The name to set on the group.', required=False) .param('description', 'Description for the group.', required=False) .param('public', 'Whether the group should be publicly visible', dataType='boolean', required=False) .errorResponse() .errorResponse('Write access was denied for the group.', 403)) @loadmodel(map={'id': 'group'}, model='group', level=AccessType.READ) def joinGroup(self, group, params): """ Accept a group invitation. If you have not been invited, this will instead request an invitation. :param group: The group to join. :type group: dict :param user: The current user. :type user: dict :returns: The updated group document. """ user = self.getCurrentUser() joinedGroup = self.model('group').joinGroup(group, user) return self.model('group').filter(joinedGroup, user, accessList=True, requests=True) joinGroup.description = ( Description('Request to join a group, or accept an invitation to join.') .responseClass('Group') .param('id', 'The ID of the group.', paramType='path') .errorResponse('ID was invalid.') .errorResponse('You were not invited to this group, or do not have ' 'read access to it.', 403)) @loadmodel(map={'id': 'group'}, model='group', level=AccessType.READ) def listMembers(self, group, params): """ Paginated member list of group members. :returns: A page of User documents representing members of the group. """ limit, offset, sort = self.getPagingParameters(params, 'lastName') return [g for g in self.model('group').listMembers( group, offset=offset, limit=limit, sort=sort)] listMembers.description = ( Description('List members of a group.') .param('id', 'The ID of the group.', paramType='path') .param('limit', "Result set size limit (default=50).", required=False, dataType='int') .param('offset', "Offset into result set (default=0).", required=False, dataType='int') .param('sort', "Field to sort the member list by (default=lastName)", required=False) .param('sortdir', "1 for ascending, -1 for descending (default=1)", required=False, dataType='int') .errorResponse('ID was invalid.') .errorResponse('Read access was denied for the group.', 403)) @loadmodel(map={'id': 'group'}, model='group', level=AccessType.WRITE) def inviteToGroup(self, group, params): """Invite the user to join the group.""" self.requireParams(('userId',), params) user = self.getCurrentUser() level = int(params.get('level', AccessType.READ)) userToInvite = self.model('user').load( id=params['userId'], user=user, level=AccessType.READ, exc=True) # Can only invite into access levels that you yourself have self.model('group').requireAccess(group, user, level) self.model('group').inviteUser(group, userToInvite, level) if params.get('quiet', '').lower() != 'true': html = mail_utils.renderTemplate('groupInvite.mako', { 'userToInvite': userToInvite, 'user': user, 'group': group }) mail_utils.sendEmail( to=userToInvite['email'], text=html, subject="Girder: You've been invited to a group") return self.model('group').filter(group, user, accessList=True, requests=True) inviteToGroup.description = ( Description("Invite a user to join a group, or accept a user's request " " to join.") .responseClass('Group') .param('id', 'The ID of the group.', paramType='path') .param('userId', 'The ID of the user to invite or accept.') .param('level', 'The access level the user will be given when they ' 'accept the invitation. Defaults to read access (0).', required=False, dataType='int') .param('quiet', 'If you do not wish this action to send an email, ' 'set this parameter to "true".', required=False) .errorResponse() .errorResponse('Write access was denied for the group.', 403)) @loadmodel(map={'id': 'group'}, model='group', level=AccessType.ADMIN) def promoteToModerator(self, group, params): return self._promote(group, params, AccessType.WRITE) promoteToModerator.description = ( Description('Promote a member to be a moderator of the group.') .responseClass('Group') .param('id', 'The ID of the group.', paramType='path') .param('userId', 'The ID of the user to promote.') .errorResponse('ID was invalid.') .errorResponse("You don't have permission to promote users.", 403)) @loadmodel(map={'id': 'group'}, model='group', level=AccessType.ADMIN) def promoteToAdmin(self, group, params): return self._promote(group, params, AccessType.ADMIN) promoteToAdmin.description = ( Description('Promote a member to be an administrator of the group.') .responseClass('Group') .param('id', 'The ID of the group.', paramType='path') .param('userId', 'The ID of the user to promote.') .errorResponse('ID was invalid.') .errorResponse("You don't have permission to promote users.", 403)) def _promote(self, group, params, level): """ Promote a user to moderator or administrator. :param group: The group to promote within. :param params: Request parameters. :param level: Either WRITE or ADMIN, for moderator or administrator. :type level: AccessType :returns: The updated group document. """ self.requireParams(('userId',), params) user = self.getCurrentUser() userToPromote = self.model('user').load( id=params['userId'], user=user, level=AccessType.READ, exc=True) if not group['_id'] in userToPromote.get('groups', []): raise AccessException('That user is not a group member.') group = self.model('group').setUserAccess( group, userToPromote, level=level, save=True) return self.model('group').filter(group, user, accessList=True) @loadmodel(map={'id': 'group'}, model='group', level=AccessType.ADMIN) def demote(self, group, params): """ Demote a user down to a normal member. :returns: The updated group document. """ self.requireParams(('userId',), params) user = self.getCurrentUser() userToDemote = self.model('user').load( id=params['userId'], user=user, level=AccessType.READ, exc=True) group = self.model('group').setUserAccess( group, userToDemote, level=AccessType.READ, save=True) return self.model('group').filter(group, user, accessList=True, requests=True) demote.description = ( Description('Demote a user to a normal group member.') .responseClass('Group') .param('id', 'The ID of the group.', paramType='path') .param('userId', 'The ID of the user to demote.') .errorResponse() .errorResponse("You don't have permission to demote users.", 403)) @loadmodel(map={'id': 'group'}, model='group', level=AccessType.READ) def removeFromGroup(self, group, params): """ Remove a user from a group. Pass a 'userId' key in params to remove a specific user; otherwise will remove this user. :param group: The group to remove the user from. :type group: dict :param user: The current user (not the user being removed). :type user: dict :param params: Request query parameters. :type params: dict :returns: The updated group document. """ user = self.getCurrentUser() if 'userId' in params: userToRemove = self.model('user').load( id=params['userId'], user=user, level=AccessType.READ, exc=True) else: # Assume user is removing himself from the group userToRemove = user # If removing someone else, you must have at least as high an # access level as they do, and you must have at least write access # to remove any user other than yourself. if user['_id'] != userToRemove['_id']: if self.model('group').hasAccess(group, userToRemove, AccessType.ADMIN): self.model('group').requireAccess(group, user, AccessType.ADMIN) else: self.model('group').requireAccess(group, user, AccessType.WRITE) groupSansUser = self.model('group').removeUser(group, userToRemove) return self.model('group').filter(groupSansUser, user, requests=True, accessList=True) removeFromGroup.description = ( Description('Remove a user from a group, or uninvite them.') .responseClass('Group') .notes("""If the specified user is not yet a member of the group, this will delete any oustanding invitation or membership request for the user. Passing no userId parameter will assume that the current user is removing himself.""") .param('id', 'The ID of the group.', paramType='path') .param('userId', 'The ID of the user to remove. If not passed, will ' 'remove yourself from the group.', required=False) .errorResponse() .errorResponse("You don't have permission to remove that user.", 403)) @loadmodel(map={'id': 'group'}, model='group', level=AccessType.ADMIN) def deleteGroup(self, group, params): self.model('group').remove(group) return {'message': 'Deleted the group {}.'.format(group['name'])} deleteGroup.description = ( Description('Delete a group by ID.') .param('id', 'The ID of the group.', paramType='path') .errorResponse('ID was invalid.') .errorResponse('Admin access was denied for the group.', 403))