def test_exception_handler(test_app):
    exception_handler.add_exception_handlers(test_app.application)

    @test_app.application.route("/endpoint/")
    @use_kwargs({'param1': webargs_fields.Int(),
                 'param2': webargs_fields.String(required=True),
                 'param3': webargs_fields.Int(required=True)
                 })
    def handle(param1, param2):
        pass

    result = test_app.get('/endpoint/?param1=not-a-string&param3=3')
    assert result.status_code == 400
    result = json.loads(result.data.decode('UTF-8'))
    assert result['message'] == ('param1: Not a valid integer. '
                                 'param2: Missing data for required field.')
Esempio n. 2
0
def test_exception_handler(test_app):
    exception_handler.add_exception_handlers(test_app.application)

    @test_app.application.route("/endpoint/")
    @use_kwargs({
        'param1': webargs_fields.Int(),
        'param2': webargs_fields.String(required=True),
        'param3': webargs_fields.Int(required=True)
    })
    def handle(param1, param2):
        pass

    result = test_app.get('/endpoint/?param1=not-a-string&param3=3')
    assert result.status_code == 400
    result = json.loads(result.data.decode('UTF-8'))
    assert result['message'] == ('param1: Not a valid integer. '
                                 'param2: Missing data for required field.')
Esempio n. 3
0
def create_app():
    """Set up the application."""
    flask_app = Flask(__name__.split('.')[0])
    local = CONFIG_BROKER['local']
    flask_app.config.from_object(__name__)
    flask_app.config['LOCAL'] = local
    flask_app.debug = CONFIG_SERVICES['debug']
    flask_app.config['SYSTEM_EMAIL'] = CONFIG_BROKER['reply_to_email']

    # Future: Override config w/ environment variable, if set
    flask_app.config.from_envvar('BROKER_SETTINGS', silent=True)

    # Set parameters
    broker_file_path = CONFIG_BROKER['broker_files']
    AccountHandler.FRONT_END = CONFIG_BROKER['full_url']
    SesEmail.SIGNING_KEY = CONFIG_BROKER['email_token_key']
    SesEmail.isLocal = local
    if SesEmail.isLocal:
        SesEmail.emailLog = os.path.join(broker_file_path, 'email.log')
    # If local, make the email directory if needed
    if local and not os.path.exists(broker_file_path):
        os.makedirs(broker_file_path)

    JsonResponse.debugMode = flask_app.debug

    if CONFIG_SERVICES['cross_origin_url'] == "*":
        CORS(flask_app, supports_credentials=False, allow_headers="*", expose_headers="X-Session-Id")
    else:
        CORS(flask_app, supports_credentials=False, origins=CONFIG_SERVICES['cross_origin_url'],
             allow_headers="*", expose_headers="X-Session-Id")
    # Enable DB session table handling
    flask_app.session_interface = UserSessionInterface()
    # Set up bcrypt
    bcrypt = Bcrypt(flask_app)

    @flask_app.teardown_appcontext
    def teardown_appcontext(exception):
        GlobalDB.close()

    @flask_app.before_request
    def before_request():
        # Set global value for local
        g.is_local = local
        sess = GlobalDB.db().session
        # setup user
        g.user = None
        if session.get('name') is not None:
            g.user = sess.query(User).filter_by(user_id=session['name']).one_or_none()

    # Root will point to index.html
    @flask_app.route("/", methods=["GET"])
    def root():
        return "Broker is running"

    @flask_app.errorhandler(ResponseException)
    def handle_response_exception(exception):
        return JsonResponse.error(exception, exception.status)

    @flask_app.errorhandler(Exception)
    def handle_exception(exception):
        wrapped = ResponseException(str(exception), StatusCode.INTERNAL_ERROR, type(exception))
        return JsonResponse.error(wrapped, wrapped.status)

    # Add routes for modules here
    add_login_routes(flask_app, bcrypt)

    add_file_routes(flask_app, CONFIG_BROKER['aws_create_temp_credentials'], local, broker_file_path)
    add_user_routes(flask_app, flask_app.config['SYSTEM_EMAIL'], bcrypt)
    add_domain_routes(flask_app)
    add_exception_handlers(flask_app)
    return flask_app
Esempio n. 4
0
def create_app():
    """Set up the application."""
    flask_app = Flask(__name__.split('.')[0])
    local = CONFIG_BROKER['local']
    flask_app.config.from_object(__name__)
    flask_app.config['LOCAL'] = local
    flask_app.debug = CONFIG_SERVICES['debug']
    flask_app.env = 'development' if CONFIG_SERVICES['debug'] else 'production'
    flask_app.config['SYSTEM_EMAIL'] = CONFIG_BROKER['reply_to_email']
    # Make the app not care if there's a trailing slash or not
    flask_app.url_map.strict_slashes = False

    # Future: Override config w/ environment variable, if set
    flask_app.config.from_envvar('BROKER_SETTINGS', silent=True)

    # Set parameters
    broker_file_path = CONFIG_BROKER['broker_files']
    AccountHandler.FRONT_END = CONFIG_BROKER['full_url']
    SesEmail.is_local = local
    if SesEmail.is_local:
        SesEmail.emailLog = os.path.join(broker_file_path, 'email.log')
    # If local, make the email directory if needed
    if local and not os.path.exists(broker_file_path):
        os.makedirs(broker_file_path)

    JsonResponse.debugMode = flask_app.debug

    if CONFIG_SERVICES['cross_origin_url'] == "*":
        CORS(flask_app, supports_credentials=False, allow_headers="*", expose_headers="X-Session-Id")
    else:
        CORS(flask_app, supports_credentials=False, origins=CONFIG_SERVICES['cross_origin_url'],
             allow_headers="*", expose_headers="X-Session-Id")
    # Enable DB session table handling
    flask_app.session_interface = UserSessionInterface()
    # Set up bcrypt
    bcrypt = Bcrypt(flask_app)

    @flask_app.teardown_appcontext
    def teardown_appcontext(exception):
        GlobalDB.close()

    @flask_app.before_request
    def before_request():
        # Set global value for local
        g.is_local = local
        sess = GlobalDB.db().session
        # setup user
        g.user = None
        if session.get('name') is not None:
            g.user = sess.query(User).filter_by(user_id=session['name']).one_or_none()

        content_type = request.headers.get('Content-Type')

        # If the request is a POST we want to log the request body
        if request.method == 'POST' and content_type and 'login' not in request.url.lower():
            request_body = {}

            # If request is json, turn it into a dict
            if 'application/json' in content_type:
                request_body = json.loads(request.get_data().decode('utf8'))
            elif 'multipart/form-data' in content_type:
                # If request is a multipart request, get only the form portions of it
                for key in request.form.keys():
                    request_body[key] = request.form[key]

            request_dict = {
                'message': 'Request body for ' + request.url,
                'body': request_body
            }
            logger.info(request_dict)

    # Root will point to index.html
    @flask_app.route("/", methods=["GET"])
    def root():
        return "Broker is running"

    @flask_app.errorhandler(ResponseException)
    def handle_response_exception(exception):
        return JsonResponse.error(exception, exception.status)

    @flask_app.errorhandler(Exception)
    def handle_exception(exception):
        wrapped = ResponseException(str(exception), StatusCode.INTERNAL_ERROR, type(exception))
        return JsonResponse.error(wrapped, wrapped.status)

    # Add routes for modules here
    add_login_routes(flask_app, bcrypt)

    add_file_routes(flask_app, local, broker_file_path)
    add_generation_routes(flask_app, local, broker_file_path)
    add_user_routes(flask_app, flask_app.config['SYSTEM_EMAIL'], bcrypt)
    add_dashboard_routes(flask_app)
    add_settings_routes(flask_app)
    add_domain_routes(flask_app)
    add_exception_handlers(flask_app)
    return flask_app
Esempio n. 5
0
def create_app():
    """Set up the application."""
    flask_app = Flask(__name__.split('.')[0])
    local = CONFIG_BROKER['local']
    flask_app.config.from_object(__name__)
    flask_app.config['LOCAL'] = local
    flask_app.debug = CONFIG_SERVICES['debug']
    flask_app.env = 'development' if CONFIG_SERVICES['debug'] else 'production'
    flask_app.config['SYSTEM_EMAIL'] = CONFIG_BROKER['reply_to_email']

    # Future: Override config w/ environment variable, if set
    flask_app.config.from_envvar('BROKER_SETTINGS', silent=True)

    # Set parameters
    broker_file_path = CONFIG_BROKER['broker_files']
    AccountHandler.FRONT_END = CONFIG_BROKER['full_url']
    SesEmail.is_local = local
    if SesEmail.is_local:
        SesEmail.emailLog = os.path.join(broker_file_path, 'email.log')
    # If local, make the email directory if needed
    if local and not os.path.exists(broker_file_path):
        os.makedirs(broker_file_path)

    JsonResponse.debugMode = flask_app.debug

    if CONFIG_SERVICES['cross_origin_url'] == "*":
        CORS(flask_app, supports_credentials=False, allow_headers="*", expose_headers="X-Session-Id")
    else:
        CORS(flask_app, supports_credentials=False, origins=CONFIG_SERVICES['cross_origin_url'],
             allow_headers="*", expose_headers="X-Session-Id")
    # Enable DB session table handling
    flask_app.session_interface = UserSessionInterface()
    # Set up bcrypt
    bcrypt = Bcrypt(flask_app)

    @flask_app.teardown_appcontext
    def teardown_appcontext(exception):
        GlobalDB.close()

    @flask_app.before_request
    def before_request():
        # Set global value for local
        g.is_local = local
        sess = GlobalDB.db().session
        # setup user
        g.user = None
        if session.get('name') is not None:
            g.user = sess.query(User).filter_by(user_id=session['name']).one_or_none()

    # Root will point to index.html
    @flask_app.route("/", methods=["GET"])
    def root():
        return "Broker is running"

    @flask_app.errorhandler(ResponseException)
    def handle_response_exception(exception):
        return JsonResponse.error(exception, exception.status)

    @flask_app.errorhandler(Exception)
    def handle_exception(exception):
        wrapped = ResponseException(str(exception), StatusCode.INTERNAL_ERROR, type(exception))
        return JsonResponse.error(wrapped, wrapped.status)

    # Add routes for modules here
    add_login_routes(flask_app, bcrypt)

    add_file_routes(flask_app, local, broker_file_path)
    add_generation_routes(flask_app, local, broker_file_path)
    add_user_routes(flask_app, flask_app.config['SYSTEM_EMAIL'], bcrypt)
    add_domain_routes(flask_app)
    add_exception_handlers(flask_app)
    return flask_app
Esempio n. 6
0
def createApp():
    """Set up the application."""
    app = Flask(__name__.split('.')[0])
    local = CONFIG_BROKER['local']
    app.config.from_object(__name__)
    app.config['LOCAL'] = local
    app.debug = CONFIG_SERVICES['debug']
    app.config['SYSTEM_EMAIL'] = CONFIG_BROKER['reply_to_email']

    # Future: Override config w/ environment variable, if set
    app.config.from_envvar('BROKER_SETTINGS', silent=True)

    # Set parameters
    broker_file_path = CONFIG_BROKER['broker_files']
    AccountHandler.FRONT_END = CONFIG_BROKER['full_url']
    sesEmail.SIGNING_KEY = CONFIG_BROKER['email_token_key']
    sesEmail.isLocal = local
    if sesEmail.isLocal:
        sesEmail.emailLog = os.path.join(broker_file_path, 'email.log')
    # If local, make the email directory if needed
    if local and not os.path.exists(broker_file_path):
        os.makedirs(broker_file_path)

    JsonResponse.debugMode = app.debug

    if CONFIG_SERVICES['cross_origin_url'] == "*":
        cors = CORS(app,
                    supports_credentials=False,
                    allow_headers="*",
                    expose_headers="X-Session-Id")
    else:
        cors = CORS(app,
                    supports_credentials=False,
                    origins=CONFIG_SERVICES['cross_origin_url'],
                    allow_headers="*",
                    expose_headers="X-Session-Id")
    # Enable DB session table handling
    app.session_interface = UserSessionInterface()
    # Set up bcrypt
    bcrypt = Bcrypt(app)

    @app.teardown_appcontext
    def teardown_appcontext(exception):
        GlobalDB.close()

    @app.before_request
    def before_request():
        GlobalDB.db()

    # Root will point to index.html
    @app.route("/", methods=["GET"])
    def root():
        return "Broker is running"

    @app.errorhandler(ResponseException)
    def handle_response_exception(exception):
        return JsonResponse.error(exception, exception.status)

    @app.errorhandler(Exception)
    def handle_exception(exception):
        wrapped = ResponseException(str(exception), StatusCode.INTERNAL_ERROR,
                                    type(exception))
        return JsonResponse.error(wrapped, wrapped.status)

    # Add routes for modules here
    add_login_routes(app, bcrypt)

    add_file_routes(app, CONFIG_BROKER['aws_create_temp_credentials'], local,
                    broker_file_path, bcrypt)
    add_user_routes(app, app.config['SYSTEM_EMAIL'], bcrypt)
    add_domain_routes(app, local, bcrypt)
    add_exception_handlers(app)
    return app