import time import yaml from flask import Flask, Response, render_template, request from flask_talisman import Talisman from kubernetes import client, config from github import Github app = Flask(__name__, template_folder="") logging.basicConfig(level=logging.DEBUG) csp = { "default-src": "'self'", "style-src": ["'self'", "https://tools-static.wmflabs.org"], "font-src": "https://tools-static.wmflabs.org" } talisman = Talisman(app, content_security_policy=csp, force_https=False, content_security_policy_nonce_in=["style-src"]) try: app.config.update( yaml.safe_load(open("/data/project/goodbot/secrets.yaml"))) config.load_kube_config() except Exception as e: # to pass tests in non-Kubernetes context app.logger.info(e) apps_v1 = client.AppsV1Api() app.logger.info("Client loaded...") @app.route("/deploy", methods=["POST"]) def respond(): def validate_signature(): key = bytes(app.config["webhook_secret"], "utf-8")
from . import bolt11 from .core import core_app from .db import init_databases, open_db from .extensions.withdraw import withdraw_ext from .helpers import megajson from .settings import WALLET, DEFAULT_USER_WALLET_NAME, FEE_RESERVE app = Flask(__name__) Talisman( app, content_security_policy={ "default-src": [ "'self'", "'unsafe-eval'", "'unsafe-inline'", "cdnjs.cloudflare.com", "code.ionicframework.com", "code.jquery.com", "fonts.googleapis.com", "fonts.gstatic.com", "maxcdn.bootstrapcdn.com", ] }, ) # filters app.jinja_env.filters["megajson"] = megajson # blueprints app.register_blueprint(core_app) app.register_blueprint(withdraw_ext, url_prefix="/withdraw")
from functools import wraps import re from flask_talisman import Talisman from Crypto.Hash import SHA256 app = Flask(__name__) # CONFIG load_dotenv(verbose=True) JWT_SECRET = os.getenv("JWT_SECRET") REQUEST_CREDENTIALS_EXPIRE = int(os.getenv("REQUEST_CREDENTIALS_EXPIRE")) PUBLICATIONS_ACCESS = int(os.getenv("PUBLICATIONS_ACCESS")) API_URL = os.getenv("API_URL") app.config["SECRET_KEY"] = secrets.token_urlsafe(16) Talisman(app) ####### def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): if (("USERNAME" not in session) or ("SESSION_ID" not in session)): return redirect("/") return f(*args, **kwargs) return decorated @app.route("/", methods=["GET"]) def index():
def init_talisman(app): if 'SERVER_SSL' in app.config and app.config['SERVER_SSL']: Talisman(app, content_security_policy=app.config['CSP_DIRECTIVES'], frame_options_allow_from='*')
import os from flask import (Flask, render_template, redirect, url_for) from flask_talisman import Talisman, GOOGLE_CSP_POLICY from requests import post, RequestException from flask_wtf import FlaskForm from wtforms import StringField, SubmitField, validators TOKEN = os.getenv('TOKEN') CHAT_ID = os.getenv('CHAT_ID') URL = f'https://api.telegram.org/bot{TOKEN}/sendMessage' app = Flask(__name__) Talisman(app, force_https_permanent=301, content_security_policy=GOOGLE_CSP_POLICY) app.config.update( dict(SECRET_KEY=os.getenv('SECRET_KEY'), WTF_CSRF_SECRET_KEY=os.getenv('WTF_CSRF_SECRET_KEY'))) @app.route('/', methods=['GET', 'POST']) def index(): form = CallBackForm() if form.validate_on_submit(): notification( f'Новая заявка: {form.name.data}\n{form.phonenumber.data}') return redirect(url_for('index')) return render_template('index.html', form=form)
def create_app(version_path, secret_key, session_cookie_name, session_cookie_domain, session_cookie_secure, use_https, enable_asset_pipeline, lando_api_url, debug=False): """ Create an app instance. """ csp = { 'default-src': "'self'", 'font-src': "'self' https://code.cdn.mozilla.net", 'style-src': "'self' https://code.cdn.mozilla.net", 'img-src': "'self' *.cloudfront.net *.gravatar.com " "*.googleusercontent.com", 'object-src': "'none'", 'frame-ancestors': "'none'", 'manifest-src': "'none'", 'worker-src': "'none'", 'media-src': "'none'", 'frame-src': "'none'", 'base-uri': "'none'", 'report-uri': "/__cspreport__" } # yapf: disable initialize_logging() app = Flask(__name__) app.debug = debug # Set configuration app.config['VERSION_PATH'] = version_path log_config_change('VERSION_PATH', version_path) version_info = json.load(open(version_path)) logger.info('application version', extra=version_info) this_app_version = version_info['version'] initialize_sentry(app, this_app_version) app.config['LANDO_API_URL'] = lando_api_url log_config_change('LANDO_API_URL', lando_api_url) app.config['BUGZILLA_URL'] = _lookup_service_url(lando_api_url, 'bugzilla') log_config_change('BUGZILLA_URL', app.config['BUGZILLA_URL']) app.config['PHABRICATOR_URL'] = (_lookup_service_url( lando_api_url, 'phabricator')) log_config_change('PHABRICATOR_URL', app.config['PHABRICATOR_URL']) # Set remaining configuration app.config['SECRET_KEY'] = secret_key app.config['SESSION_COOKIE_NAME'] = session_cookie_name log_config_change('SESSION_COOKIE_NAME', session_cookie_name) app.config['SESSION_COOKIE_DOMAIN'] = session_cookie_domain log_config_change('SESSION_COOKIE_DOMAIN', session_cookie_domain) app.config['SESSION_COOKIE_SECURE'] = session_cookie_secure log_config_change('SESSION_COOKIE_SECURE', session_cookie_secure) app.config['SERVER_NAME'] = session_cookie_domain log_config_change('SERVER_NAME', session_cookie_domain) app.config['USE_HTTPS'] = use_https log_config_change('USE_HTTPS', use_https) app.config['PREFERRED_URL_SCHEME'] = 'https' if use_https else 'http' Talisman(app, content_security_policy=csp, force_https=use_https) # Authentication global oidc authentication = auth.OpenIDConnect(auth.OIDCConfig()) oidc = authentication.auth(app) # Register routes via Flask Blueprints from landoui.pages import pages from landoui.revisions import revisions from landoui.dockerflow import dockerflow app.register_blueprint(pages) app.register_blueprint(revisions) app.register_blueprint(dockerflow) # Register template helpers from landoui.template_helpers import template_helpers app.register_blueprint(template_helpers) # Register error pages errorhandlers.register_error_handlers(app) # Setup Flask Assets assets = Environment(app) if enable_asset_pipeline: loader = YAMLLoader( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'assets_src/assets.yml')) assets.register(loader.load_bundles()) return app
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 secure HTTP headers if app.config['APP_ENABLE_SECURE_HEADERS']: self.talisman = Talisman( app, **app.config.get('APP_DEFAULT_SECURE_HEADERS', {})) # Enable Rate limiter # Flask limiter needs to be initialised after talisman, since if the # talisman preprocessor doesn't run you will get an error on it's # afterprocessor. self.limiter = Limiter(app, key_func=obj_or_import_string( app.config.get('RATELIMIT_KEY_FUNC'), default=useragent_and_ip_limit_key)) # Enable PING view if app.config['APP_HEALTH_BLUEPRINT_ENABLED']: blueprint = Blueprint('invenio_app_ping', __name__) limiter = self.limiter @blueprint.route('/ping') @limiter.exempt def ping(): """Load balancer ping view.""" return 'OK' ping.talisman_view_options = {'force_https': False} app.register_blueprint(blueprint) requestid_header = app.config.get('APP_REQUESTID_HEADER') if requestid_header: @app.before_request def set_request_id(): """Extracts a request id from an HTTP header.""" request_id = request.headers.get(requestid_header) if request_id: # Capped at 200 to protect against malicious clients # sending very large headers. g.request_id = request_id[:200] # If installed register the Flask-DebugToolbar extension try: from flask_debugtoolbar import DebugToolbarExtension app.extensions['flask-debugtoolbar'] = DebugToolbarExtension(app) except ImportError: app.logger.debug('Flask-DebugToolbar extension not installed.') # Force host header check (by evaluating request.host) in order to make # Werkzeugs trusted host feature work properly. if app.config['APP_ALLOWED_HOSTS']: @app.before_request def before_request(): request.host # Add theme template loader if app.config.get('APP_THEME'): app.jinja_env.loader = ThemeJinjaLoader(app, app.jinja_env.loader) # Register self app.extensions['invenio-app'] = self
app.config.update( SESSION_COOKIE_SECURE=True, SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE='Lax', ) db = SQLAlchemy(app) db.init_app(app) fa = FontAwesome(app) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint) from .admin import admin app.register_blueprint(admin.admin) from application.rapport.rapport import rapportBP as rapport_blueprint app.register_blueprint(rapport_blueprint) csrf = CSRFProtect(app) csrf.init_app(app) talisman = Talisman(app) talisman.content_security_policy_report_only = True login_manager = LoginManager() login_manager.login_view = 'auth.login' login_manager.init_app(app) from .models import User @login_manager.user_loader def load_user(id): return User.query.filter(User.id == int(id))
# if the configuration file is specified via an environment variable application.config.from_pyfile(configuration, silent=False) else: try: application.config.from_pyfile("development.py", silent=False) except Exception: application.config.from_pyfile("sqlite.py", silent=False) set_logging(application.config["LOG_PATH"]) db = SQLAlchemy(application) migrate = Migrate(application, db) talisman = Talisman( application, content_security_policy=application.config["CONTENT_SECURITY_POLICY"]) babel = Babel(application) @babel.localeselector def get_locale(): # if a user is logged in, use the locale from the user settings # user = getattr(g, 'user', None) # if user is not None: # return user.locale # otherwise try to guess the language from the user accept # header the browser transmits. We support de/fr/en in this # example. The best match wins. return request.accept_languages.best_match(
import sys import traceback import models_elastic as nweb from nmap_helper import * # get_ip etc from datetime import datetime app = Flask(__name__, static_url_path='/static') if os.environ.get("DEBUG") == "True": print("[-] DEBUG ENABLED, DISABLING TALISMAN") else: print("[+] ENABLING TALISMAN") Talisman(app, content_security_policy=os.environ.get("CSP_DIRECTIVES", DEFAULT_CSP_POLICY)) app.jinja_env.add_extension('jinja2.ext.do') # Setup the Flask-JWT-Extended extension # log2(26^22) ~= 100 (pull at least 100 bits of entropy) app.config['JWT_SECRET_KEY'] = os.environ.get( "JWT_SECRET_KEY", ''.join(random.choice(string.ascii_lowercase) for i in range(22))) #app.config['JWT_SECRET_KEY'] = '12345' app.config['JWT_TOKEN_LOCATION'] = ['cookies'] if app.debug == False: app.config['JWT_COOKIE_SECURE'] = True #app.config['JWT_ACCESS_COOKIE_PATH'] = '/api/'
csp = {"style-src": ["'self'", "https://cdnjs.cloudflare.com", "https://cdn.datatables.net", "https://unpkg.com", "https://fonts.googleapis.com", "'unsafe-inline'"], "script-src": ["'self'", "https://cdnjs.cloudflare.com", "https://unpkg.com", "'unsafe-inline'"], "font-src": ["'self'", "data:", "https://cdnjs.cloudflare.com", "https://fonts.gstatic.com"]} Talisman(app, content_security_policy=csp) cache = Cache(config={'CACHE_TYPE': 'simple', 'CACHE_DEFAULT_TIMEOUT': 1800}) cache.init_app(app) Bootstrap(app) xr.set_options(display_style="html") catalog_dir = "https://raw.githubusercontent.com/pangeo-data/pangeo-datastore/master/intake-catalogs/" master = intake.open_catalog(catalog_dir + "master.yaml") @app.route('/') @cache.cached()
from website.app import create_app from flask_talisman import Talisman from os import environ app = create_app({ 'SECRET_KEY': 'secret', 'OAUTH2_REFRESH_TOKEN_GENERATOR': True, 'SQLALCHEMY_TRACK_MODIFICATIONS': False, 'SQLALCHEMY_DATABASE_URI': 'sqlite:///db.sqlite', }) Talisman(app, content_security_policy={ 'default-src': [ '\'self\'', '\'unsafe-inline\'', 'stackpath.bootstrapcdn.com', 'code.jquery.com', 'cdn.jsdelivr.net', 'fonts.googleapis.com', 'fonts.gstatic.com' ] }) # Flask extension for http security headers # for https use flask run --cert=cert.pem --key=key.pem # or uncomment below if __name__ == "__main__": app.run(host='avuesse', ssl_context=(f"{environ['APP_BASE_DIR']}/cert.pem", f"{environ['APP_BASE_DIR']}/key.pem"), port=5555)
"CACHE_REDIS_URL": os.environ.get("REDIS_URL"), "CACHE_DEFAULT_TIMEOUT": 60 * 60 * 6, # 6 hours } else: CACHE_CONFIG = {"CACHE_TYPE": "null"} # optimization & security cache = Cache(app, config=CACHE_CONFIG) Compress(app) Talisman( app, content_security_policy={ "default-src": [ "'self'", "'unsafe-eval'", "'unsafe-inline'", "fonts.googleapis.com", "fonts.gstatic.com", "localhost:8000" if app.config["DEBUG"] else "www.hipeac.net", ] }, ) # assets assets = Environment(app) assets.url = app.static_url_path assets.register( "base_css", Bundle("scss/base.scss", filters="pyscss", output="css/base.css")) # jinja
return str(o) return JSONEncoder.default(self, o) # This is only in effect when you call jsonify() app.json_encoder = CustomJSONEncoder #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ print("ENV_TYPE:{},DEBUG={}".format(ENV_TYPE, DEBUG)) if ENV_TYPE == "Production": app.debug = False crash_mailer(app, ENV_TYPE, HOSTNAME) log_handler(app) talisman = Talisman(app) print("Registering Crash Mailer") elif 'DEV' in ENV_TYPE: # Running crash reporting in dev when DEBUG is off, but not on individual machines. if DEBUG == False: print("Registering Crash Mailer") crash_mailer(app, ENV_TYPE, HOSTNAME) log_handler(app) CORS(app, resources={r"*": {"origins": "*"}}) else: if DEBUG == False: app.debug = False else: app.debug = True
from flask_talisman import Talisman from time import sleep import logging import os app = Flask(__name__) port = int(os.environ.get("PORT", 5000)) app.config['SECRET_KEY'] = str(os.environ.get("SECRET_KEY", "notanenviormentsecretkey")) csp = { 'default-src': '\'self\'', 'img-src': '*', 'media-src': '*', 'script-src': '*', } talisman = Talisman(app, force_https=True, content_security_policy=csp) # app.add_url_rule('/favicon.ico', redirect_to=url_for('static', filename='favicon.ico')) # logging.basicConfig(level=logging.DEBUG) @app.route('/', methods=['GET', 'POST']) def countdown(): cnt = 3 text = text_heart(3) if request.method == 'POST': print('GOT A POST REQUEST') print(request.get_json()) # return redirect(url_for('display')) return render_template('display.html', title="Display Page", style="display.css",
return flask.Flask.select_jinja_autoescape(self, filename) # flask.Flask.select_jinja_autoescape = select_jinja_autoescape app = flask.Flask(__name__) # config: one default (public), the other private app.config.from_object('settings') os.environ["FLASK_SETTINGS"] = cube.CONFIG["flask_config"] app.config.from_envvar("FLASK_SETTINGS") # Security csp = { "default-src": "'self'", } Talisman(app, content_security_policy=None) # explicit CSRF protection for all forms CSRFProtect(app) # generate sitemap # ext = Sitemap(app=app) flask_uploads.configure_uploads(app, (forms.times, forms.photos)) # Strange glitch with TJ servers - if you look at the source code this *should* happen already... app.register_blueprint(flask_uploads.uploads_mod) def alert(msg: str, category: str = "success", loc: str = "index") -> Response: """ Redirects the user with an alert. """ flask.flash(msg, category) dest = {"self": flask.request.path, "meta": flask.request.full_path}
# Cache static resources for 10800 secs (3 hrs) with SEND_FILE_MAX_AGE_DEFAULT. # Flask default if not set is 12 hours but we want to match app.yaml # which is used by Google App Engine as it serves static files directly app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 10800 # Convert URL routes with regex app.url_map.converters['regex'] = RegexConverter # Make these functions available in templates. app.jinja_env.globals['get_view_args'] = get_view_args app.jinja_env.globals['chapter_lang_exists'] = chapter_lang_exists app.jinja_env.globals['featured_chapters_exists'] = featured_chapters_exists app.jinja_env.globals['HTTP_STATUS_CODES'] = HTTP_STATUS_CODES app.jinja_env.globals['get_ebook_methodology'] = get_ebook_methodology app.jinja_env.globals['add_footnote_links'] = add_footnote_links app.jinja_env.globals['year_live'] = year_live app.jinja_env.globals['get_versioned_filename'] = get_versioned_filename app.jinja_env.filters['accentless_sort'] = accentless_sort talisman = Talisman( app, content_security_policy=csp.csp, content_security_policy_nonce_in=['script-src', 'style-src'], feature_policy=feature_policy.feature_policy) # Circular Import but this is fine because routes and errors modules are not used in here and # this way we make app available for decorators in both modules # For more details, check https://flask.palletsprojects.com/en/1.1.x/patterns/packages/ import server.routes import server.errors
return GET_FEATURE_FLAGS_FUNC(deepcopy(_feature_flags)) return _feature_flags def is_feature_enabled(feature): """Utility function for checking whether a feature is turned on""" return get_feature_flags().get(feature) # Flask-Compress if conf.get("ENABLE_FLASK_COMPRESS"): Compress(app) if conf["TALISMAN_ENABLED"]: talisman_config = conf.get("TALISMAN_CONFIG") Talisman(app, **talisman_config) # Hook that provides administrators a handle on the Flask APP # after initialization flask_app_mutator = conf.get("FLASK_APP_MUTATOR") if flask_app_mutator: flask_app_mutator(app) # from flask import Flask, json, make_response # 添加每次请求后的操作函数,必须要返回res @app.after_request def myapp_after_request(resp): try: if g.user and g.user.username: resp.set_cookie('myapp_username', g.user.username)
valid_extensions = [ext for ext in ExtensionManager(disabled=disabled_extensions).extensions if ext.is_valid] # optimization & security # ----------------------- Compress(app) Talisman( app, force_https=FORCE_HTTPS, content_security_policy={ "default-src": [ "'self'", "'unsafe-eval'", "'unsafe-inline'", "blob:", "api.opennode.co", "fonts.googleapis.com", "fonts.gstatic.com", "github.com", "avatars2.githubusercontent.com", ] }, ) # blueprints / extensions # ----------------------- app.register_blueprint(core_app)
def create_app(test_config=None): app = Flask(__name__) print("Getting config values from config.py") app.config.from_pyfile("config.py", silent=False) if test_config is not None: app.config.update(test_config) print("Getting config values from environment") secret_key = os.getenv("SECRET_KEY") if secret_key and not app.config["SECRET_KEY"]: app.config["SECRET_KEY"] = secret_key.encode('utf_8') drive_api_key = os.getenv("DRIVE_API_KEY") if drive_api_key and not app.config["DRIVE_API_KEY"]: app.config["DRIVE_API_KEY"] = drive_api_key root_id = os.getenv("ROOT_ID") if root_id and not app.config["ROOT_ID"]: app.config["ROOT_ID"] = root_id mongodb_host = os.getenv("MONGODB_HOST") if mongodb_host and not app.config["MONGODB_HOST"]: app.config["MONGODB_HOST"] = mongodb_host app.config["MONGO_URI"] = mongodb_host site_url = os.getenv("SITE_URL") if site_url and not app.config["SITE_URL"]: app.config["SITE_URL"] = site_url print("Initializing login manager") login_manager.init_app(app) print("Initializing bcrypt") bcrypt.init_app(app) print("Initializing MongoDB") db.init_app(app) print("Initializing root user") if initialize_root_user() == 1: return None print("Initializing PyMongo") pymongo.init_app(app) csp = { 'default-src': [ '\'self\'', 'stackpath.bootstrapcdn.com', 'code.jquery.com', 'cdn.jsdelivr.net', 'cdnjs.cloudflare.com', 'drive.google.com', '*.googleusercontent.com', 'ajax.googleapis.com', 'www.google-analytics.com', '\'unsafe-inline\'' ], 'img-src': ['\'self\' data: *'] } print("Initializing Talisman") Talisman(app, content_security_policy=csp) print("Registering blueprints") app.register_blueprint(results) app.register_blueprint(users) app.register_blueprint(api) app.register_error_handler(404, page_not_found) login_manager.login_view = "users.login" print('\033[92mStartup successful\033[0m') return app
"style-src": [ "'self'", "https://cdn.ons.gov.uk", "'unsafe-inline'", "https://tagmanager.google.com", "https://fonts.googleapis.com", ], } app = create_app_object() talisman = Talisman( app, content_security_policy=CSP_POLICY, content_security_policy_nonce_in=["script-src"], force_https=app.config["SECURE_APP"], strict_transport_security=True, strict_transport_security_max_age=31536000, frame_options="DENY", ) redis = redis.Redis(host=app.config["REDIS_HOST"], port=app.config["REDIS_PORT"], db=app.config["REDIS_DB"]) app.jinja_env.add_extension("jinja2.ext.do") app.register_blueprint(filter_blueprint) @app.context_processor def inject_availability_message():
'\'self\'', '*.google.com', '*.google-analytics.com', '*.gstatic.com', 'unpkg.com' ], 'script-src': [ '\'self\'', '\'unsafe-inline\'', '*.googletagmanager.com', '*.google-analytics.com', '*.google.com', '*.gstatic.com', ] } _t = Talisman(app, content_security_policy=csp) # HTTPS forced # Configuration - replace with your own keys app.config['USPS_UID'] = "" app.config['RECAPTCHA_SITE_KEY'] = "" app.config['RECAPTCHA_SECRET_KEY'] = "" recaptcha = ReCaptcha(app=app) @app.route("/api/format-address", methods=['POST']) def formatAddress(): """Internal API endpoint to return a formatted address. Proxies through errors.""" if recaptcha.verify() or app.config.get('testing'): if 'addr2' not in request.form: result = {'error': "You need at least one address line."}
from urlparse import urlparse from csp import csp import reports as report_util import faq as faq_util from legacy import Legacy from flask import Flask, request, make_response, jsonify, render_template, redirect, abort, url_for as flask_url_for from flaskext.markdown import Markdown from flask_talisman import Talisman app = Flask(__name__) Markdown(app) Talisman(app, content_security_policy=csp, content_security_policy_nonce_in=['script-src']) legacy_util = Legacy(faq_util) # Overwrite the built-in method. def url_for(endpoint, **kwargs): # Persist the lens parameter across navigations. lens = request.args.get('lens') if report_util.is_valid_lens(lens): kwargs['lens'] = lens # Pass through to the built-in method. return flask_url_for(endpoint, **kwargs) app.jinja_env.globals['url_for'] = url_for
from models.alert import Rules from models.tile import S3Transfer logging.basicConfig(level=logging.INFO) with open('logging.yml', 'r') as log_config: config_yml = log_config.read() config_dict = yaml.load(config_yml) logging.config.dictConfig(config_dict) logger = logging.getLogger('sso-dashboard') app = Flask(__name__) talisman = Talisman( app, content_security_policy=DASHBOARD_CSP, force_https=False ) app.config.from_object(config.Config(app).settings) app_list = S3Transfer(config.Config(app).settings) app_list.sync_config() assets = Environment(app) js = Bundle('js/base.js', filters='jsmin', output='js/gen/packed.js') assets.register('js_all', js) sass = Bundle('css/base.scss', filters='scss') css = Bundle(sass, filters='cssmin', output='css/gen/all.css') assets.register('css_all', css) # Hack to support serving .svg
from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_socketio import SocketIO from flask_talisman import Talisman from config import Config from dark_chess_api.endpoint_handler import Endpointer ############## # Services # ############## db = SQLAlchemy() # database migrate = Migrate() # database migrations socketio = SocketIO() # web-sockets talisman = Talisman() # security-defaults mocker = Faker() # mocking service endpointer = Endpointer() # endpoint validation and documentation def create_app(config=Config): app = Flask(__name__) app.config.from_object(config) from dark_chess_api.modules.errors.handlers import error_response endpointer.init_app(app, error_handler=error_response) CORS(app, resources={'/socket.io/': {'origins': app.config['FRONTEND_ROOT']}}) db.init_app(app) migrate.init_app(app, db) socketio.init_app(app, cors_allowed_origins=app.config['FRONTEND_ROOT'])
def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) csp = { 'default-src': ['*', "'unsafe-inline'", "'unsafe-eval'"] # 'script-src': ["'unsafe-inline'", "'nonce-allow'"], # 'style-src': ["'unsafe-inline'", "'nonce-allow'"], # 'connect-src': ["'unsafe-inline'", "'nonce-allow'"], # 'img-src': ["*"], # 'default-src': [ # '\'self\'', # "'nonce-allow'", # "d3js.org" # ] } Talisman(app, content_security_policy=csp) CORS(app) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('app_config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) queue_pool = [ Queue(channel, connection=conn) for channel in ['high', 'default', 'low'] ] # queue_pool = [Queue(channel, connection=conn) for channel in ['high']] popularity_thresholds_500k_samples = [ 2500, 2000, 1500, 1000, 700, 400, 250, 150 ] @app.before_request def redirect_to_new_domain(): urlparts = urlparse(request.url) if urlparts.netloc == FROM_DOMAIN and urlparts.path == "/": urlparts_list = list(urlparts) urlparts_list[1] = TO_DOMAIN return redirect(urlunparse(urlparts_list), code=301) @app.route('/') def homepage(): return render_template('index.html') @app.route('/get_recs', methods=['GET', 'POST']) def get_recs(): username = request.args.get('username').lower().strip() training_data_size = int(request.args.get('training_data_size')) popularity_filter = int(request.args.get("popularity_filter")) data_opt_in = (request.args.get("data_opt_in") == "true") if popularity_filter >= 0: popularity_threshold = popularity_thresholds_500k_samples[ popularity_filter] else: popularity_threshold = None num_items = 500 ordered_queues = sorted( queue_pool, key=lambda queue: DeferredJobRegistry(queue=queue).count) print([(q, DeferredJobRegistry(queue=q).count) for q in ordered_queues]) q = ordered_queues[0] job_get_user_data = q.enqueue( get_client_user_data, args=( username, data_opt_in, ), description= f"Scraping user data for {request.args.get('username')} (sample: {training_data_size}, popularity_filter: {popularity_threshold}, data_opt_in: {data_opt_in})", result_ttl=45, ttl=300) # job_create_df = q.enqueue(create_training_data, args=(training_data_size, exclude_popular,), depends_on=job_get_user_data, description=f"Creating training dataframe for {request.args.get('username')}", result_ttl=5) job_build_model = q.enqueue( build_client_model, args=( username, training_data_size, popularity_threshold, num_items, ), depends_on=job_get_user_data, description= f"Building model for {request.args.get('username')} (sample: {training_data_size}, popularity_filter: {popularity_threshold})", result_ttl=30, ttl=300) # job_run_model = q.enqueue(run_client_model, args=(username,num_items,), depends_on=job_build_model, description=f"Running model for {request.args.get('username')}", result_ttl=5) return jsonify({ "redis_get_user_data_job_id": job_get_user_data.get_id(), # "redis_create_df_job_id": job_create_df.get_id(), "redis_build_model_job_id": job_build_model.get_id() # "redis_run_model_job_id": job_run_model.get_id() }) @app.route("/results", methods=['GET']) def get_results(): job_ids = request.args.to_dict() job_statuses = {} for key, job_id in job_ids.items(): try: job_statuses[key.replace('_id', '_status')] = Job.fetch( job_id, connection=conn).get_status() except NoSuchJobError: job_statuses[key.replace('_id', '_status')] = "finished" end_job = Job.fetch(job_ids['redis_build_model_job_id'], connection=conn) execution_data = {"build_model_stage": end_job.meta.get('stage')} try: user_job = Job.fetch(job_ids['redis_get_user_data_job_id'], connection=conn) execution_data |= { "num_user_ratings": user_job.meta.get('num_user_ratings'), "user_status": user_job.meta.get('user_status') } except NoSuchJobError: pass if end_job.is_finished: return jsonify({ "statuses": job_statuses, "execution_data": execution_data, "result": end_job.result }), 200 else: return jsonify({ "statuses": job_statuses, "execution_data": execution_data }), 202 return app
def create_app(): """ Flask application factory """ # Create Flask app load app.config app = Flask(__name__) app.config.from_object(__name__ + '.ConfigClass') # Security Headers csp = { 'default-src': '\'self\'', 'style-src': '\'unsafe-inline\' \'self\' bootstrapcdn.com *.bootstrapcdn.com cloudflare.com *.cloudflare.com googleapis.com *.googleapis.com jsdelivr.net *.jsdelivr.net', 'script-src': '\'unsafe-eval\' \'self\' bootstrapcdn.com *.bootstrapcdn.com cloudflare.com *.cloudflare.com googleapis.com *.googleapis.com jquery.com *.jquery.com jsdelivr.net *.jsdelivr.net', 'font-src': 'cloudflare.com *.cloudflare.com gstatic.com *.gstatic.com bootstrapcdn.com *.bootstrapcdn.com', 'img-src': '\'self\' data:' } feature_policy = { 'geolocation': '\'none\'', 'accelerometer': '\'none\'', 'camera': '\'none\'', 'geolocation': '\'none\'', 'gyroscope': '\'none\'', 'magnetometer': '\'none\'', 'microphone': '\'none\'', 'payment': '\'none\'', 'usb': '\'none\'' } Talisman(app, content_security_policy=csp, feature_policy=feature_policy, content_security_policy_nonce_in=['script-src']) # Initialize Flask-SQLAlchemy db = SQLAlchemy(app) # Define the User data-model. # NB: Make sure to add flask_user UserMixin !!! class User(db.Model, UserMixin): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) active = db.Column('is_active', db.Boolean(), nullable=False, server_default='1') # User authentication information. The collation='NOCASE' is required # to search case insensitively when USER_IFIND_MODE is 'nocase_collation'. username = db.Column(db.String(100, collation='NOCASE'), nullable=False, unique=True) password = db.Column(db.String(255), nullable=False, server_default='') email_confirmed_at = db.Column(db.DateTime()) # User information first_name = db.Column(db.String(100, collation='NOCASE'), nullable=False, server_default='') last_name = db.Column(db.String(100, collation='NOCASE'), nullable=False, server_default='') # Create all database tables db.create_all() # Setup Flask-User and specify the User data-model user_manager = UserManager(app, db, User) # The Home page is accessible to anyone @app.route('/') def home_page(): return redirect(url_for('hub')) # The Members page is only accessible to authenticated users via the @login_required decorator @app.route('/member_page') @login_required # User must be authenticated def member_page(): return redirect(url_for('dashboard')) @app.route("/reportcenter") @login_required def reportcenter(): return redirect(url_for('dashboard')) @app.route("/reportcenter/dashboard") @login_required def dashboard(): conn = sqlite3.connect('hubapp.sqlite') c = conn.cursor() c.execute( 'SELECT count(*) AS \"status\" FROM webreport WHERE status = \"open\"' ) webreport = c.fetchone() web = webreport[0] c.execute( 'SELECT count(*) AS \"webstatus\" FROM smsreport WHERE status = \"open\"' ) smsreport = c.fetchone() sms = smsreport[0] c.execute( 'SELECT count(*) AS \"phonestatus\" FROM phonereport WHERE status = \"open\"' ) phonereport = c.fetchone() phone = phonereport[0] c.execute( 'select count(*) AS \"webstatusclosed\" FROM webreport WHERE status = \"close\"' ) closedweb = c.fetchone() cweb = closedweb[0] c.execute( 'select count(*) AS \"smsstatusclosed\" FROM smsreport WHERE status = \"close\"' ) closedsms = c.fetchone() csms = closedsms[0] c.execute( 'select count(*) AS \"phonestatusclosed\" FROM phonereport WHERE status = \"close\"' ) closedphone = c.fetchone() cphone = closedsms[0] closed = cweb + csms + cphone c.execute( 'select count(*) AS \"webstatusassigned\" FROM webreport WHERE status = \"assigned\"' ) assignedweb = c.fetchone() aweb = assignedweb[0] c.execute( 'select count(*) AS \"smsstatusassigned\" FROM smsreport WHERE status = \"assigned\"' ) assignedsms = c.fetchone() asms = assignedsms[0] c.execute( 'select count(*) AS \"phonestatusassigned\" FROM phonereport WHERE status = \"assigned\"' ) assignedphone = c.fetchone() aphone = assignedphone[0] assigned = aweb + asms + aphone conn.close() return render_template('dashboard.html', web=web, sms=sms, phone=phone, closed=closed, assigned=assigned) @app.route("/reportcenter/full") @login_required def fullreport(): conn = sqlite3.connect('hubapp.sqlite') c = conn.cursor() c.execute("SELECT * FROM webreport") items = c.fetchall() c.execute("SELECT * FROM smsreport") smsitems = c.fetchall() c.execute("SELECT * FROM phonereport") phoneitems = c.fetchall() return render_template('fullreport.html', items=items, smsitems=smsitems, phoneitems=phoneitems) @app.route("/reportcenter/open") @login_required def openreport(): conn = sqlite3.connect('hubapp.sqlite') c = conn.cursor() c.execute( 'SELECT ID, telephone number, category, message, status FROM webreport WHERE status = \"open\"' ) web = c.fetchall() c.execute( 'SELECT ID, telephone number, category, message, status FROM smsreport WHERE status = \"open\"' ) sms = c.fetchall() c.execute( 'SELECT ID, telephone number, category, message, status FROM phonereport WHERE status = \"open\"' ) phone = c.fetchall() conn.close() return render_template('openreport.html', sms=sms, web=web, phone=phone) @app.route("/reportcenter/assigned") @login_required def assignedreport(): conn = sqlite3.connect('hubapp.sqlite') c = conn.cursor() c.execute( 'SELECT ID, telephone number, category, message, status FROM webreport WHERE status = \"assigned\"' ) web = c.fetchall() c.execute( 'SELECT ID, telephone number, category, message, status FROM smsreport WHERE status = \"assigned\"' ) sms = c.fetchall() c.execute( 'SELECT ID, telephone number, category, message, status FROM phonereport WHERE status = \"assigned\"' ) phone = c.fetchall() conn.close() return render_template('assignedreport.html', sms=sms, web=web, phone=phone) @app.route("/reportcenter/web/close/<int:id>") @login_required def closereport(id): conn = sqlite3.connect('hubapp.sqlite') c = conn.cursor() try: c.execute("UPDATE webreport SET status = ? WHERE ID = ?", ('close', id)) conn.commit() conn.close() return redirect(url_for('openreport')) except: return 'This case has already been closed.' @app.route("/reportcenter/web/assign/<int:id>") @login_required def assignreport(id): conn = sqlite3.connect('hubapp.sqlite') c = conn.cursor() try: print('hi') c.execute("UPDATE webreport SET status = ? WHERE ID = ?", ('assigned', id)) conn.commit() conn.close() return redirect(url_for('assignedreport')) except: return 'This case has already been assigned.' @app.route("/reportcenter/sms/close/<int:id>") @login_required def smsclosereport(id): conn = sqlite3.connect('hubapp.sqlite') c = conn.cursor() try: c.execute("UPDATE smsreport SET status = ? WHERE ID = ?", ('close', id)) conn.commit() conn.close() return redirect(url_for('openreport')) except: return 'This case has already been closed.' @app.route("/reportcenter/sms/assign/<int:id>") @login_required def smsassignreport(id): conn = sqlite3.connect('hubapp.sqlite') c = conn.cursor() try: c.execute("UPDATE smsreport SET status = ? WHERE ID = ?", ('assigned', id)) conn.commit() conn.close() return redirect(url_for('assignedreport')) except: return 'This case has already been assigned.' @app.route("/reportcenter/phone/close/<int:id>") @login_required def phoneclosereport(id): conn = sqlite3.connect('hubapp.sqlite') c = conn.cursor() try: c.execute("UPDATE phonereport SET status = ? WHERE ID = ?", ('close', id)) conn.commit() conn.close() return redirect(url_for('openreport')) except: return 'This case has already been closed.' @app.route("/reportcenter/phone/assign/<int:id>") @login_required def phoneassignreport(id): conn = sqlite3.connect('hubapp.sqlite') c = conn.cursor() try: c.execute("UPDATE phonereport SET status = ? WHERE ID = ?", ('assigned', id)) conn.commit() conn.close() return redirect(url_for('assignedreport')) except: return 'This case has already been assigned.' @app.route("/gdpr") def gdpr(): return render_template('gdpr.html') @app.route("/hub", methods=['GET']) def hub(): return render_template('default.html') @app.route("/hub/food", methods=['GET', 'POST']) def food(): form = MyForm() if form.validate_on_submit(): conn = sqlite3.connect('hubapp.sqlite') c = conn.cursor() number = form.telephonenumber.data food = form.food.data c.execute("insert into webreport values (?, ?, ?, ?, ?)", (None, number, 'food', food, 'open')) conn.commit() conn.close() return redirect(url_for('success')) return render_template('food.html', form=form) @app.route("/hub/medicine", methods=['GET', 'POST']) def medication(): form = MedForm() if form.validate_on_submit(): conn = sqlite3.connect('hubapp.sqlite') c = conn.cursor() number = form.telephonenumber.data medication = form.medication.data c.execute("insert into webreport values (?, ?, ?, ?, ?)", (None, number, 'medication', medication, 'open')) conn.commit() conn.close() return redirect(url_for('success')) return render_template('medicine.html', form=form) @app.route("/hub/emotionalsupport", methods=['GET', 'POST']) def emotionalsupport(): form = EmotionalForm() if form.validate_on_submit(): conn = sqlite3.connect('hubapp.sqlite') c = conn.cursor() number = form.telephonenumber.data food = form.emotional.data c.execute("insert into webreport values (?, ?, ?, ?, ?)", (None, number, 'Emotional Support', food, 'open')) conn.commit() conn.close() return redirect(url_for('success')) return render_template('emotionalsupport.html', form=form) @app.route("/hub/success") def success(): return render_template('success.html') @app.route("/sms", methods=['POST']) def sms(): conn = sqlite3.connect('hubapp.sqlite') c = conn.cursor() number = request.form['From'] message_body = request.form['Body'].lower() resp = MessagingResponse() if message_body == 'hi': response_message = fallback_resp if 'food shopping' in message_body: response_message = 'Great! What food do you require? Say I need food followed by the items. For example \'I need 1 tinned beans\'' elif 'i need' in message_body: helper_resp = message_body.replace('i need ', '') helper_message = 'a new food request has come in from the following number: ' + number + ' for the following items: ' + helper_resp message = client.messages.create(to=responder_number, from_=twilio_number, body=helper_message) c.execute("insert into smsreport values (?, ?, ?, ?, ?)", (None, responder_number, 'food', helper_resp, 'open')) response_message = default_resp elif 'medication' in message_body: response_message = 'Great! Where do we need to pick your medications up from and is the perscription paid/free? Say for example \'pick up from spires pharmacy free prescription in the name of John Doe\'' elif 'pick up' in message_body: helper_resp = message_body.replace('pick up from ', '') helper_message = 'a new medication request has come in from the following number: ' + number + ' for the following: ' + helper_resp message = client.messages.create(to=responder_number, from_=twilio_number, body=helper_message) response_message = default_resp c.execute( "insert into smsreport values (?, ?, ?, ?, ?)", (None, responder_number, 'edication', helper_resp, 'open')) elif 'emotional support call' in message_body: helper_message = 'a new emotional support phone call request has come in from the following number: ' + number message = client.messages.create(to=responder_number, from_=twilio_number, body=helper_message) response_message = default_resp c.execute("insert into smsreport values (?, ?, ?, ?, ?)", (None, responder_number, 'emotional support', helper_resp, 'open')) else: response_message = fallback_resp resp.message(response_message) conn.commit() conn.close() return str(resp) @app.route("/voice", methods=['GET', 'POST']) def voiceresponse(): response = VoiceResponse() gather = Gather(input='speech', action='/voice/selection', language=locale) gather.say( 'Welcome to the Emergency Response Hub, Please say out loud one of the following three options. food. medication. and finally. emotional support. if you need your prescriptions picked up say medication. If you need food say food. if you need an emotional support chat say emotional support.', voice='alice', language=locale) response.append(gather) return str(response) @app.route("/voice/selection", methods=['GET', 'POST']) def selection(): speech = request.values.get('SpeechResult') caller = request.values.get('Caller') response = VoiceResponse() if speech == 'food': gather = Gather(input='speech', action='/voice/food', language=locale) gather.say( "Please say what food you require. For example baked beans.", voice='alice', language=locale) response.append(gather) elif speech == 'medication': gather = Gather(input='speech', action='/voice/medication', language=locale) gather.say("Please say the medication you require.", voice='alice', language=locale) response.append(gather) elif speech == 'emotional support': if caller != None: conn = sqlite3.connect('hubapp.sqlite') c = conn.cursor() response.say( 'You said you need emotional support. One of our volunteers will be in touch soon. In the meantime if you want to talk to someone immediately please contact Samaritans at 1. 1. 6. 1. 2. 3. The Lines are open 24 hours a day 7 days a week.', voice='alice', language=locale) response.say('Thank you for calling. Goodbye.', voice='alice', language=locale) speech = "requires emotional support callback." c.execute("insert into phonereport values (?, ?, ?, ?, ?)", (None, caller, 'emotional support', speech, 'open')) conn.commit() conn.close() response.hangup() else: response.say( 'Unfortauntely your caller ID has been witheald. We are unable to process your emotional support request unless we are able to get your caller ID. However you can call Samaritans for free at 1. 1. 6. 1. 2. 3.' ) else: response.say( 'I\'m sorry, I was unable to identify what you said. Please call back or alternatively text this number your request. Goodbye!', voice='alice', language=locale) response.hangup() return str(response) @app.route("/voice/medication", methods=['GET', 'POST']) def phonemedication(): speech = request.values.get('SpeechResult') caller = request.values.get('Caller') response = VoiceResponse() if caller != None: conn = sqlite3.connect('hubapp.sqlite') c = conn.cursor() c.execute("insert into phonereport values (?, ?, ?, ?, ?)", (None, caller, 'medication', speech, 'open')) response.say( 'I have notified the team that you require the following medication: ' + speech, voice='alice', language=locale) response.say( 'They will be in contact soon. Thank you for calling. Goodbye!', voice='alice', language=locale) conn.commit() conn.close() else: response.say( 'Unfortunately I am unable to process your call as you are witholding your caller id. You can either disable your caller ID or use our online service. Thank You, Goodbye.' ) return str(response) @app.route("/voice/food", methods=['GET', 'POST']) def phonefood(): speech = request.values.get('SpeechResult') caller = request.values.get('Caller') response = VoiceResponse() if caller != None: conn = sqlite3.connect('hubapp.sqlite') c = conn.cursor() c.execute("insert into phonereport values (?, ?, ?, ?, ?)", (None, caller, 'food', speech, 'open')) response.say( 'I have notified the team that you require the following: ' + speech, voice='alice', language=locale) response.say( 'they will be in contact soon. Thank you for calling. Goodbye!', voice='alice', language=locale) conn.commit() conn.close() else: response.say( 'Unfortunately I am unable to process your call as you are witholding your caller id. You can either disable your caller ID or use our online service. Thank You, Goodbye.' ) return str(response) return app
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate # from flask_bootstrap import Bootstrap from flask_login import LoginManager from flask_admin import Admin # Initial solution but at the end, required to built own admin view from flask_admin.contrib.sqla import ModelView from flask_talisman import Talisman, ALLOW_FROM from config import DevelopmentConfig, TestConfig, ProductionConfig app = Flask(__name__, static_folder='./static', template_folder='./layouts') app.config.from_object( ProductionConfig) # Dont forget to switch stripe key in prospectly.js talisman = Talisman(app, content_security_policy=app.config['CSP'], content_security_policy_nonce_in=['script-src']) db = SQLAlchemy(app) migrate = Migrate(app, db) # bootstrap = Bootstrap(app) login_manager = LoginManager(app) login_manager.login_view = 'auth.login' # set the endpoint for the login page login_manager.login_message = 'Vous devez etre connecté pour voir cette page.' from .models import * from .errors import errors as errors_blueprint app.register_blueprint(errors_blueprint) from .main import main as main_blueprint
import logging, os from logging.handlers import SMTPHandler, RotatingFileHandler from flask import Flask from flask_seasurf import SeaSurf from flask_talisman import Talisman from config import Config, Development seasurf = SeaSurf() talisman = Talisman() csp = { 'default-src': [ '\'self\'', '*.cloudflare.com', '*.jsdelivr.net', '*.jquery.com', '*.gravatar.com', '*.googleapis.com', '*.w3.org', '*.github.com' ], 'script-src': [ '\'self\'', '*.cloudflare.com', '*.jsdelivr.net', '*.jquery.com', '*.gravatar.com', '*.googleapis.com', '*.w3.org', '*.github.com' ], 'style-src': [ '\'unsafe-inline\' \'self\'', '*.cloudflare.com', '*.jsdelivr.net', '*.jquery.com', '*.gravatar.com', '*.googleapis.com', '*.w3.org', '*.github.com' ], } def create_app(config_class=Development): """Construct the core application.""" app = Flask(__name__, instance_relative_config=True, static_url_path='')
from flask import Flask from config import Config from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_login import LoginManager from flask_talisman import Talisman import json application = Flask(__name__) Talisman(application) application.config.from_object(Config) db = SQLAlchemy(application) migrate = Migrate(application, db) login = LoginManager(application) login.login_view = 'login' from app import routes, models