def create_app(test_config=None): app = Flask(__name__) app.config['MONGODB_HOST'] = os.getenv('MONGODB_HOST') app.config['SECRET_KEY'] = os.urandom(32) db.init_app(app) login_manager.init_app(app) bcrypt.init_app(app) # Register new blueprints app.register_blueprint(users) app.register_blueprint(groups) app.register_blueprint(polls) # Register error handler app.register_error_handler(404, page_not_found) login_manager.login_view = "users.login" csp = { 'default-src': ['\'self\'', 'https://plotly.com/'], 'script-src': [ 'https://stackpath.bootstrapcdn.com/bootstrap/', 'https://code.jquery.com/', 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/', '\'unsafe-inline\'', '\'unsafe-eval\'' ], 'style-src': [ 'https://stackpath.bootstrapcdn.com/bootstrap/', '\'unsafe-inline\'', '\'unsafe-eval\'' ] } Talisman(app, content_security_policy=csp) return app
def setUp(self): self.app = flask.Flask(__name__) self.talisman = Talisman(self.app) self.client = self.app.test_client() self.app.route('/')(hello_world) self.app.route('/with_nonce')(with_nonce)
def create_webapp(deployer, cluster, release_channel_factory, status): from flask_bootstrap import Bootstrap from flask_talisman import Talisman, DENY from ..web.api import api from ..web.frontend import frontend from ..web.healthcheck import healthcheck from ..web.metrics import metrics from .nav import nav app = Flask(__name__) # TODO: These options are like this because we haven't set up TLS csp = { 'default-src': SELF, 'script-src': [SELF], 'style-src': [SELF], 'object-src': [NONE] } Talisman(app, frame_options=DENY, force_https=False, strict_transport_security=False, content_security_policy=csp) Bootstrap(app) app.config['BOOTSTRAP_SERVE_LOCAL'] = True api.cluster = cluster api.deployer = deployer api.status = status frontend.release_channel_factory = release_channel_factory healthcheck.status = status app.register_blueprint(api) app.register_blueprint(frontend) app.register_blueprint(metrics) app.register_blueprint(healthcheck) nav.init_app(app) _connect_signals() return app
def setup_basic_security(app: Flask): """ Apply some basic security specifications over the HTTP exchanges. """ csp = GOOGLE_CSP_POLICY.copy() csp["style-src"] = csp["style-src"].split(' ') csp["style-src"].append("*.fontawesome.com") csp["style-src"].append("*.cloudflare.com") csp["style-src"].append("'unsafe-inline'") csp["font-src"] = csp["font-src"].split(' ') csp["font-src"].append("*.fontawesome.com") csp["font-src"].append("'unsafe-inline'") csp["default-src"] = csp["default-src"].split(' ') # csp["default-src"].append("'self'") csp["img-src"] = [] csp["img-src"].append("'self'") Talisman(app, force_https=False, strict_transport_security=False, session_cookie_secure=False, content_security_policy=csp)
def create_app(test_config=None): app = Flask(__name__) app.config.from_pyfile("config.py", silent=False) if test_config is not None: app.config.update(test_config) app.config["MONGODB_HOST"] = os.getenv("MONGODB_HOST") db.init_app(app) login_manager.init_app(app) bcrypt.init_app(app) app.register_blueprint(users) app.register_blueprint(dogs) app.register_error_handler(404, page_not_found) inline = '\'unsafe-inline\'' login_manager.login_view = "users.login" csp = { 'default-src': ['\'self\'', 'https://dog.ceo/api'], 'img-src': ['*','\'self\'', 'data:'], 'style-src': ['https://stackpath.bootstrapcdn.com/bootstrap/','\'self\'','*.plot.ly/','https://js.stripe.com', inline], 'script-src': [inline,'\'unsafe-eval\'','https://stackpath.bootstrapcdn.com/bootstrap/', 'https://code.jquery.com/', 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js','\'self\'','https://cdn.plot.ly/plotly-latest.min.js','*.plot.ly', 'https://cdn.plot.ly', 'https://js.stripe.com','https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js.map'], 'media-src': ['https://dog.ceo/api','https://plot.ly/','https://cdn.plot.ly/plotly-gl2d-latest.min.js'], } Talisman(app, content_security_policy=csp) return app
def testPermissionsPolicy(self): # default disabled FLoC response = self.client.get('/', environ_overrides=HTTPS_ENVIRON) permissions_policy = response.headers['Permissions-Policy'] self.assertIn('interest-cohort=()', permissions_policy) self.talisman.permissions_policy['geolocation'] = '()' response = self.client.get('/', environ_overrides=HTTPS_ENVIRON) permissions_policy = response.headers['Permissions-Policy'] self.assertIn('geolocation=()', permissions_policy) self.talisman.permissions_policy['geolocation'] = '()' self.talisman.permissions_policy[ 'fullscreen'] = '(self, "https://example.com")' response = self.client.get('/', environ_overrides=HTTPS_ENVIRON) permissions_policy = response.headers['Permissions-Policy'] self.assertIn( 'geolocation=(), fullscreen=(self, "https://example.com")', permissions_policy) # no policy self.talisman.permissions_policy = {} response = self.client.get('/', environ_overrides=HTTPS_ENVIRON) permissions_policy = response.headers.get('Permissions-Policy') self.assertEqual(None, permissions_policy) # string policy at initialization app = flask.Flask(__name__) Talisman(app, permissions_policy='vibrate=(), geolocation=()') response = app.test_client().get('/', environ_overrides=HTTPS_ENVIRON) self.assertIn('vibrate=(), geolocation=()', response.headers['Permissions-Policy'])
def init_app(self, app, **kwargs): """Initialize application object. :param app: An instance of :class:`~flask.Flask`. """ # Init the configuration self.init_config(app) # Enable Rate limiter self.limiter = Limiter(app, key_func=get_ipaddr) # Enable secure HTTP headers if app.config['APP_ENABLE_SECURE_HEADERS']: self.talisman = Talisman( app, **app.config.get('APP_DEFAULT_SECURE_HEADERS', {})) # Enable PING view if app.config['APP_HEALTH_BLUEPRINT_ENABLED']: blueprint = Blueprint('invenio_app_ping', __name__) @blueprint.route('/ping') def ping(): """Load balancer ping view.""" return 'OK' ping.talisman_view_options = {'force_https': False} app.register_blueprint(blueprint) # Register self app.extensions['invenio-app'] = self
def create_app(): app = Flask(__name__) #csrf = SeaSurf(app) csp = { 'script-src': '\'self\' \'unsafe-eval\' dal2iwprittp7.cloudfront.net code.jquery.com', 'default-src': '\'self\' dal2iwprittp7.cloudfront.net', 'style-src': '\'self\' dal2iwprittp7.cloudfront.net fonts.googleapis.com fonts.gstatic.com', 'font-src': '\'self\' use.fontawesome.com dal2iwprittp7.cloudfront.net fonts.googleapis.com fonts.gstatic.com data:', 'img-src': '\'self\' dal2iwprittp7.cloudfront.net data:', 'worker-src': '\'self\' blob:' } Talisman(app, \ strict_transport_security=False, \ force_https=False, \ session_cookie_secure=False, \ content_security_policy=csp) app.config.from_pyfile('settings.py') #app.secret_key = 'gthSckChOFUF0bclBO3s' # import blueprints from .base.views import base_app # register blueprints app.register_blueprint(base_app) return app
def create_app(config_name): app = Flask(__name__) app.config['CONSENT_FULL_TEMPLATE'] = 'consent.html' app.config['CONSENT_BANNER_TEMPLATE'] = 'consent_banner.html' # consent = Consent(app) # consent.add_standard_categories() app.config.from_object(config[config_name]) config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) login_manager.init_app(app) pagedown.init_app(app) nav.init_app(app) Markdown(app, extensions=['fenced_code']) if app.config['SSL_REDIRECT']: from flask_talisman import Talisman Talisman(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .navs.nav_items import NavItems as NavItems nav.register_element('top', NavItems.topbar) return app
def create_app(): app = Flask(__name__) csp = { 'default-src': [ '\'self\'', '\'unsafe-inline\'', '\'unsafe-eval\'', 'stackpath.bootstrapcdn.com', 'code.jquery.com', 'cdn.jsdelivr.net' ], 'img-src': ['\'self\'', 'data:'] } Talisman(app, content_security_policy=csp) app.config.from_pyfile("config.py", silent=False) db.init_app(app) login_manager.init_app(app) bcrypt.init_app(app) app.register_blueprint(users) app.register_blueprint(report) app.register_error_handler(404, page_not_found) login_manager.login_view = "users.login" return app
def create_app(): app = Flask(__name__) #app.config.from_pyfile("config.py", silent=False) #to run app locally, export the MONGODB_HOST Variable in terminal app.config["MONGODB_HOST"] = os.getenv("MONGODB_HOST") app.config[ "SECRET_KEY"] = b'\x020;yr\x91\x11\xbe"\x9d\xc1\x14\x91\xadf\xec' csp = { 'script-src': 'https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css' } db.init_app(app) login_manager.init_app(app) bcrypt.init_app(app) Talisman(app, content_security_policy=csp) app.register_blueprint(users) app.register_blueprint(landlords) login_manager.login_view = "users.login" return app
def create_app(config_class=Config): app = Flask(__name__, static_url_path='', static_folder='client/build') app.config.from_object(config_class) Talisman(app, content_security_policy=None) from shopping_list.modules.items import models from shopping_list.modules.groups import models db.app = app db.init_app(app) with app.app_context(): db.create_all() api.app = app CORS(app) @app.route('/') def serve(): return send_from_directory(app.static_folder, 'index.html') from .modules.items import routes from .modules.alerts import routes from .modules.groups import routes return app
def register_extensions(app): """ register extensions to the app """ app.jinja_env.add_extension('jinja2.ext.do') # Global values in jinja db.init_app(app) # Influx db time-series database init_api(app) app = extension_babel(app) # Language translations app = extension_compress(app) # Compress app responses with gzip app = extension_limiter(app) # Limit authentication blueprint requests to 200 per minute app = extension_login_manager(app) # User login management app = extension_session(app) # Server side session # Create and populate database if it doesn't exist with app.app_context(): db.create_all() populate_db() # This is disabled because there's a bug that messes up user databases # The upgrade script will execute alembic to upgrade the database # alembic_upgrade_db() # Check user option to force all web connections to use SSL # Fail if the URI is empty (pytest is running) if app.config['SQLALCHEMY_DATABASE_URI'] != 'sqlite://': with session_scope(app.config['SQLALCHEMY_DATABASE_URI']) as new_session: misc = new_session.query(Misc).first() if misc and misc.force_https: csp = {'default-src': ['*', '\'unsafe-inline\'', '\'unsafe-eval\'']} Talisman(app, content_security_policy=csp)
def testContentSecurityPolicyOptions(self): self.talisman.content_security_policy['image-src'] = '*' response = self.client.get('/', environ_overrides=HTTPS_ENVIRON) csp = response.headers['Content-Security-Policy'] self.assertEqual(csp, "default-src 'self'; image-src *") self.talisman.content_security_policy['image-src'] = [ '\'self\'', 'example.com' ] response = self.client.get('/', environ_overrides=HTTPS_ENVIRON) csp = response.headers['Content-Security-Policy'] self.assertIn('default-src \'self\'', csp) self.assertIn('image-src \'self\' example.com', csp) # string policy self.talisman.content_security_policy = 'default-src \'foo\' spam.eggs' response = self.client.get('/', environ_overrides=HTTPS_ENVIRON) self.assertEqual(response.headers['Content-Security-Policy'], 'default-src \'foo\' spam.eggs') # no policy self.talisman.content_security_policy = False response = self.client.get('/', environ_overrides=HTTPS_ENVIRON) self.assertNotIn('Content-Security-Policy', response.headers) # string policy at initialization app = flask.Flask(__name__) Talisman(app, content_security_policy='default-src \'foo\' spam.eggs') response = app.test_client().get('/', environ_overrides=HTTPS_ENVIRON) self.assertIn('default-src \'foo\' spam.eggs', response.headers['Content-Security-Policy'])
def _before_adding_routes(app, app_config): script_hashes, style_hashes = WSGIServer.get_csp_hashes( app, app_config) server_config = app_config.server_config csp = { "default-src": ["'self'"], "connect-src": ["'self'"], "script-src": ["'self'", "'unsafe-eval'", "'unsafe-inline'"] + script_hashes, "style-src": ["'self'", "'unsafe-inline'"] + style_hashes, "img-src": ["'self'", "data:"], "object-src": ["'none'"], "base-uri": ["'none'"], "frame-ancestors": ["'none'"], } if not app.debug: csp["upgrade-insecure-requests"] = "" if server_config.app__csp_directives: for k, v in server_config.app__csp_directives.items(): if not isinstance(v, list): v = [v] csp[k] = csp.get(k, []) + v Talisman( app, force_https=server_config.app__force_https, frame_options="DENY", content_security_policy=csp, )
def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) mongo.init_app(app) app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True from app.users.routes import users from app.main.routes import main from app.recipes.routes import recipes app.register_blueprint(users) app.register_blueprint(main) app.register_blueprint(recipes) csp = { 'default-src': [ '\'unsafe-inline\' \'self\'', '*.cloudflare.com', '*.fontawesome.com', '*.googleapis.com', '*.gstatic.com' ], 'img-src': '*', 'script-src': [ '\'unsafe-inline\' \'self\'', '*.cloudflare.com', '*.fontawesome.com', '*.googleapis.com', '*.gstatic.com' ] } Talisman(app, content_security_policy=csp) return app
def testContentSecurityPolicyOptions(self): self.talisman.content_security_policy['image-src'] = '*' response = self.client.get('/', environ_overrides=HTTPS_ENVIRON) csp = response.headers['Content-Security-Policy'] self.assertIn("default-src 'self';", csp) self.assertIn("object-src \'none\';", csp) self.assertIn("image-src *", csp) self.talisman.content_security_policy['image-src'] = [ '\'self\'', 'example.com' ] response = self.client.get('/', environ_overrides=HTTPS_ENVIRON) csp = response.headers['Content-Security-Policy'] self.assertIn('default-src \'self\'', csp) self.assertIn('image-src \'self\' example.com', csp) # string policy self.talisman.content_security_policy = 'default-src \'foo\' spam.eggs' response = self.client.get('/', environ_overrides=HTTPS_ENVIRON) self.assertEqual(response.headers['Content-Security-Policy'], 'default-src \'foo\' spam.eggs') # no policy self.talisman.content_security_policy = False response = self.client.get('/', environ_overrides=HTTPS_ENVIRON) self.assertNotIn('Content-Security-Policy', response.headers) # string policy at initialization app = flask.Flask(__name__) Talisman(app, content_security_policy='default-src \'foo\' spam.eggs') response = app.test_client().get('/', environ_overrides=HTTPS_ENVIRON) self.assertIn('default-src \'foo\' spam.eggs', response.headers['Content-Security-Policy']) # x-content-type-options disabled app = flask.Flask(__name__) Talisman(app, x_content_type_options=False) response = app.test_client().get('/', environ_overrides=HTTPS_ENVIRON) self.assertNotIn('X-Content-Type-Options', response.headers) # x-xss-protection disabled app = flask.Flask(__name__) Talisman(app, x_xss_protection=False) response = app.test_client().get('/', environ_overrides=HTTPS_ENVIRON) self.assertNotIn('X-XSS-Protection', response.headers)
def register_extensions(app): """Register Flask extensions.""" CORS(app) Talisman(app) extensions.cache.init_app(app, config={'CACHE_TYPE': 'simple'}) extensions.csrf.init_app(app) app.secret_key = extensions.SECRET_KEY
def _before_adding_routes(app, app_config): script_hashes = WSGIServer.get_csp_hashes(app, app_config) server_config = app_config.server_config # add the api_base_url to the connect_src csp header. extra_connect_src = [] api_base_url = server_config.get_api_base_url() if api_base_url: parse_api_base_url = urlparse(api_base_url) extra_connect_src = [ f"{parse_api_base_url.scheme}://{parse_api_base_url.netloc}" ] # This hash should be in sync with the script within # `client/configuration/webpack/obsoleteHTMLTemplate.html` # It is _very_ difficult to generate the correct hash manually, # consider forcing CSP to fail on the local server by intercepting the response via Requestly # this should print the failing script's hash to console. # See more here: https://github.com/chanzuckerberg/cellxgene/pull/1745 obsolete_browser_script_hash = [ "'sha256-/rmgOi/skq9MpiZxPv6lPb1PNSN+Uf4NaUHO/IjyfwM='" ] csp = { "default-src": ["'self'"], "connect-src": ["'self'"] + extra_connect_src, "script-src": ["'self'", "'unsafe-eval'"] + obsolete_browser_script_hash + script_hashes, "style-src": ["'self'", "'unsafe-inline'"], "img-src": ["'self'", "https://cellxgene.cziscience.com", "data:"], "object-src": ["'none'"], "base-uri": ["'none'"], "frame-ancestors": ["'none'"], } if not app.debug: csp["upgrade-insecure-requests"] = "" if server_config.app__csp_directives: for k, v in server_config.app__csp_directives.items(): if not isinstance(v, list): v = [v] csp[k] = csp.get(k, []) + v # Add the web_base_url to the CORS header web_base_url = server_config.get_web_base_url() if web_base_url: web_base_url_parse = urlparse(web_base_url) allowed_origin = f"{web_base_url_parse.scheme}://{web_base_url_parse.netloc}" CORS(app, supports_credentials=True, origins=allowed_origin) Talisman( app, force_https=server_config.app__force_https, frame_options="DENY", content_security_policy=csp, )
def create_app(run_as_server=True): """Create web app.""" setup_logging(run_as_server) app = Flask(__name__.split('.')[0]) configure_app(app) global talisman talisman = Talisman( app, content_security_policy={ 'default-src': ['*', '\'unsafe-inline\'', '\'unsafe-eval\'', 'data:', 'blob:'] }, force_https=app.config.get('FORCE_HTTPS', True)) setup_theme(app) setup_assets(app) setup_cache_timeouts(app) setup_ratelimits(app) setup_uploader(app) setup_error_email(app) setup_login_manager(app) setup_babel(app) setup_markdown(app) setup_db(app) setup_repositories(app) setup_cache(app) setup_strong_password(app) mail.init_app(app) sentinel.init_app(app) setup_exporter(app) setup_http_signer(app) signer.init_app(app) if app.config.get('SENTRY_DSN'): # pragma: no cover Sentry(app) if run_as_server: # pragma: no cover setup_scheduled_jobs(app) setup_blueprints(app) setup_hooks(app) setup_error_handlers(app) setup_ldap(app) setup_external_services(app) setup_importers(app) setup_jinja(app) setup_csrf_protection(app) setup_debug_toolbar(app) setup_jinja2_filters(app) setup_newsletter(app) setup_sse(app) setup_json_serializer(app) setup_cors(app) setup_profiler(app) plugin_manager.init_app(app) plugin_manager.install_plugins() import pybossa.model.event_listeners anonymizer.init_app(app) setup_task_presenter_editor(app) setup_schedulers(app) return app
def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(config_class) db.init_app(app) migrate.init_app(app, db) mail.init_app(app) login.init_app(app) moment.init_app(app) bootstrap.init_app(app) csp = { 'default-src': [ '\'self\'', '*.cloudflare.com', ], 'script-src': [ '*.cloudflare.com', '\'sha256-BnbhRZiV8CMKnm4i7fAgTMjXRwEbmlN96V4mq+Blvk4=\'' ] } Talisman(app, content_security_policy=csp) from app.errors import bp as errors_bp app.register_blueprint(errors_bp) from app.auth import bp as auth_bp app.register_blueprint(auth_bp) from app.main import bp as main_bp app.register_blueprint(main_bp) from app.api import bp as api_bp app.register_blueprint(api_bp, url_prefix='/api/v1/') if not app.debug and not app.testing: if not os.path.exists('logs'): os.mkdir('logs') file_handler = RotatingFileHandler('logs/blogapp.log', maxBytes=10240, backupCount=10) file_handler.setFormatter( logging.Formatter( '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]' )) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) app.logger.info('Blog app starting up') return app
def setup(app: Flask) -> None: config = app.config # CSP if not app.debug: csp = config.get("CONTENT_SECURITY_POLICY", DEFAULT_CSP_POLICY) Talisman(app, content_security_policy=csp) # Debug Toolbar init_debug_toolbar(app)
def configure_talisman(app): if app.config.get("TALISMAN"): from flask_talisman import Talisman talisman_kwargs = { k.replace("TALISMAN_", "").lower(): v for k, v in app.config.items() if k.startswith("TALISMAN_") } Talisman(app, **talisman_kwargs)
def create_app(): app = Flask(__name__, static_folder='www/mobile/static') app.config.from_object(config) MobileMod(app) CommandsLoader(app) Talisman(app, content_security_policy=config.get('CONTENT_SECURITY_POLICY'), content_security_policy_nonce_in=['script-src']) # This hook ensures that a connection is opened to handle any queries # generated by the request. @app.before_request def _db_connect(): if database.is_closed(): database.connect() # This hook ensures that the connection is closed when we've finished # processing the request. @app.teardown_request def _db_close(exc): if not database.is_closed(): database.close() @app.errorhandler(404) def page_not_found(e): if request.headers.get('X-Requested-With') == 'XMLHttpRequest': return jsonify({ 'message': 'Page not found', 'status_code': 404 }), 404 return render_template('404.html'), 404 @app.errorhandler(403) def forbidden(e): if request.headers.get('X-Requested-With') == 'XMLHttpRequest': return jsonify({ 'message': 'Access forbidden', 'status_code': 403 }), 403 return render_template('403.html'), 403 @app.errorhandler(423) def locked(e): if request.headers.get('X-Requested-With') == 'XMLHttpRequest': return jsonify({ 'message': 'Somebody already picked up the phone', 'status_code': 423 }), 423 return render_template('423.html'), 423 return app
def create_app(config_class=Config): # app initialization + configuration app = Flask(__name__) app.config.from_object(config_class) # extensions for app init from above mongo.init_app(app) # route imports from app.errors.routes import errors from app.main.routes import main from app.recipes.routes import recipes from app.users.routes import users app.register_blueprint(errors) app.register_blueprint(main) app.register_blueprint(recipes) app.register_blueprint(users) # whitelist sources for Flask-Talisman csp = { 'img-src': '*', 'default-src': [ '\'unsafe-inline\' \'self\'', '*.herokuapp.com', '*.cloudflare.com', '*.fontawesome.com', '*.googleapis.com', '*.gstatic.com', 'unpkg.com' ], 'style-src': [ '\'unsafe-inline\' \'self\'', '*.herokuapp.com', '*.cloudflare.com', '*.fontawesome.com', '*.googleapis.com', '*.gstatic.com', 'unpkg.com', ], 'script-src': [ '\'unsafe-inline\' \'self\'', '*.herokuapp.com', '*.jquery.com', '*.cloudflare.com', 'unpkg.com', ], 'script-src-elem': [ '\'unsafe-inline\' \'self\'', '*.herokuapp.com', '*.jquery.com', '*.cloudflare.com', 'unpkg.com', ] } # force HTTPS security header using Flask-Talisman Talisman(app, content_security_policy=csp) return app
def register_extensions(app): """Register Flask extensions.""" assets.init_app(app) hashing.init_app(app) cache.init_app(app) db.init_app(app) login_manager.init_app(app) migrate.init_app(app, db) if 'SERVER_SSL' in app.config and app.config['SERVER_SSL']: Talisman(app) return None
def __call__(self): """Read this from config actually. This config is quite unsafe but it is here to make the vuln-app work.""" if self.enabled: Talisman(self.app, content_security_policy={ 'default-src': '\'self\'', 'style-src': ['\'unsafe-inline\'', '\'self\''], 'script-src': ['\'self\'', '\'unsafe-inline\''] }) else: """Do nothing""" pass
def __init__(self, shutdown_handler, host='localhost', port=5000, ssl=False): csp = { 'default-src': ['\'self\'', 'localhost'], 'style-src': [ '\'self\'', 'use.fontawesome.com', 'fonts.googleapis.com', 'fonts.gstatic.com', 'http://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css', 'https://cdnjs.cloudflare.com/ajax/libs/jvectormap/2.0.4/jquery-jvectormap.css', 'http://cdn.jsdelivr.net/chartist.js/latest/chartist.min.css', '\'unsafe-inline\'' ], 'font-src': [ '\'self\'', 'use.fontawesome.com', 'fonts.googleapis.com', 'fonts.gstatic.com', '\'unsafe-inline\'' ], 'img-src': [ '\'self\'', 'data:', 'use.fontawesome.com', 'fonts.googleapis.com', 'fonts.gstatic.com' ], 'script-src': [ '\'self\'', '\'unsafe-inline\'', 'http://cdn.jsdelivr.net/chartist.js/latest/chartist.min.js' ], } if FROZEN: Talisman(_app, force_https=ssl, content_security_policy=csp) else: from flask_cors import CORS CORS(_app) # # otp = OTP() # otp.init_app(_app) flask_compress.Compress(_app) self._shutdown_handler = shutdown_handler self._host = host self._port = int(port) self._use_ssl = ssl self._certfile_path = APP_DIR / 'lib' / 'liquitrader.crt' self._keyfile_path = APP_DIR / 'lib' / 'liquitrader.key' self._jwt = None # Set constants for WSGIServer WSGIServer.version = 'LiquiTrader/2.0' self._wsgi_server = None
def create_app(): """ Create the WSGI app for passari-web-ui """ app = Flask("passari_web_ui") app.config.from_object("passari_web_ui.default_config") app.config.update(**get_flask_config()) app.config["SQLALCHEMY_DATABASE_URI"] = get_connection_uri() app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db.init_app(app) with app.app_context(): init_security() # Register blueprints from passari_web_ui.api.views import routes as api_routes from passari_web_ui.ui.views import routes as ui_routes api_routes.before_request(require_authentication) ui_routes.before_request(require_authentication) app.before_request(add_system_status) app.register_blueprint(api_routes, url_prefix="/api") app.register_blueprint(ui_routes, url_prefix="/web-ui") register_rq_dashboard(app) # Redirect the user to the main page of web UI by default app.add_url_rule("/", "index", lambda: redirect(url_for("ui.overview"))) # Register CLI commands app.cli.add_command(create_db) # Enable global CSRF CSRFProtect(app) # Enable HTTPS only and other security improvements Talisman( app, content_security_policy={ "default-src": "'self'", # 'unsafe-eval' required for compiling Vue templates "script-src": "'self' 'unsafe-eval'", "style-src": "'self' 'unsafe-inline'", # Needed for embedding HTML reports in "View single SIP" page "frame-src": "'self' blob:" }, content_security_policy_nonce_in=["script-src"]) return app
def create_app(test_config=None): app = Flask(__name__) app.config.update(dict( DEBUG = True, MAIL_SERVER = 'smtp.gmail.com', MAIL_PORT = 587, MAIL_USE_TLS = True, MAIL_USE_SSL = False, MAIL_USERNAME = '******', MAIL_PASSWORD = '******', MAIL_DEFAULT_SENDER='*****@*****.**' )) mail = Mail(app) csp = { 'default-src': ['\'self\'', '\'unsafe-inline\'', 'stackpath.bootstrapcdn.com', 'code.jquery.com', 'cdn.jsdelivr.net', 'cdnjs.cloudflare.com'], 'img-src': ['self', 'data:'], } talisman = Talisman(app, content_security_policy=csp) app.config.from_pyfile("config.py", silent=False) if test_config is not None: app.config.update(test_config) app.config["MONGODB_HOST"] = os.getenv("MONGODB_HOST") db.init_app(app) login_manager.init_app(app) bcrypt.init_app(app) # %%%%%%%%% REGISTERING BLUEPRINTS %%%%%%%%% from flask_app.users.routes import users from flask_app.photos.routes import photos app.register_blueprint(users) app.register_blueprint(photos) # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% app.register_error_handler(404, page_not_found) login_manager.login_view = "users.login" return app