Example #1
0
    def __func():
        if not _reset_token_durations(access_token_duration=configuration.get(
                'access_token_duration', None),
                                      refresh_token_duration=configuration.get(
                                          'refresh_token_duration', None)):
            return Problem.from_crud_resource(
                BAD_REQUEST, 'configuration', 'update',
                'Access token duration must be less than refresh token duration.'
            )

        for config, config_value in configuration.items():
            if hasattr(walkoff.config.paths, config):
                setattr(walkoff.config.paths, config, config_value)
            elif hasattr(walkoff.config.config, config):
                setattr(walkoff.config.config, config, config_value)

        current_app.logger.info('Changed configuration')
        try:
            walkoff.config.config.write_values_to_file()
            return __get_current_configuration(), SUCCESS
        except (IOError, OSError) as e:
            current_app.logger.error(
                'Could not write changes to configuration to file')
            return Problem(
                IO_ERROR, 'Could not write changes to file.',
                'Could not write configuration changes to file. Problem: {}'.
                format(format_exception_message(e)))
Example #2
0
    def __func(workflow):
        try:
            errors = workflow_schema.load(data, instance=workflow).errors
            if errors:
                return Problem.from_crud_resource(
                    INVALID_INPUT_ERROR,
                    'workflow',
                    'update',
                    'Could not update workflow {}. Invalid input.'.format(
                        workflow_id),
                    ext=errors)
        except InvalidExecutionElement as e:
            executiondb.execution_db.session.rollback()
            current_app.logger.error(e.message)
            return Problem.from_crud_resource(
                INVALID_INPUT_ERROR, 'workflow', 'update',
                'Could not update workflow {}. Invalid input.'.format(
                    workflow_id))

        try:
            executiondb.execution_db.session.commit()
        except IntegrityError:
            executiondb.execution_db.session.rollback()
            current_app.logger.error(
                'Could not update workflow {}. Unique constraint failed'.
                format(workflow_id))
            return unique_constraint_problem('workflow', 'update', workflow_id)

        current_app.logger.info('Updated workflow {0}'.format(workflow_id))
        return workflow_schema.dump(workflow).data, SUCCESS
Example #3
0
    def __func(workflow):
        if not workflow.is_valid:
            return Problem(INVALID_INPUT_ERROR, 'Cannot execute workflow',
                           'Workflow is invalid')
        args = data['arguments'] if 'arguments' in data else None
        start = data['start'] if 'start' in data else None

        arguments = []
        if args:
            errors = []
            arguments = [Argument(**arg) for arg in args]
            for argument in arguments:
                if argument.errors:
                    errors.append('Errors in argument {}: {}'.format(
                        argument.name, argument.errors))
            if errors:
                current_app.logger.error(
                    'Could not execute workflow. Invalid Argument construction'
                )
                return Problem(
                    INVALID_INPUT_ERROR, 'Cannot execute workflow.',
                    'Some arguments are invalid. Reason: {}'.format(errors))

        execution_id = current_app.running_context.executor.execute_workflow(
            workflow_id, start=start, start_arguments=arguments)
        current_app.logger.info('Executed workflow {0}'.format(workflow_id))
        return {'id': execution_id}, SUCCESS_ASYNC
Example #4
0
def stream_console_events():
    workflow_execution_id = request.args.get('workflow_execution_id')
    if workflow_execution_id is None:
        return Problem(BAD_REQUEST, 'Could not connect to log stream',
                       'workflow_execution_id is a required query param')
    try:
        UUID(workflow_execution_id)
        return console_stream.stream(subchannel=workflow_execution_id)
    except (ValueError, AttributeError):
        return Problem(BAD_REQUEST, 'Could not connect to log stream',
                       'workflow_execution_id must be a valid UUID')
Example #5
0
 def __func():
     user_id = get_jwt_identity()
     user = User.query.filter(User.id == user_id).first()
     message = Message.query.filter(Message.id == message_id).first()
     if message is None:
         return Problem(OBJECT_DNE_ERROR, 'Cannot read message.',
                        'Message {} does not exist.'.format(message_id))
     if user not in message.users:
         return Problem(
             FORBIDDEN_ERROR, 'message', 'read',
             'User is not allowed to access message {}'.format(message_id))
     message.record_user_action(user, MessageAction.read)
     db.session.commit()
     MessageActionEvent.read.send(message, data={'user': user})
     return message.as_json(user=user), SUCCESS
Example #6
0
    def __func():
        if request.files and 'file' in request.files:
            f = request.files['file']
            add_device_json = json.loads(f.read().decode('utf-8'))
        else:
            add_device_json = request.get_json()
        if current_app.running_context.execution_db.session.query(
                Device).filter(Device.name ==
                               add_device_json['name']).first() is not None:
            current_app.logger.error('Could not create device {0}. '
                                     'Device already exists.'.format(
                                         add_device_json['name']))
            return Problem.from_crud_resource(
                OBJECT_EXISTS_ERROR, 'device', 'create',
                'Device with name {} already exists.'.format(
                    add_device_json['name']))

        fields = {
            field['name']: field['value']
            for field in add_device_json['fields']
        }
        app = add_device_json['app_name']
        device_type = add_device_json['type']
        try:
            device_api = get_app_device_api(app, device_type)
            device_fields_api = device_api['fields']
            validate_device_fields(device_fields_api, fields, device_type, app)
        except (UnknownApp, UnknownDevice, InvalidArgument) as e:
            return __crud_device_error_handler('create', e, app, device_type)
        else:
            fields = add_device_json['fields']
            add_configuration_keys_to_device_json(fields, device_fields_api)
            app = current_app.running_context.execution_db.session.query(
                App).filter(App.name == app).first()
            if app is None:
                current_app.logger.error(
                    'SEVERE: App defined in api does not have corresponding entry in database. '
                    'Cannot add device')
                return Problem.from_crud_resource(
                    INVALID_INPUT_ERROR, 'device', 'create',
                    'App {} does not exist.'.format(
                        add_device_json['app_name']))
            device = Device.from_json(add_device_json)
            app.add_device(device)
            current_app.running_context.execution_db.session.add(device)
            current_app.running_context.execution_db.session.commit()
            device_json = get_device_json_with_app_name(device)
            return device_json, OBJECT_CREATED
Example #7
0
def improper_json_problem(type_, operation, id_, errors=None):
    return Problem.from_crud_resource(
        BAD_REQUEST,
        type_,
        operation,
        'Could not {} {} {}. Invalid JSON'.format(operation, type_, id_),
        ext={'errors': errors})
Example #8
0
    def __func(playbook):
        workflow_name = data['name']
        if 'start' not in data:
            return Problem(BAD_REQUEST, 'Could not create workflow.',
                           '"start" is required field.')
        try:
            workflow = workflow_schema.load(data)
            if workflow.errors:
                current_app.running_context.execution_db.session.rollback()
                current_app.logger.error(
                    'Could not create Workflow {}. Invalid input'.format(
                        workflow_name))
                return improper_json_problem('workflow', 'create',
                                             workflow_name, workflow.errors)
            else:
                workflow = workflow.data
                playbook.workflows.append(workflow)
                current_app.running_context.execution_db.session.add(workflow)
                current_app.running_context.execution_db.session.commit()
        except IntegrityError:
            current_app.running_context.execution_db.session.rollback()
            current_app.logger.error(
                'Could not create workflow {}. Unique constraint failed'.
                format(workflow_name))
            return unique_constraint_problem('workflow', 'create',
                                             workflow_name)

        current_app.logger.info('Workflow {0}-{1} created'.format(
            playbook_id, workflow_name))
        return workflow_schema.dump(workflow).data, OBJECT_CREATED
Example #9
0
def act_on_messages():
    from walkoff.messaging import MessageAction

    @jwt_required
    @permissions_accepted_for_resources(
        ResourcePermissions('messages', ['update']))
    def other_action_func(action_):
        return act_on_message_helper(action_)

    @jwt_required
    @permissions_accepted_for_resources(
        ResourcePermissions('messages', ['delete']))
    def delete_message_action():
        return act_on_message_helper(MessageAction.delete)

    action = MessageAction.convert_string(request.get_json()['action'])
    if action is None or action == MessageAction.respond:
        possible_actions = [
            action.name for action in MessageAction
            if action != MessageAction.respond
        ]
        return Problem(
            OBJECT_DNE_ERROR, 'Unknown action on messages.',
            'Unknown action: {0}. Possible actions are {1}.'.format(
                action, possible_actions))

    if action == MessageAction.delete:
        return delete_message_action()
    else:
        return other_action_func(action)
Example #10
0
def improper_json_problem(type_, operation, id_, errors=None):
    return Problem.from_crud_resource(
        BAD_REQUEST,
        type_,
        operation,
        'Could not {} {} {}. Invalid JSON'.format(operation, type_, id_),
        ext={'errors': errors})
Example #11
0
 def __func():
     if request.files and 'file' in request.files:
         f = request.files['file']
         data = json.loads(f.read().decode('utf-8'))
     else:
         data = request.get_json()
     case_name = data['name']
     case_obj = CaseSubscription.query.filter_by(name=case_name).first()
     if case_obj is None:
         case_subscription = CaseSubscription(**data)
         db.session.add(case_subscription)
         db.session.commit()
         case = case_database.Case(name=case_name)
         current_app.running_context.case_db.session.add(case)
         current_app.running_context.case_db.commit()
         if 'subscriptions' in data:
             subscriptions = convert_subscriptions(data['subscriptions'])
             subscriptions, controller_subscriptions = split_subscriptions(
                 subscriptions)
             current_app.running_context.executor.create_case(
                 case.id, subscriptions)
             if controller_subscriptions:
                 current_app.running_context.case_logger.add_subscriptions(
                     case.id, subscriptions)
         current_app.logger.debug('Case added: {0}'.format(case_name))
         return case_subscription.as_json(), OBJECT_CREATED
     else:
         current_app.logger.warning(
             'Cannot create case {0}. Case already exists.'.format(
                 case_name))
         return Problem.from_crud_resource(
             OBJECT_EXISTS_ERROR, 'case', 'create',
             'Case with name {} already exists.'.format(case_name))
Example #12
0
    def __func():
        data = request.get_json()
        case_obj = CaseSubscription.query.filter_by(id=data['id']).first()
        if case_obj:
            original_name = case_obj.name
            case_name = data['name'] if 'name' in data else original_name

            if 'note' in data and data['note']:
                case_obj.note = data['note']
            if 'name' in data and data['name']:
                case_subscription.rename_case(case_obj.name, data['name'])
                case_obj.name = data['name']
                db.session.commit()
                current_app.logger.debug(
                    'Case name changed from {0} to {1}'.format(
                        original_name, data['name']))
            if 'subscriptions' in data:
                case_obj.subscriptions = data['subscriptions']
                subscriptions = {
                    subscription['id']: subscription['events']
                    for subscription in data['subscriptions']
                }
                for uid, events in subscriptions.items():
                    case_subscription.modify_subscription(
                        case_name, uid, events)
            db.session.commit()
            return case_obj.as_json(), SUCCESS
        else:
            current_app.logger.error(
                'Cannot update case {0}. Case does not exist.'.format(
                    data['id']))
            return Problem.from_crud_resource(
                OBJECT_DNE_ERROR, 'case.', 'update',
                'Case {} does not exist.'.format(data['id']))
Example #13
0
    def __func():
        config_in = request.get_json()
        if not _reset_token_durations(access_token_duration=config_in.get('access_token_duration', None),
                                      refresh_token_duration=config_in.get('refresh_token_duration', None)):
            return Problem.from_crud_resource(
                BAD_REQUEST,
                'configuration',
                'update',
                'Access token duration must be less than refresh token duration.')

        for config, config_value in config_in.items():
            if hasattr(walkoff.config.Config, config.upper()):
                setattr(walkoff.config.Config, config.upper(), config_value)
            elif hasattr(current_app.config, config.upper()):
                setattr(current_app.config, config.upper(), config_value)

        current_app.logger.info('Changed configuration')
        try:
            walkoff.config.Config.write_values_to_file()
            return __get_current_configuration(), SUCCESS
        except (IOError, OSError) as e:
            current_app.logger.error('Could not write changes to configuration to file')
            return Problem(
                IO_ERROR,
                'Could not write changes to file.',
                'Could not write configuration changes to file. Problem: {}'.format(format_exception_message(e)))
Example #14
0
 def test_make_response_body_with_instance(self):
     self.expected['instance'] = self.instance
     self.assertEqual(
         Problem.make_response_body(self.status,
                                    self.title,
                                    self.detail,
                                    instance=self.instance),
         json.dumps(self.expected))
Example #15
0
 def test_make_response_body_with_ext(self):
     self.expected.update(self.ext)
     self.assertEqual(
         Problem.make_response_body(self.status,
                                    self.title,
                                    self.detail,
                                    ext=self.ext),
         json.dumps(self.expected))
Example #16
0
 def test_init_with_headers(self):
     problem = Problem(self.status,
                       self.title,
                       self.detail,
                       headers={'x-error': 'something'})
     response = json.loads(problem.response[0].decode('utf-8'))
     self.assertDictEqual(response, self.expected)
     self.assertIn('x-error', problem.headers)
Example #17
0
 def __func():
     data = request.get_json()
     refresh_token = data.get('refresh_token', None) if data else None
     if refresh_token is None:
         return Problem(BAD_REQUEST, 'Could not logout.', 'A refresh token is required to logout.')
     decoded_refresh_token = decode_token(refresh_token)
     refresh_token_identity = decoded_refresh_token[current_app.config['JWT_IDENTITY_CLAIM']]
     user_id = get_jwt_identity()
     if user_id == refresh_token_identity:
         user = User.query.filter(User.id == user_id).first()
         if user is not None:
             user.logout()
         revoke_token(decode_token(refresh_token))
         return None, NO_CONTENT
     else:
         return Problem(
             BAD_REQUEST,
             'Could not logout.',
             'The identity of the refresh token does not match the identity of the authentication token.')
Example #18
0
 def test_make_response_body_with_type(self):
     status = 404
     self.expected['type'] = self.type_
     self.expected['status'] = status
     self.assertEqual(
         Problem.make_response_body(status,
                                    self.title,
                                    self.detail,
                                    type_=self.type_),
         json.dumps(self.expected))
Example #19
0
    def __func():
        if request.files and 'file' in request.files:
            f = request.files['file']
            add_device_json = json.loads(f.read().decode('utf-8'))
        else:
            add_device_json = request.get_json()
        if current_app.running_context.execution_db.session.query(Device).filter(
                Device.name == add_device_json['name']).first() is not None:
            current_app.logger.error('Could not create device {0}. '
                                     'Device already exists.'.format(add_device_json['name']))
            return Problem.from_crud_resource(
                OBJECT_EXISTS_ERROR,
                'device',
                'create',
                'Device with name {} already exists.'.format(add_device_json['name']))

        fields = {field['name']: field['value'] for field in add_device_json['fields']}
        app = add_device_json['app_name']
        device_type = add_device_json['type']
        try:
            device_api = get_app_device_api(app, device_type)
            device_fields_api = device_api['fields']
            validate_device_fields(device_fields_api, fields, device_type, app)
        except (UnknownApp, UnknownDevice, InvalidArgument) as e:
            return __crud_device_error_handler('create', e, app, device_type)
        else:
            fields = add_device_json['fields']
            add_configuration_keys_to_device_json(fields, device_fields_api)
            app = current_app.running_context.execution_db.session.query(App).filter(App.name == app).first()
            if app is None:
                current_app.logger.error('SEVERE: App defined in api does not have corresponding entry in database. '
                                         'Cannot add device')
                return Problem.from_crud_resource(
                    INVALID_INPUT_ERROR,
                    'device',
                    'create',
                    'App {} does not exist.'.format(add_device_json['app_name']))
            device = Device.from_json(add_device_json)
            app.add_device(device)
            current_app.running_context.execution_db.session.add(device)
            current_app.running_context.execution_db.session.commit()
            device_json = get_device_json_with_app_name(device)
            return device_json, OBJECT_CREATED
Example #20
0
    def __func():
        try:
            result = case_database.case_db.case_events_as_json(case_id)
        except Exception:
            current_app.logger.error(
                'Cannot get events for case {0}. Case does not exist.'.format(
                    case_id))
            return Problem(OBJECT_DNE_ERROR, 'Could not read events for case.',
                           'Case {} does not exist.'.format(case_id))

        return result, SUCCESS
def stream_workflow_status():
    workflow_execution_id = request.args.get('workflow_execution_id', 'all')
    if workflow_execution_id != 'all':
        try:
            UUID(workflow_execution_id)
        except ValueError:
            return Problem(
                BAD_REQUEST,
                'Could not connect to action results stream',
                'workflow_execution_id must be a valid UUID')
    return workflow_stream.stream(subchannel=workflow_execution_id)
Example #22
0
def update_user_fields(data, user):
    original_username = str(user.username)
    if 'username' in data and data['username']:
        user_db = User.query.filter_by(username=data['username']).first()
        if user_db is None or user_db.id == user.id:
            user.username = data['username']
        else:
            return Problem(
                BAD_REQUEST, 'Cannot update user.',
                'Username {} is already taken.'.format(data['username']))
    if 'old_password' in data and 'password' in data:
        if user.verify_password(data['old_password']):
            user.password = data['password']
        else:
            user.username = original_username
            return Problem.from_crud_resource(
                UNAUTHORIZED_ERROR, 'user', 'update',
                'Current password is incorrect.')
    db.session.commit()
    current_app.logger.info('Updated user {0}. Updated to: {1}'.format(
        user.id, user.as_json()))
    return user.as_json(), SUCCESS
Example #23
0
    def __func():
        try:
            page = request.args.get('page', 1, type=int)
            result = current_app.running_context.case_db.case_events_as_json(
                case_id)
        except Exception:
            current_app.logger.error(
                'Cannot get events for case {0}. Case does not exist.'.format(
                    case_id))
            return Problem(OBJECT_DNE_ERROR, 'Could not read events for case.',
                           'Case {} does not exist.'.format(case_id))

        return result, SUCCESS
Example #24
0
def refresh():
    current_user_id = get_jwt_identity()
    user = User.query.filter(User.id == current_user_id).first()
    if user is None:
        revoke_token(get_raw_jwt())
        return Problem(
            UNAUTHORIZED_ERROR,
            'Could not grant access token.',
            'User {} from refresh JWT identity could not be found.'.format(current_user_id))
    if user.active:
        return {'access_token': create_access_token(identity=current_user_id, fresh=False)}, OBJECT_CREATED
    else:
        return user_deactivated_problem
Example #25
0
 def __func(user):
     if user.id != get_jwt_identity():
         db.session.delete(user)
         db.session.commit()
         current_app.logger.info('User {0} deleted'.format(user.username))
         return None, NO_CONTENT
     else:
         current_app.logger.error(
             'Could not delete user {0}. User is current user.'.format(
                 user.id))
         return Problem.from_crud_resource(
             FORBIDDEN_ERROR, 'user', 'delete',
             'Current user cannot delete self.')
Example #26
0
 def __func():
     case_obj = CaseSubscription.query.filter_by(id=case_id).first()
     if case_obj:
         delete_cases([case_obj.name])
         db.session.delete(case_obj)
         db.session.commit()
         current_app.logger.debug('Case deleted {0}'.format(case_id))
         return None, NO_CONTENT
     else:
         current_app.logger.error(
             'Cannot delete case {0}. Case does not exist.'.format(case_id))
         return Problem.from_crud_resource(
             OBJECT_DNE_ERROR, 'case', 'delete',
             'Case {} does not exist.'.format(case_id))
Example #27
0
    def __func():
        # TODO: Remove this once connexion can validate enums with openapi3.
        if field_name not in [
                'info', 'action_apis', 'condition_apis', 'transform_apis',
                'device_apis', 'tags', 'externalDocs'
        ]:
            return Problem(BAD_REQUEST, 'Could not read app api.',
                           '{} is not a valid field name.'.format(field_name))

        api = walkoff.config.app_apis.get(app_name, None)
        if api is not None:
            return format_full_app_api(api, app_name)[field_name], SUCCESS
        else:
            return app_api_dne_problem(app_name)
Example #28
0
    def __func(workflow):
        data = request.get_json()

        if 'name' in data and data['name']:
            new_workflow_name = data['name']
        else:
            new_workflow_name = workflow.name + "_Copy"

        workflow_json = workflow_schema.dump(workflow)
        workflow_json = workflow_json.data
        workflow_json.pop('id')
        workflow_json['name'] = new_workflow_name

        regenerate_workflow_ids(workflow_json)

        if executiondb.execution_db.session.query(
                exists().where(Playbook.id == playbook_id)).scalar():
            playbook = executiondb.execution_db.session.query(
                Playbook).filter_by(id=playbook_id).first()
        else:
            executiondb.execution_db.session.rollback()
            current_app.logger.error(
                'Could not copy workflow {}. Playbook does not exist'.format(
                    playbook_id))
            return Problem.from_crud_resource(
                OBJECT_DNE_ERROR, 'workflow', 'copy',
                'Could not copy workflow {}. Playbook with id {} does not exist.'
                .format(workflow_id, playbook_id))

        try:

            new_workflow = workflow_schema.load(workflow_json)
            new_workflow = new_workflow.data

            executiondb.execution_db.session.add(new_workflow)
            playbook.add_workflow(new_workflow)
            executiondb.execution_db.session.commit()
        except IntegrityError:
            executiondb.execution_db.session.rollback()
            current_app.logger.error(
                'Could not copy workflow {}. Unique constraint failed'.format(
                    new_workflow_name))
            return unique_constraint_problem('workflow', 'copy',
                                             new_workflow_name)

        current_app.logger.info('Workflow {0} copied to {1}'.format(
            workflow_id, new_workflow.id))
        return workflow_schema.dump(new_workflow).data, OBJECT_CREATED
Example #29
0
 def __func(user):
     data = request.get_json()
     current_user = get_jwt_identity()
     if user.id == current_user:
         return update_user_fields(data, user)
     else:
         response = role_update_user_fields(data, user, update=True)
         if isinstance(response, tuple) and response[1] == FORBIDDEN_ERROR:
             current_app.logger.error(
                 'User {0} does not have permission to '
                 'update user {1}'.format(current_user, user.id))
             return Problem.from_crud_resource(
                 FORBIDDEN_ERROR, 'user', 'update',
                 'Current user does not have permission to update user {}.'.
                 format(user_id))
         else:
             return response
Example #30
0
 def test_init(self):
     problem = Problem(self.status,
                       self.title,
                       self.detail,
                       instance=self.instance,
                       type_=self.type_,
                       ext=self.ext)
     self.expected.update(self.ext)
     self.expected.update({'type': self.type_, 'instance': self.instance})
     # For some reason Werkzueg puts the response in a list and as a bytes string in Python 3
     response = json.loads(problem.response[0].decode('utf-8'))
     self.assertDictEqual(response, self.expected)
     self.assertEqual(problem.status_code, self.status)
     self.assertEqual(len(problem.headers),
                      2)  # Content-Type and Content-Length
     self.assertEqual(problem.content_type, Problem.default_mimetype)
     self.assertEqual(problem.mimetype, Problem.default_mimetype)
Example #31
0
def act_on_message_helper(action):
    from walkoff.messaging import MessageAction, MessageActionEvent

    user_id = get_jwt_identity()
    user = User.query.filter(User.id == user_id).first()
    if user is None:
        return Problem(
            OBJECT_DNE_ERROR,
            'Cannot act on messages.',
            'User {} does not exist, so messages cannot be accessed.'.format(user_id))
    send_read_callback = action == MessageAction.read
    for message in (message for message in user.messages if message.id in request.get_json()['ids']):
        message.record_user_action(user, action)
        if send_read_callback:
            MessageActionEvent.read.send(message, data={'user': user})

    db.session.commit()
    return 'Success', SUCCESS
Example #32
0
    def __func(workflow):
        errors = workflow_schema.load(data, instance=workflow).errors
        if errors:
            return Problem.from_crud_resource(
                INVALID_INPUT_ERROR,
                'workflow',
                'update',
                'Could not update workflow {}. Invalid input.'.format(workflow_id), ext=errors)

        try:
            current_app.running_context.execution_db.session.commit()
        except IntegrityError:
            current_app.running_context.execution_db.session.rollback()
            current_app.logger.error('Could not update workflow {}. Unique constraint failed'.format(workflow_id))
            return unique_constraint_problem('workflow', 'update', workflow_id)

        current_app.logger.info('Updated workflow {0}'.format(workflow_id))
        return workflow_schema.dump(workflow), SUCCESS
Example #33
0
    def __func():
        data = request.get_json()
        username = data['username']
        if not User.query.filter_by(username=username).first():
            user = add_user(username=username, password=data['password'])

            if 'roles' in data or 'active' in data:
                role_update_user_fields(data, user)

            db.session.commit()
            current_app.logger.info('User added: {0}'.format(user.as_json()))
            return user.as_json(), OBJECT_CREATED
        else:
            current_app.logger.warning(
                'Cannot create user {0}. User already exists.'.format(
                    username))
            return Problem.from_crud_resource(
                OBJECT_EXISTS_ERROR, 'user', 'create',
                'User with username {} already exists'.format(username))
Example #34
0
    def __func():
        # TODO: Remove this once connexion can validate enums with openapi3.
        if field_name and field_name not in [
                'info', 'action_apis', 'condition_apis', 'transform_apis',
                'device_apis', 'tags', 'external_docs'
        ]:
            return Problem(BAD_REQUEST, 'Could not read app api.',
                           '{} is not a valid field name.'.format(field_name))

        ret = []
        for app_name, app_api in walkoff.config.app_apis.items():
            ret.append(format_full_app_api(app_api, app_name))
        if field_name is not None:
            default = [] if field_name not in ('info', 'external_docs') else {}
            ret = [{
                'name': api['name'],
                field_name: api.get(field_name, default)
            } for api in ret]
        return ret, SUCCESS
Example #35
0
 def __func():
     json_data = request.get_json()
     if not Role.query.filter_by(name=json_data['name']).first():
         resources = json_data['resources'] if 'resources' in json_data else []
         if '/roles' in resources:
             resources.remove('/roles')
         role_params = {'name': json_data['name'],
                        'description': json_data['description'] if 'description' in json_data else '',
                        'resources': resources}
         new_role = Role(**role_params)
         db.session.add(new_role)
         db.session.commit()
         current_app.logger.info('Role added: {0}'.format(role_params))
         return new_role.as_json(), OBJECT_CREATED
     else:
         current_app.logger.warning('Cannot add role {0}. Role already exists'.format(json_data['name']))
         return Problem.from_crud_resource(
             OBJECT_EXISTS_ERROR,
             'role',
             'create',
             'Role with name {} already exists'.format(json_data['name']))
Example #36
0
    def __func(workflow):
        data = request.get_json()

        if 'name' in data and data['name']:
            new_workflow_name = data['name']
        else:
            new_workflow_name = workflow.name + "_Copy"

        workflow_json = workflow_schema.dump(workflow)
        workflow_json.pop('id')
        workflow_json.pop('is_valid', None)
        workflow_json['name'] = new_workflow_name

        regenerate_workflow_ids(workflow_json)
        if current_app.running_context.execution_db.session.query(exists().where(Playbook.id == playbook_id)).scalar():
            playbook = current_app.running_context.execution_db.session.query(Playbook).filter_by(
                id=playbook_id).first()
        else:
            current_app.running_context.execution_db.session.rollback()
            current_app.logger.error('Could not copy workflow {}. Playbook does not exist'.format(playbook_id))
            return Problem.from_crud_resource(
                OBJECT_DNE_ERROR,
                'workflow',
                'copy',
                'Could not copy workflow {}. Playbook with id {} does not exist.'.format(workflow_id, playbook_id))

        try:

            new_workflow = workflow_schema.load(workflow_json)

            current_app.running_context.execution_db.session.add(new_workflow)
            playbook.add_workflow(new_workflow)
            current_app.running_context.execution_db.session.commit()
        except IntegrityError:
            current_app.running_context.execution_db.session.rollback()
            current_app.logger.error('Could not copy workflow {}. Unique constraint failed'.format(new_workflow_name))
            return unique_constraint_problem('workflow', 'copy', new_workflow_name)

        current_app.logger.info('Workflow {0} copied to {1}'.format(workflow_id, new_workflow.id))
        return workflow_schema.dump(new_workflow), OBJECT_CREATED
Example #37
0
 def test_make_response_body(self):
     self.assertEqual(Problem.make_response_body(self.status, self.title, self.detail), json.dumps(self.expected))
Example #38
0
def resource_not_found_problem(resource, operation, id_):
    return Problem.from_crud_resource(
        OBJECT_DNE_ERROR,
        resource,
        operation,
        '{} {} does not exist.'.format(resource.title(), id_))
Example #39
0
def invalid_id_problem(resource, operation):
    return Problem.from_crud_resource(BAD_REQUEST, resource, operation, 'Invalid ID format.')
Example #40
0
def unique_constraint_problem(type_, operation, id_):
    return Problem.from_crud_resource(
        OBJECT_EXISTS_ERROR,
        type_,
        operation,
        'Could not {} {} {}, possibly because of invalid or non-unique IDs.'.format(operation, type_, id_))
Example #41
0
 def test_make_response_body_with_type(self):
     status = 404
     self.expected['type'] = self.type_
     self.expected['status'] = status
     self.assertEqual(
         Problem.make_response_body(status, self.title, self.detail, type_=self.type_), json.dumps(self.expected))
Example #42
0
 def test_make_response_body_with_ext(self):
     self.expected.update(self.ext)
     self.assertEqual(
         Problem.make_response_body(self.status, self.title, self.detail, ext=self.ext),
         json.dumps(self.expected))
Example #43
0
def scheduled_task_name_already_exists_problem(name, operation):
    return Problem.from_crud_resource(
        OBJECT_EXISTS_ERROR,
        'scheduled task',
        operation,
        'Could not {} scheduled task. Scheduled task with name {} already exists.'.format(operation, name))
Example #44
0
 def test_make_response_body_with_instance(self):
     self.expected['instance'] = self.instance
     self.assertEqual(
         Problem.make_response_body(self.status, self.title, self.detail, instance=self.instance),
         json.dumps(self.expected))