def decipherUser(appletSpecificId): thisUser = getCurrentUser() try: ciphered = FolderModel().load(appletSpecificId, level=AccessType.NONE, user=thisUser) userId = list(FolderModel().find( query={ 'parentId': ciphered['_id'], 'parentCollection': 'folder', 'name': 'userID' })) except: return (None) try: cUser = str(userId[0]['meta']['user']['@id']) if len(userId) and type( userId[0]) == dict and userId[0].get('meta').get('user').get( '@id') else None FolderModel().setUserAccess(doc=ciphered, user=UserModel().load(id=cUser, user=cUser), level=AccessType.READ, save=True, currentUser=thisUser, force=True) return (cUser) except: return (None)
def handle(self, record): user = getCurrentUser() if record.msg == 'rest.request': # Some characters may not be stored as MongoDB Object keys # https://docs.mongodb.com/manual/core/document/#field-names # RFC3986 technically allows such characters to be encoded in the query string, and # 'params' also contains data from form bodies, which may contain arbitrary field names # For MongoDB, '\x00', '.', and '$' must be encoded, and for invertibility, '%' must be # encoded too, but just encode everything for simplicity record.details['params'] = { # 'urllib.parse.quote' alone doesn't replace '.' urllib.parse.quote(paramKey, safe='').replace('.', '%2E'): paramValue for paramKey, paramValue in six.viewitems( record.details['params']) } Record().save( { 'type': record.msg, 'details': record.details, 'ip': cherrypy.request.remote.ip, 'userId': user and user['_id'], 'when': datetime.datetime.utcnow() }, triggerEvents=False)
def canonicalUser(user): thisUser = getCurrentUser() try: userId = UserModel().load(user, level=AccessType.NONE, user=thisUser) except: return (None) try: return (str(userId['_id']) if '_id' in userId else None) except: return (None)
def _loadModel(self, name, info, id, model): if info['force']: doc = model.load(id, force=True, **info['kwargs']) elif info['level'] is not None: doc = model.load(id=id, level=info['level'], user=getCurrentUser(), **info['kwargs']) else: doc = model.load(id, **info['kwargs']) if doc is None and info['exc']: raise RestException('Invalid %s id (%s).' % (model.name, str(id))) if info['requiredFlags']: model.requireAccessFlags(doc, user=getCurrentUser(), flags=info['requiredFlags']) return doc
def getUserCipher(appletAssignment, user): """ Returns an applet-specific user ID. Parameters ---------- appletAssignment: Mongo Folder cursor Applet folder in Assignments collection user: string or list applet-specific ID, canonical ID or email address Returns ------- user: string applet-specific ID """ if not isinstance(user, str): return ([getUserCipher(appletAssignment, u) for u in list(user)]) thisUser = getCurrentUser() appletAssignments = list(FolderModel().childFolders( parent=appletAssignment, parentType='folder', user=thisUser)) allCiphers = list( itertools.chain.from_iterable([ list(FolderModel().find( query={ 'parentId': assignment.get('_id'), 'parentCollection': 'folder', 'name': 'userID' })) for assignment in appletAssignments ])) if len(appletAssignments) else [] cUser = getCanonicalUser(user) aUser = [ cipher['parentId'] for cipher in allCiphers if (cipher['meta']['user']['@id'] == cUser) if cipher.get('meta') and cipher['meta'].get('user') and cipher['meta']['user'].get('@id') and cipher.get('parentId') ] if cUser and len(allCiphers) else [] aUser = aUser[0] if len(aUser) else createCipher( appletAssignment, appletAssignments, cUser if cUser is not None else user)['_id'] return (str(aUser))
def _folderUpdate(self, event): params = event.info['params'] if {'isVirtual', 'virtualItemsQuery', 'virtualItemsSort'} & set(params): folder = Folder().load(event.info['returnVal']['_id'], force=True) update = False if params.get('isVirtual') is not None: update = True folder['isVirtual'] = params['isVirtual'] if params.get('virtualItemsQuery') is not None: update = True folder['virtualItemsQuery'] = params['virtualItemsQuery'] if params.get('virtualItemsSort') is not None: update = True folder['virtualItemsSort'] = params['virtualItemsSort'] if update: self.requireAdmin(self.getCurrentUser(), 'Must be admin to setup virtual folders.') folder = Folder().filter(Folder().save(folder), rest.getCurrentUser()) event.preventDefault().addResponse(folder)
def finalizeUpload(self, upload, assetstore=None): """ This should only be called manually in the case of creating an empty file, i.e. one that has no chunks. :param upload: The upload document. :type upload: dict :param assetstore: If known, the containing assetstore for the upload. :type assetstore: dict :returns: The file object that was created. """ from girderformindlogger.models.assetstore import Assetstore from girderformindlogger.models.file import File from girderformindlogger.models.item import Item from girderformindlogger.utility import assetstore_utilities events.trigger('model.upload.finalize', upload) if assetstore is None: assetstore = Assetstore().load(upload['assetstoreId']) if 'fileId' in upload: # Updating an existing file's contents file = File().load(upload['fileId'], force=True) # Delete the previous file contents from the containing assetstore assetstore_utilities.getAssetstoreAdapter(Assetstore().load( file['assetstoreId'])).deleteFile(file) item = Item().load(file['itemId'], force=True) File().propagateSizeChange(item, upload['size'] - file['size']) # Update file info file['creatorId'] = upload['userId'] file['created'] = datetime.datetime.utcnow() file['assetstoreId'] = assetstore['_id'] file['size'] = upload['size'] # If the file was previously imported, it is no longer. if file.get('imported'): file['imported'] = False else: # Creating a new file record if upload.get('attachParent'): item = None elif upload['parentType'] == 'folder': # Create a new item with the name of the file. item = Item().createItem(name=upload['name'], creator={'_id': upload['userId']}, folder={'_id': upload['parentId']}) elif upload['parentType'] == 'item': item = Item().load(id=upload['parentId'], force=True) else: item = None file = File().createFile(item=item, name=upload['name'], size=upload['size'], creator={'_id': upload['userId']}, assetstore=assetstore, mimeType=upload['mimeType'], saveFile=False) if upload.get('attachParent'): if upload['parentType'] and upload['parentId']: file['attachedToType'] = upload['parentType'] file['attachedToId'] = upload['parentId'] adapter = assetstore_utilities.getAssetstoreAdapter(assetstore) file = adapter.finalizeUpload(upload, file) event_document = {'file': file, 'upload': upload} events.trigger('model.file.finalizeUpload.before', event_document) file = File().save(file) events.trigger('model.file.finalizeUpload.after', event_document) if '_id' in upload: self.remove(upload) logger.info('Upload complete. Upload=%s File=%s User=%s' % (upload['_id'], file['_id'], upload['userId'])) # Add an async event for handlers that wish to process this file. eventParams = { 'file': file, 'assetstore': assetstore, 'currentToken': rest.getCurrentToken(), 'currentUser': rest.getCurrentUser() } if 'reference' in upload: eventParams['reference'] = upload['reference'] events.daemon.trigger('data.process', eventParams) return file
def createCipher(applet, appletAssignments, user): thisUser = getCurrentUser() cUser = None try: cUser = UserModel().load(user, level=AccessType.NONE, user=thisUser) except: cur_config = config.getConfig() if not re.match(cur_config['users']['email_regex'], user): raise ValidationException('Invalid email address.', 'user') newCipher = FolderModel().createFolder(parent=applet, name=nextCipher(appletAssignments), parentType='folder', public=False, creator=thisUser, reuseExisting=True) if cUser is None: try: appletName = FolderModel().preferredName(FolderModel().load( applet['meta']['applet']['@id'], level=AccessType.NONE, user=thisUser)['name']) except: raise ValidationException('Invalid assignment folder.', 'applet') try: cUser = UserModel().createUser(login="******".join( [appletName.replace(' ', ''), str(newCipher['name'])]), password=str(uuid.uuid4()), firstName=appletName, email=user, admin=False, public=False, currentUser=thisUser) except: cUser = UserModel().createUser(login="******".join([ appletName.replace(' ', ''), str(applet['meta']['applet']['@id']), str(FolderModel().preferredName(newCipher)) ]), password=str(uuid.uuid4()), firstName=appletName, email=user, admin=False, public=False, currentUser=thisUser) newSecretCipher = FolderModel().setMetadata( FolderModel().createFolder(parent=newCipher, name='userID', parentType='folder', public=False, creator=thisUser, reuseExisting=True), {'user': { '@id': str(cUser['_id']) }}) FolderModel().setAccessList(doc=newSecretCipher, access={ 'users': [], 'groups': [] }, save=True, user=thisUser, force=True) for u in [thisUser, cUser]: FolderModel().setUserAccess(doc=newSecretCipher, user=u, level=None, save=True, currentUser=thisUser, force=True) for u in [thisUser, cUser]: FolderModel().setUserAccess(doc=newSecretCipher, user=u, level=AccessType.READ, save=True, currentUser=thisUser, force=True) return (newCipher)
def wrapped(*args, **kwargs): if not rest.getCurrentUser(): raise AccessException('You must be logged in.') return fun(*args, **kwargs)
def wrapped(*args, **kwargs): rest.requireAdmin(rest.getCurrentUser()) return fun(*args, **kwargs)