Python werkzeug.middleware.proxy_fix.ProxyFix() Examples

The following are 9 code examples of werkzeug.middleware.proxy_fix.ProxyFix(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module werkzeug.middleware.proxy_fix , or try the search function .
Example #1
Source File: test_trackable.py    From flask-security with MIT License 6 votes vote down vote up
def test_trackable_with_multiple_ips_in_headers(app, client):
    app.wsgi_app = ProxyFix(app.wsgi_app, x_for=2)

    e = "matt@lp.com"
    authenticate(client, email=e)
    logout(client)
    authenticate(
        client,
        email=e,
        headers={"X-Forwarded-For": "99.99.99.99, 88.88.88.88, 77.77.77.77"},
    )

    with app.app_context():
        user = app.security.datastore.find_user(email=e)
        assert user.last_login_at is not None
        assert user.current_login_at is not None
        assert user.last_login_ip == _client_ip(client)
        assert user.current_login_ip == "88.88.88.88"
        assert user.login_count == 2 
Example #2
Source File: init_wsgi_middlewares.py    From airflow with Apache License 2.0 6 votes vote down vote up
def init_wsgi_middleware(flask_app: Flask):
    """Handle X-Forwarded-* headers and base_url support"""
    # Apply DispatcherMiddleware
    base_url = urlparse(conf.get('webserver', 'base_url'))[2]
    if not base_url or base_url == '/':
        base_url = ""
    if base_url:
        flask_app.wsgi_app = DispatcherMiddleware(  # type: ignore
            _root_app, mounts={base_url: flask_app.wsgi_app}
        )

    # Apply ProxyFix middleware
    if conf.getboolean('webserver', 'ENABLE_PROXY_FIX'):
        flask_app.wsgi_app = ProxyFix(  # type: ignore
            flask_app.wsgi_app,
            x_for=conf.getint("webserver", "PROXY_FIX_X_FOR", fallback=1),
            x_proto=conf.getint("webserver", "PROXY_FIX_X_PROTO", fallback=1),
            x_host=conf.getint("webserver", "PROXY_FIX_X_HOST", fallback=1),
            x_port=conf.getint("webserver", "PROXY_FIX_X_PORT", fallback=1),
            x_prefix=conf.getint("webserver", "PROXY_FIX_X_PREFIX", fallback=1),
        ) 
Example #3
Source File: app_object.py    From docassemble with MIT License 6 votes vote down vote up
def create_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    from docassemble.base.config import daconfig
    import docassemble.webapp.database
    import docassemble.webapp.db_object
    connect_string = docassemble.webapp.database.connection_string()
    alchemy_connect_string = docassemble.webapp.database.alchemy_connection_string()
    app.config['SQLALCHEMY_DATABASE_URI'] = alchemy_connect_string
    app.secret_key = daconfig.get('secretkey', '38ihfiFehfoU34mcq_4clirglw3g4o87')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db = docassemble.webapp.db_object.init_flask()
    db.init_app(app)
    csrf = CSRFProtect()
    csrf.init_app(app)
    babel = Babel()
    babel.init_app(app)
    if daconfig.get('behind https load balancer', False):
        if proxyfix_version >= 15:
            app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)
        else:
            app.wsgi_app = ProxyFix(app.wsgi_app)
    if 'cross site domains' in daconfig:
        CORS(app, origins=daconfig['cross site domains'], supports_credentials=True)
    return app, csrf, babel 
Example #4
Source File: test_trackable.py    From flask-security with MIT License 5 votes vote down vote up
def test_trackable_flag(app, client):
    app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1)
    e = "matt@lp.com"
    authenticate(client, email=e)
    logout(client)
    authenticate(client, email=e, headers={"X-Forwarded-For": "127.0.0.1"})

    with app.app_context():
        user = app.security.datastore.find_user(email=e)
        assert user.last_login_at is not None
        assert user.current_login_at is not None
        assert user.last_login_ip == _client_ip(client)
        assert user.current_login_ip == "127.0.0.1"
        assert user.login_count == 2 
Example #5
Source File: test_trackable.py    From flask-security with MIT License 5 votes vote down vote up
def test_trackable_using_login_user(app, client):
    """
    This tests is only to serve as an example of how one needs to call
    datastore.commit() after logging a user in to make sure the trackable
    fields are saved to the datastore.
    """
    app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1)

    @app.route("/login_custom", methods=["POST"])
    def login_custom():
        user = app.security.datastore.find_user(email=e)
        login_user(user)

        @after_this_request
        def save_user(response):
            app.security.datastore.commit()
            return response

        return redirect("/")

    e = "matt@lp.com"
    authenticate(client, email=e)
    logout(client)

    data = dict(email=e, password="password", remember="y")
    client.post("/login_custom", data=data, headers={"X-Forwarded-For": "127.0.0.1"})

    with app.app_context():
        user = app.security.datastore.find_user(email=e)
        assert user.last_login_at is not None
        assert user.current_login_at is not None
        assert user.last_login_ip == _client_ip(client)
        assert user.current_login_ip == "127.0.0.1"
        assert user.login_count == 2 
Example #6
Source File: server.py    From powerfulseal with Apache License 2.0 5 votes vote down vote up
def start_server(host, port, policy, accept_proxy_headers=False, logger=None):
    if accept_proxy_headers:
        app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_port=1, x_prefix=1)
    config["policy"] = policy
    config["logger"] = logger
    threading.Thread(target=app.run, args=(host, port), daemon=True).start() 
Example #7
Source File: proxy_fix.py    From notifications-admin with MIT License 5 votes vote down vote up
def __init__(self, app, forwarded_proto):
        self.app = ProxyFix(app, x_for=1, x_proto=1, x_host=1, x_port=0, x_prefix=0)
        self.forwarded_proto = forwarded_proto 
Example #8
Source File: apiserver.py    From oxfs with MIT License 4 votes vote down vote up
def start_service(self, port):
        apiserver = self
        self.app = Flask(__name__)
        self.app.wsgi_app = ProxyFix(self.app.wsgi_app)
        self.api = Api(self.app, version='1.0', title='Oxfs Api',
                       description='The Oxfs Api')

        # Response model
        fs_namespace = self.api.namespace('fs', description='fs operations')
        status_model = self.api.model(
            'Status',
            {
                'status': fields.Boolean,
                'data': fields.String
            })

        # Request arguments
        string_args = self.api.parser()
        string_args.add_argument('path', required=True, help='absolute path')

        # Api
        @fs_namespace.route('/reload')
        @fs_namespace.expect(string_args)
        class Reload(Resource):
            @fs_namespace.marshal_with(status_model, envelope='data')
            def post(self):
                args = string_args.parse_args()
                path = apiserver.oxfs_fuse.remotepath(args['path'])
                status = (apiserver.cleanf(path), apiserver.cleand(path))
                return {'status': False not in status, 'data': path}

        @fs_namespace.route('/clear')
        class Clear(Resource):
            @fs_namespace.marshal_with(status_model, envelope='data')
            def delete(self):
                status = apiserver.clear()
                return {'status': True, 'data': 'success'}

        @fs_namespace.route('/directories')
        @fs_namespace.expect(string_args)
        class Directories(Resource):
            @fs_namespace.marshal_with(status_model, envelope='data')
            def get(self):
                args = string_args.parse_args()
                path = apiserver.oxfs_fuse.remotepath(args['path'])
                status, data = apiserver.fetchd(path)
                return {'status': status, 'data': data}

        self.set_flask_env()
        self.app.run(port=port, debug=False) 
Example #9
Source File: app.py    From incubator-superset with Apache License 2.0 4 votes vote down vote up
def configure_middlewares(self) -> None:
        if self.config["ENABLE_CORS"]:
            from flask_cors import CORS

            CORS(self.flask_app, **self.config["CORS_OPTIONS"])

        if self.config["ENABLE_PROXY_FIX"]:
            from werkzeug.middleware.proxy_fix import ProxyFix

            self.flask_app.wsgi_app = ProxyFix(  # type: ignore
                self.flask_app.wsgi_app, **self.config["PROXY_FIX_CONFIG"]
            )

        if self.config["ENABLE_CHUNK_ENCODING"]:

            class ChunkedEncodingFix:  # pylint: disable=too-few-public-methods
                def __init__(self, app: Flask) -> None:
                    self.app = app

                def __call__(
                    self, environ: Dict[str, Any], start_response: Callable[..., Any]
                ) -> Any:
                    # Setting wsgi.input_terminated tells werkzeug.wsgi to ignore
                    # content-length and read the stream till the end.
                    if environ.get("HTTP_TRANSFER_ENCODING", "").lower() == "chunked":
                        environ["wsgi.input_terminated"] = True
                    return self.app(environ, start_response)

            self.flask_app.wsgi_app = ChunkedEncodingFix(  # type: ignore
                self.flask_app.wsgi_app  # type: ignore
            )

        if self.config["UPLOAD_FOLDER"]:
            try:
                os.makedirs(self.config["UPLOAD_FOLDER"])
            except OSError:
                pass

        for middleware in self.config["ADDITIONAL_MIDDLEWARE"]:
            self.flask_app.wsgi_app = middleware(  # type: ignore
                self.flask_app.wsgi_app
            )

        # Flask-Compress
        Compress(self.flask_app)

        if self.config["TALISMAN_ENABLED"]:
            talisman.init_app(self.flask_app, **self.config["TALISMAN_CONFIG"])