Esempio n. 1
0
 def upload_file(self):
     """
     https://developers.box.com/docs/#files-upload-a-file
     """
     attributes = request.forms.get('attributes') or request.forms.get(
         'metadata')
     if not attributes:
         abort(400, 'Missing parameter: attributes')
     attributes = json.loads(attributes)
     parent = attributes.get('parent')
     if parent is None or 'id' not in parent:
         abort(400, 'Missing parameter: parent(id)')
     parent_id = parent['id']
     folder = get_folder_by_id(self._db_session, parent_id)
     content = request.files.file.file.read()
     file_hash = sha1()
     file_hash.update(content)
     owner = get_user_from_header(self._db_session)
     file_object = FileModel(
         content=content,
         name=attributes.get('name', request.files.file.name),
         parent_id=folder.id,
         sha1=file_hash.hexdigest(),
         size=len(content),
         owned_by=owner,
         created_by=owner,
     )
     self._db_session.add(file_object)
     self._db_session.commit()
     self._db_session.add(
         EventModel(event_type='ITEM_UPLOAD',
                    source_id=file_object.file_id,
                    source_type='file'))
     self._db_session.commit()
     return json.dumps({'entries': [file_object]})
 def upload_file(self):
     """
     https://developers.box.com/docs/#files-upload-a-file
     """
     attributes = request.forms.get('attributes') or request.forms.get('metadata')
     if not attributes:
         abort(400, 'Missing parameter: attributes')
     attributes = json.loads(attributes)
     parent = attributes.get('parent')
     if parent is None or 'id' not in parent:
         abort(400, 'Missing parameter: parent(id)')
     parent_id = parent['id']
     folder = get_folder_by_id(self._db_session, parent_id)
     content = request.files.file.file.read()
     file_hash = sha1()
     file_hash.update(content)
     owner = get_user_from_header(self._db_session)
     file_object = FileModel(
         content=content,
         name=attributes.get('name', request.files.file.name),
         parent_id=folder.id,
         sha1=file_hash.hexdigest(),
         size=len(content),
         owned_by=owner,
         created_by=owner,
     )
     self._db_session.add(file_object)
     self._db_session.commit()
     self._db_session.add(EventModel(event_type='ITEM_UPLOAD', source_id=file_object.file_id, source_type='file'))
     self._db_session.commit()
     return json.dumps({'entries': [file_object]})
Esempio n. 3
0
 def update_file_info(self, file_id):
     file_object = get_file_by_id(self._db_session, file_id)
     self._check_file_lock(file_object)
     params = json.load(request.body)
     for key, value in params.items():
         if not hasattr(FileModel, key):
             abort(400, 'File has no attribute {0}.'.format(key))
         if key == 'parent':
             # Move
             parent_id = value['id']
             parent_folder = get_folder_by_id(self._db_session, parent_id)
             file_object.parent_id = parent_folder.id
             self._db_session.add(
                 EventModel(event_type='ITEM_MOVE',
                            source_id=file_object.file_id,
                            source_type='file'), )
         else:
             setattr(file_object, key, value)
             if key == 'name':
                 self._db_session.add(
                     EventModel(event_type='ITEM_RENAME',
                                source_id=file_object.file_id,
                                source_type='file'), )
             elif key == 'sync_state':
                 event_type = 'ITEM_SYNC' if value == 'synced' else 'ITEM_UNSYNC'
                 self._db_session.add(
                     EventModel(event_type=event_type,
                                source_id=file_object.file_id,
                                source_type='file'), )
     self._db_session.commit()
     return json.dumps(file_object)
 def _get_parent(self):
     params = json.load(request.body)
     parent = params.get('parent')
     if parent is None or 'id' not in parent:
         abort(400, 'Missing parameter: parent(id)')
     parent_id = parent['id']
     return get_folder_by_id(self._db_session, parent_id)
 def update_file_info(self, file_id):
     file_object = get_file_by_id(self._db_session, file_id)
     self._check_file_lock(file_object)
     params = json.load(request.body)
     for key, value in params.items():
         if not hasattr(FileModel, key):
             abort(400, 'File has no attribute {0}.'.format(key))
         if key == 'parent':
             # Move
             parent_id = value['id']
             parent_folder = get_folder_by_id(self._db_session, parent_id)
             file_object.parent_id = parent_folder.id
             self._db_session.add(
                 EventModel(event_type='ITEM_MOVE', source_id=file_object.file_id, source_type='file'),
             )
         else:
             setattr(file_object, key, value)
             if key == 'name':
                 self._db_session.add(
                     EventModel(event_type='ITEM_RENAME', source_id=file_object.file_id, source_type='file'),
                 )
             elif key == 'sync_state':
                 event_type = 'ITEM_SYNC' if value == 'synced' else 'ITEM_UNSYNC'
                 self._db_session.add(
                     EventModel(event_type=event_type, source_id=file_object.file_id, source_type='file'),
                 )
     self._db_session.commit()
     return json.dumps(file_object)
Esempio n. 6
0
 def update_folder_info(self, folder_id):
     folder = get_folder_by_id(self._db_session, folder_id)
     params = json.load(request.body)
     for key, value in params.items():
         if not hasattr(FolderModel, key):
             abort(400, "Folder has no attribute {0}.".format(key))
         if key == "parent":
             # Move
             parent_id = value["id"]
             parent_folder = get_folder_by_id(self._db_session, parent_id)
             folder.parent_id = parent_folder.id
             self._db_session.add(
                 EventModel(event_type="ITEM_MOVE", source_id=folder.folder_id, source_type="folder")
             )
         else:
             setattr(folder, key, value)
             if key == "name":
                 self._db_session.add(
                     EventModel(event_type="ITEM_RENAME", source_id=folder.folder_id, source_type="folder")
                 )
             elif key == "sync_state":
                 event_type = "ITEM_SYNC" if value == FolderSyncState.IS_SYNCED else "ITEM_UNSYNC"
                 self._db_session.add(
                     EventModel(event_type=event_type, source_id=folder.folder_id, source_type="folder")
                 )
     self._db_session.commit()
     return json.dumps(folder)
 def update_folder_info(self, folder_id):
     folder = get_folder_by_id(self._db_session, folder_id)
     params = json.load(request.body)
     for key, value in params.items():
         if not hasattr(FolderModel, key):
             abort(400, 'Folder has no attribute {0}.'.format(key))
         if key == 'parent':
             # Move
             parent_id = value['id']
             parent_folder = get_folder_by_id(self._db_session, parent_id)
             folder.parent_id = parent_folder.id
             self._db_session.add(
                 EventModel(event_type='ITEM_MOVE', source_id=folder.folder_id, source_type='folder'),
             )
         else:
             setattr(folder, key, value)
             if key == 'name':
                 self._db_session.add(
                     EventModel(event_type='ITEM_RENAME', source_id=folder.folder_id, source_type='folder'),
                 )
             elif key == 'sync_state':
                 event_type = 'ITEM_SYNC' if value == FolderSyncState.IS_SYNCED else 'ITEM_UNSYNC'
                 self._db_session.add(
                     EventModel(event_type=event_type, source_id=folder.folder_id, source_type='folder'),
                 )
     self._db_session.commit()
     return json.dumps(folder)
Esempio n. 8
0
 def create_folder(self):
     """
     https://developers.box.com/docs/#folders-create-a-new-folder
     """
     params = json.load(request.body)
     name = params.get("name")
     if name is None:
         abort(400, "Missing parameter: name")
     parent = params.get("parent")
     if parent is None or "id" not in parent:
         abort(400, "Missing parameter: parent(id)")
     parent_id = parent["id"]
     try:
         parent_folder = self._db_session.query(FolderModel).filter_by(folder_id=parent_id).one()
     except NoResultFound:
         abort(404)
     owner = get_user_from_header(self._db_session)
     name_in_use = self._db_session.query(FolderModel).filter_by(name=name).count()
     if name_in_use:
         abort(409, "An item with that name already exists.")
     folder = FolderModel(name=name, parent_id=parent_folder.id, owned_by=owner, created_by=owner)
     self._db_session.add(folder)
     self._db_session.commit()
     self._db_session.add(EventModel(event_type="ITEM_CREATE", source_id=folder.folder_id, source_type="folder"))
     self._db_session.commit()
     return json.dumps(folder)
 def create_folder(self):
     """
     https://developers.box.com/docs/#folders-create-a-new-folder
     """
     params = json.load(request.body)
     name = params.get('name')
     if name is None:
         abort(400, 'Missing parameter: name')
     parent = params.get('parent')
     if parent is None or 'id' not in parent:
         abort(400, 'Missing parameter: parent(id)')
     parent_id = parent['id']
     try:
         parent_folder = self._db_session.query(FolderModel).filter_by(folder_id=parent_id).one()
     except NoResultFound:
         abort(404)
     owner = get_user_from_header(self._db_session)
     name_in_use = self._db_session.query(FolderModel).filter_by(name=name).count()
     if name_in_use:
         abort(409, 'An item with that name already exists.')
     folder = FolderModel(name=name, parent_id=parent_folder.id, owned_by=owner, created_by=owner)
     self._db_session.add(folder)
     self._db_session.commit()
     self._db_session.add(EventModel(event_type='ITEM_CREATE', source_id=folder.folder_id, source_type='folder'))
     self._db_session.commit()
     return json.dumps(folder)
    def check_authorization_header(self):
        """
        Check that the request has an auth header and that its token matches the currently valid token.
        Further check that the token isn't expired.

        Called by methods decorated with the authorize decorator.
        """
        authorization_header = request.headers.get('Authorization')
        if not authorization_header or not authorization_header.startswith('Bearer '):
            abort(401)
        token = authorization_header[7:]
        token_record = get_token_record_by_token(self._db_session, token)
        if datetime.utcnow() > token_record.expires_at:
            abort(401)
Esempio n. 11
0
    def check_authorization_header(self):
        """
        Check that the request has an auth header and that its token matches the currently valid token.
        Further check that the token isn't expired.

        Called by methods decorated with the authorize decorator.
        """
        authorization_header = request.headers.get('Authorization')
        if not authorization_header or not authorization_header.startswith(
                'Bearer '):
            abort(401)
        token = authorization_header[7:]
        token_record = get_token_record_by_token(self._db_session, token)
        if datetime.utcnow() > token_record.expires_at:
            abort(401)
Esempio n. 12
0
    def oauth2_token(self):
        """
        OAuth2 /token method.
        Either exchanges an auth code for an access/refresh token pair, or refreshes a token.
        """
        grant_type = request.forms.get('grant_type')
        client_id, client_secret = request.forms.get(
            'client_id'), request.forms.get('client_secret')
        app = self._get_application_by_id(client_id)
        if client_secret != app.client_secret:
            abort(400, 'Invalid client secret: {0}'.format(client_secret))

        if grant_type == 'authorization_code':
            code = request.forms.get('code')
            if self._auth_request is None:
                abort(400, 'Invalid code: {0}'.format(code))
            access_token, refresh_token = self._auth_request[
                'access_token'], self._auth_request['refresh_token']
        elif grant_type == 'refresh_token':
            refresh_token = request.forms.get('refresh_token')
            refresh_token_record = get_token_record_by_token(
                self._db_session, refresh_token)
            if refresh_token_record.token_type == 'refresh':
                if datetime.utcnow() > refresh_token_record.expires_at:
                    abort(400, 'Token expired: {0}'.format(refresh_token))
                access_token, _, refresh_token, _ = self._create_tokens(
                    client_id,
                    owned_by_id=refresh_token_record.owned_by_id,
                )
            else:
                abort(400, 'Invalid token: {0}'.format(refresh_token))
        else:
            abort(400, 'Invalid grant type: {0}'.format(grant_type))

        return json.dumps({
            'access_token': access_token,
            'refresh_token': refresh_token,
            'expires_in': self.ACCESS_TOKEN_DURATION_SECONDS,
        })
    def oauth2_token(self):
        """
        OAuth2 /token method.
        Either exchanges an auth code for an access/refresh token pair, or refreshes a token.
        """
        grant_type = request.forms.get('grant_type')
        client_id, client_secret = request.forms.get('client_id'), request.forms.get('client_secret')
        app = self._get_application_by_id(client_id)
        if client_secret != app.client_secret:
            abort(400, 'Invalid client secret: {0}'.format(client_secret))

        if grant_type == 'authorization_code':
            code = request.forms.get('code')
            if self._auth_request is None:
                abort(400, 'Invalid code: {0}'.format(code))
            access_token, refresh_token = self._auth_request['access_token'], self._auth_request['refresh_token']
        elif grant_type == 'refresh_token':
            refresh_token = request.forms.get('refresh_token')
            refresh_token_record = get_token_record_by_token(self._db_session, refresh_token)
            if refresh_token_record.token_type == 'refresh':
                if datetime.utcnow() > refresh_token_record.expires_at:
                    abort(400, 'Token expired: {0}'.format(refresh_token))
                access_token, _, refresh_token, _ = self._create_tokens(
                    client_id,
                    owned_by_id=refresh_token_record.owned_by_id,
                )
            else:
                abort(400, 'Invalid token: {0}'.format(refresh_token))
        else:
            abort(400, 'Invalid grant type: {0}'.format(grant_type))

        return json.dumps({
            'access_token': access_token,
            'refresh_token': refresh_token,
            'expires_in': self.ACCESS_TOKEN_DURATION_SECONDS,
        })
Esempio n. 14
0
 def _check_file_lock(file_object, is_download=False):
     if len(file_object.locks):
         lock_object = file_object.locks[0]
         if not is_download or lock_object.is_download_prevented:
             abort(403, 'File is locked.')
Esempio n. 15
0
def get_token_record_by_token(db_session, token):
    try:
        return db_session.query(TokenModel).filter_by(token=token).one()
    except NoResultFound:
        abort(401)
Esempio n. 16
0
def get_folder_by_id(db_session, folder_id):
    try:
        return db_session.query(FolderModel).filter_by(folder_id=folder_id).one()
    except NoResultFound:
        abort(404)
Esempio n. 17
0
def get_file_by_id(db_session, file_id):
    try:
        return db_session.query(FileModel).filter_by(file_id=file_id).one()
    except NoResultFound:
        abort(404)
Esempio n. 18
0
def error(code, message=None, headers=None):
    return lambda erroneous_function: lambda *args, **kwargs: abort(code, message=message, headers=headers)
 def _get_user_by_id(self, user_id):
     try:
         return self._db_session.query(UserModel).filter_by(user_id=user_id).one()
     except NoResultFound:
         abort(401)
Esempio n. 20
0
 def _get_user_by_id(self, user_id):
     try:
         return self._db_session.query(UserModel).filter_by(
             user_id=user_id).one()
     except NoResultFound:
         abort(401)
Esempio n. 21
0
def get_token_record_by_token(db_session, token):
    try:
        return db_session.query(TokenModel).filter_by(token=token).one()
    except NoResultFound:
        abort(401)
Esempio n. 22
0
 def _get_application_by_id(self, client_id):
     try:
         return self._db_session.query(ApplicationModel).filter_by(
             client_id=client_id).one()
     except NoResultFound:
         abort(400, 'Invalid client id: {0}'.format(client_id))
 def _get_application_by_id(self, client_id):
     try:
         return self._db_session.query(ApplicationModel).filter_by(client_id=client_id).one()
     except NoResultFound:
         abort(400, 'Invalid client id: {0}'.format(client_id))
Esempio n. 24
0
 def _get_user_by_login(self, user_login):
     try:
         return self._db_session.query(UserModel).filter_by(
             login=user_login).one()
     except NoResultFound:
         abort(401)
 def _get_user_by_login(self, user_login):
     try:
         return self._db_session.query(UserModel).filter_by(login=user_login).one()
     except NoResultFound:
         abort(401)
Esempio n. 26
0
def error(code, message=None, headers=None):
    return lambda erroneous_function: lambda *args, **kwargs: abort(code, message=message, headers=headers)
Esempio n. 27
0
def get_file_by_id(db_session, file_id):
    try:
        return db_session.query(FileModel).filter_by(file_id=file_id).one()
    except NoResultFound:
        abort(404)
Esempio n. 28
0
def get_folder_by_id(db_session, folder_id):
    try:
        return db_session.query(FolderModel).filter_by(
            folder_id=folder_id).one()
    except NoResultFound:
        abort(404)
 def _check_file_lock(file_object, is_download=False):
     if len(file_object.locks):
         lock_object = file_object.locks[0]
         if not is_download or lock_object.is_download_prevented:
             abort(403, 'File is locked.')