Gestione dei BluePrint """ app = Flask(__name__) app.secret_key = "sezdrtfyuijko" # utenti app.register_blueprint(main) # amministratori app.register_blueprint(admin, url_prefix='/admin') # sezione login app.register_blueprint(auth, url_prefix='/auth') # comunicazione arduino app.register_blueprint(arduino, url_prefix='/arduino') # email mittente DEFAULT_SENDER = "*****@*****.**" # protezione con token csrf = CSRFProtect(app) # esenzione da protezione token, per comunicazione con arduino csrf.exempt("arduinoHandler.controllers.addParking") csrf.exempt("arduinoHandler.controllers.setParking") csrf.exempt("arduinoHandler.controllers.test_attuatore") csrf.exempt("arduinoHandler.controllers.attesa")
""" return dict(url_for=dated_url_for) def dated_url_for(endpoint, **values): if endpoint == 'static': filename = values.get('filename', None) # pdf.js 用来加载 PDF, 这个特例不需要加查询戳 if filename == 'js/pdfjs/web/viewer.html': pass elif filename: file_path = os.path.join(app.root_path, endpoint, filename) # 如果静态资源不存在, 则会抛出异常, 异常中不用做处理。 try: values['q'] = int(os.stat(file_path).st_mtime) except OSError: pass return url_for(endpoint, **values) manager = Manager(app) migrate = Migrate(app, db) babel = Babel(app) csrf = CSRFProtect(app) csrf.exempt(wechat.views.process) manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run()
if app.debug: app.logger.setLevel(logging.DEBUG) # pylint: disable=no-member else: # In production mode, add log handler to sys.stderr. app.logger.addHandler(logging.StreamHandler()) # pylint: disable=no-member app.logger.setLevel(logging.INFO) # pylint: disable=no-member logging.getLogger('pyhive.presto').setLevel(logging.INFO) db = SQLA(app) if conf.get('WTF_CSRF_ENABLED'): csrf = CSRFProtect(app) csrf_exempt_list = conf.get('WTF_CSRF_EXEMPT_LIST', []) for ex in csrf_exempt_list: csrf.exempt(ex) pessimistic_connection_handling(db.engine) cache = setup_cache(app, conf.get('CACHE_CONFIG')) tables_cache = setup_cache(app, conf.get('TABLE_NAMES_CACHE_CONFIG')) migrate = Migrate(app, db, directory=APP_DIR + '/migrations') # Logging configuration logging.basicConfig(format=app.config.get('LOG_FORMAT')) logging.getLogger().setLevel(app.config.get('LOG_LEVEL')) if app.config.get('ENABLE_TIME_ROTATE'): logging.getLogger().setLevel(app.config.get('TIME_ROTATE_LOG_LEVEL')) handler = TimedRotatingFileHandler(
def create_app(test_config=None): app = Flask(__name__) app.config.from_mapping(get_config()) if test_config is not None: # load the test config if passed in app.config.update(test_config) # Connect the db db.init_app(app) # Set up flask-login login_manager = LoginManager() login_manager.init_app(app) # Set up flask-principal for roles management principals = Principal() principals.init_app(app) # Set up csrf protection csrf = CSRFProtect() csrf.init_app(app) csrf.exempt(login_blueprint) app.register_blueprint(login_blueprint) app.register_blueprint(admin_blueprint, url_prefix="/admin") app.register_blueprint(token_management_blueprint, url_prefix="/user") app.register_blueprint(aggregation_unit_blueprint, url_prefix="/spatial_aggregation") # Set the log level app.before_first_request( partial(app.logger.setLevel, app.config["LOG_LEVEL"])) if app.config["DEMO_MODE"]: # Create demo data app.before_first_request(make_demodata) else: # Initialise the database app.before_first_request(partial(init_db, force=app.config["RESET_DB"])) # Create an admin user app.before_first_request( partial( add_admin, username=app.config["ADMIN_USER"], password=app.config["ADMIN_PASSWORD"], )) app.before_first_request(app.config["DB_IS_SET_UP"].wait ) # Cause workers to wait for db to set up @app.after_request def set_xsrf_cookie(response): """ Sets the csrf token used by csrf protect as a cookie to allow usage with react. """ response.set_cookie("X-CSRF", generate_csrf()) try: current_app.logger.debug( f"Logged in user was {flask.g.user.username}:{flask.g.user.id}" ) current_app.logger.debug(flask.session) except AttributeError: current_app.logger.debug(f"User was not logged in.") return response @app.errorhandler(CSRFError) def handle_csrf_error(e): """ CSRF errors are interpreted as an access denied. """ return "CSRF error", 401 @app.errorhandler(InvalidUsage) def handle_invalid_usage(error): response = flask.jsonify(error.to_dict()) response.status_code = error.status_code return response @app.before_request def before_request(): """ Make sessions expire after 20 minutes of inactivity. """ flask.session.permanent = True app.permanent_session_lifetime = datetime.timedelta(minutes=20) flask.session.modified = True flask.g.user = flask_login.current_user try: current_app.logger.debug( f"Logged in user is {flask.g.user.username}:{flask.g.user.id}") current_app.logger.debug(flask.session) except AttributeError: current_app.logger.debug(f"User is not logged in.") @login_manager.user_loader def load_user(userid): """Helper for flask-login.""" return User.query.filter(User.id == userid).first() @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): """Helper for flask-principal.""" # Set the identity user object identity.user = current_user # Add the UserNeed to the identity if hasattr(current_user, "id"): identity.provides.add(UserNeed(current_user.id)) try: if current_user.is_admin: identity.provides.add(RoleNeed("admin")) except AttributeError: pass # Definitely not an admin @app.cli.command("get-fernet") def make_flowauth_fernet_key(): """ Generate a new Fernet key for symmetric encryption of data at rest. """ print(f'FLOWAUTH_FERNET_KEY="{Fernet.generate_key().decode()}"') # Add flask <command> CLI commands app.cli.add_command(demodata) app.cli.add_command(init_db_command) app.cli.add_command(add_admin_command) return app
def create_app(test_config=None): app = Flask(__name__, instance_relative_config=True) app.config.from_object("config") if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile("config.py", silent=True) else: # load the test config if passed in app.config.update(test_config) # Connect the db db.init_app(app) # Set up flask-login login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = "/" # Set up flask-principal for roles management principals = Principal() principals.init_app(app) # Set up csrf protection csrf = CSRFProtect() csrf.init_app(app) csrf.exempt(login_blueprint) app.register_blueprint(login_blueprint) app.register_blueprint(admin_blueprint, url_prefix="/admin") app.register_blueprint(token_management_blueprint, url_prefix="/user") app.register_blueprint( aggregation_unit_blueprint, url_prefix="/spatial_aggregation" ) @app.after_request def set_xsrf_cookie(response): """ Sets the csrf token used by csrf protect as a cookie to allow usage with react. """ response.set_cookie("X-CSRF", generate_csrf()) return response @app.errorhandler(CSRFError) def handle_csrf_error(e): """ CSRF errors are interpreted as an access denied. """ return "CSRF error", 401 @app.errorhandler(InvalidUsage) def handle_invalid_usage(error): response = flask.jsonify(error.to_dict()) response.status_code = error.status_code return response @app.before_request def before_request(): """ Make sessions expire after 20 minutes of inactivity. """ flask.session.permanent = True app.permanent_session_lifetime = datetime.timedelta(minutes=20) flask.session.modified = True flask.g.user = flask_login.current_user @login_manager.user_loader def load_user(userid): """Helper for flask-login.""" return User.query.filter(User.id == userid).first() @identity_loaded.connect_via(app) def on_identity_loaded(sender, identity): """Helper for flask-principal.""" # Set the identity user object identity.user = current_user # Add the UserNeed to the identity if hasattr(current_user, "id"): identity.provides.add(UserNeed(current_user.id)) try: if current_user.is_admin: identity.provides.add(RoleNeed("admin")) except AttributeError: pass # Definitely not an admin @app.cli.command("get-fernet") def make_fernet_key(): """ Generate a new Fernet key for symmetric encryption of data at rest. """ print(f'FERNET_KEY="{Fernet.generate_key().decode()}"') # Add flask <command> CLI commands app.cli.add_command(demodata) app.cli.add_command(init_db_command) app.cli.add_command(add_admin) return app
# This attaches the *flask_sso* login handler to the SSO_LOGIN_URL, ext = SSO(app=app) from flowapp import models, constants, validators from .views.admin import admin from .views.rules import rules from .views.api_v1 import api as api_v1 from .views.api_v2 import api as api_v2 from .views.api_v3 import api as api_v3 from .views.api_keys import api_keys from .auth import auth_required from .views.dashboard import dashboard # no need for csrf on api because we use JWT csrf.exempt(api_v1) csrf.exempt(api_v2) app.register_blueprint(admin, url_prefix='/admin') app.register_blueprint(rules, url_prefix='/rules') app.register_blueprint(api_keys, url_prefix='/api_keys') app.register_blueprint(api_v1, url_prefix='/api/v1') app.register_blueprint(api_v2, url_prefix='/api/v2') app.register_blueprint(api_v3, url_prefix='/api/v3') app.register_blueprint(dashboard, url_prefix='/dashboard') @ext.login_handler def login(user_info): try: uuid = user_info.get('eppn')
app.register_blueprint(my_oauth2_provider.blueprint, url_prefix='/oauth') app.register_blueprint(blueprint_applications, url_prefix='/applications') app.register_blueprint(blueprint_main, url_prefix='/') from lucky_club.api.profile.view import blueprint_users from lucky_club.api.categories.views import blueprint_categories from lucky_club.api.lots.views import blueprint_lots from lucky_club.api.attaches.views import blueprint_attachments app.register_blueprint(blueprint_users, url_prefix='/api/profile') app.register_blueprint(blueprint_categories, url_prefix='/api/categories') app.register_blueprint(blueprint_lots, url_prefix='/api/lots') app.register_blueprint(blueprint_attachments, url_prefix='/api/attachments') # disable csrf protection for api urls csrf.exempt(my_oauth2_provider.blueprint) csrf.exempt(blueprint_users) csrf.exempt(blueprint_categories) csrf.exempt(blueprint_lots) csrf.exempt(blueprint_attachments) @app.cli.command('initdb') def initdb_command(): """Creates the database tables.""" from lucky_club.database import init_db init_db() print('Initialized the database.') @app.context_processor
# 注册路由 register_blueprint(app, ADMIN_ROUTES) register_blueprint(app, MOBILE_ROUTES) register_blueprint(app, API_ROUTES) register_blueprint(app, PC_ROUTES) # 数据库初始化 db.init_app(app) # 上传文件存储 configure_uploads(app) # 启动form表单csr保护 csrf = CSRFProtect(app) csrf.exempt('app.views.admin.upload.ueditor') csrf.exempt('app.views.api.pay.notify') # flask session Session(app) excel.init_excel(app) # 注册jinja模板过滤器 jinja_filters = { 'timestamp2str':timestamp2str, 'before_after_timestamp':before_after_timestamp, 'json_loads':json_loads, 'static_uri':static_uri, 'toint':toint, 'toamount':toamount,
def create_app(): app = Flask(__name__, template_folder='templates', static_folder='frontend') env = os.environ.get('FLASK_ENV') if env == 'production': app.config.from_object(ProdConfig) else: app.config.from_object(DevConfig) db.init_app(app) csrf = CSRFProtect(app) login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'auth.login' ma.init_app(app) @login_manager.user_loader def load_user(user_id): with db.session_scope() as session: return session.query(User).filter_by(id=user_id).first() return False @login_manager.request_loader def load_user_from_request(request): if request.method == "GET" and 'login' in request.path: return None auth_header = request.headers.get('Authorization') if auth_header: auth_header = auth_header.replace('Basic ', '', 1) try: credentials = base64.b64decode(auth_header).decode() credentials = credentials.split(':') user = authenticate_user(credentials[0], credentials[1]) return user except TypeError as e: logging.error({'exception': str(e)}) return None @app.route("/test") def test(): counter = db.redis.incr("counter") return "<b>Count:</b> {}".format(counter) @app.route('/') @app.route('/account', endpoint='account') @app.route('/trade', endpoint='trade') @app.route('/activity', endpoint='activty') @login_required def index(): return render_template('index.html', env=current_app.config['ENV'], dev_server=current_app.config['WEBPACK_DEV_SERVER']) @app.context_processor def inject_date(): return { 'now': datetime.datetime.utcnow() } #TODO: Error handling across API and Application. # @app.errorhandler(Exception) # def handle_exception(e): # exc_type, exc_value, exc_traceback = sys.exc_info() # logging.error(str(e)) # logging.error('\n' + ''.join(traceback.format_tb(exc_traceback))) # if request.path.startswith('/api/'): # if isinstance(e, HTTPException): # response = { 'error': e.description } # return response, e.code # response = { 'error': errors.DEFAULT } # return response, 500 # else: # if hasattr(e, 'code') and e.code == 404: # return render_template('errors/404.html') # else: # return render_template('errors/500.html') with app.app_context(): for bp in api_blueprints: csrf.exempt(bp[0]) app.register_blueprint(bp[0], url_prefix='/api{}'.format(bp[1])) app.register_blueprint(auth_bp) return app
site = Flask(__name__) site.config.from_object(os.environ['SITE_CONFIG']) site.register_blueprint(typus_web.bp, url_prefix='/typus') site.register_blueprint(flatpages.bp) pages = FlatPages(site) babel = Babel(site) csrf = CSRFProtect(site) # F*****g Jesus f**k! I'm not able to pass a class based view # since it has an endpoint which is not equal to views's name! # And I can't use a decorator because of relative f*****g imports! # See the form, it has to exempt csrf too. # Who the hell had invented this? csrf.exempt('website.apps.typus_web.views.api_view') @babel.localeselector def get_locale(): supported_locals = site.config['BABEL_SUPPORTED_LOCALES'] lang = request.args.get('lang') if lang and lang in supported_locals: return lang fallback = site.config['BABEL_DEFAULT_LOCALE'] return request.accept_languages.best_match(supported_locals) or fallback @site.before_request def before_request():
app.config.setdefault('SSO_ATTRIBUTE_MAP', SSO_ATTRIBUTE_MAP) app.config.setdefault('SSO_LOGIN_URL', '/login') # This attaches the *flask_sso* login handler to the SSO_LOGIN_URL, ext = SSO(app=app) from flowapp import models, constants, validators from .views.admin import admin from .views.rules import rules from .views.apiv1 import api from .views.api_keys import api_keys from .auth import auth_required from .views.dashboard import dashboard # no need for csrf on api because we use JWT csrf.exempt(api) app.register_blueprint(admin, url_prefix='/admin') app.register_blueprint(rules, url_prefix='/rules') app.register_blueprint(api_keys, url_prefix='/api_keys') app.register_blueprint(api, url_prefix='/api/v1') app.register_blueprint(dashboard, url_prefix='/dashboard') @ext.login_handler def login(user_info): try: uuid = user_info.get('eppn') except KeyError: uuid = False return redirect('/')
@app.errorhandler(404) def not_found(error): return render_template('404.html'), 404 from .mod_auth.config_manager import ConfigManager # init config manager config_manager = ConfigManager(app.config['USER_CONFIG_PATH']) from .mod_main.controllers import mod_main as main_module from .mod_auth.controllers import mod_auth as auth_module from .mod_api.controllers import mod_api as api_module # api module routes does not require login, # so no csrf is required # (hijacking session is useless, autentization is done via api key) csrf.exempt(api_module) app.register_blueprint(main_module) app.register_blueprint(auth_module) app.register_blueprint(api_module) db.create_all() # if debug flag is true, allow simulator @app.route('/simulator') def simulator(): if app.config['DEBUG'] == True: return render_template('simulator.html') return render_template('404.html'), 404 def run():
def create_app(config: "SDConfig") -> Flask: app = Flask( __name__, template_folder=config.JOURNALIST_TEMPLATES_DIR, static_folder=path.join(config.SECUREDROP_ROOT, "static"), ) app.config.from_object(config.JOURNALIST_APP_FLASK_CONFIG_CLS) app.session_interface = JournalistInterfaceSessionInterface() csrf = CSRFProtect(app) app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False app.config["SQLALCHEMY_DATABASE_URI"] = config.DATABASE_URI db.init_app(app) class JSONEncoder(json.JSONEncoder): """Custom JSON encoder to use our preferred timestamp format""" def default(self, obj: "Any") -> "Any": if isinstance(obj, datetime): return obj.strftime(API_DATETIME_FORMAT) super(JSONEncoder, self).default(obj) app.json_encoder = JSONEncoder # TODO: enable type checking once upstream Flask fix is available. See: # https://github.com/pallets/flask/issues/4295 @app.errorhandler(CSRFError) # type: ignore def handle_csrf_error(e: CSRFError) -> "Response": app.logger.error("The CSRF token is invalid.") session.clear() msg = gettext("You have been logged out due to inactivity.") flash(msg, "error") return redirect(url_for("main.login")) def _handle_http_exception( error: "HTTPException", ) -> "Tuple[Union[Response, str], Optional[int]]": # Workaround for no blueprint-level 404/5 error handlers, see: # https://github.com/pallets/flask/issues/503#issuecomment-71383286 # TODO: clean up API error handling such that all except 404/5s are # registered in the blueprint and 404/5s are handled at the application # level. handler = list(app.error_handler_spec["api"][error.code].values())[0] if request.path.startswith("/api/") and handler: return handler(error) # type: ignore return render_template("error.html", error=error), error.code for code in default_exceptions: app.errorhandler(code)(_handle_http_exception) i18n.configure(config, app) app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True app.jinja_env.globals["version"] = version.__version__ app.jinja_env.filters["rel_datetime_format"] = template_filters.rel_datetime_format app.jinja_env.filters["filesizeformat"] = template_filters.filesizeformat app.jinja_env.filters["html_datetime_format"] = template_filters.html_datetime_format app.jinja_env.add_extension("jinja2.ext.do") @app.before_first_request def expire_blacklisted_tokens() -> None: cleanup_expired_revoked_tokens() @app.before_request def update_instance_config() -> None: InstanceConfig.get_default(refresh=True) @app.before_request def setup_g() -> "Optional[Response]": """Store commonly used values in Flask's special g object""" if "expires" in session and datetime.now(timezone.utc) >= session["expires"]: session.clear() flash(gettext("You have been logged out due to inactivity."), "error") uid = session.get("uid", None) if uid: user = Journalist.query.get(uid) if user and "nonce" in session and session["nonce"] != user.session_nonce: session.clear() flash(gettext("You have been logged out due to password change"), "error") session["expires"] = datetime.now(timezone.utc) + timedelta( minutes=getattr(config, "SESSION_EXPIRATION_MINUTES", 120) ) uid = session.get("uid", None) if uid: g.user = Journalist.query.get(uid) # pylint: disable=assigning-non-slot i18n.set_locale(config) if InstanceConfig.get_default().organization_name: g.organization_name = ( # pylint: disable=assigning-non-slot InstanceConfig.get_default().organization_name ) else: g.organization_name = gettext("SecureDrop") # pylint: disable=assigning-non-slot try: g.logo = get_logo_url(app) # pylint: disable=assigning-non-slot except FileNotFoundError: app.logger.error("Site logo not found.") if request.path.split("/")[1] == "api": pass # We use the @token_required decorator for the API endpoints else: # We are not using the API if request.endpoint not in _insecure_views and not logged_in(): return redirect(url_for("main.login")) if request.method == "POST": filesystem_id = request.form.get("filesystem_id") if filesystem_id: g.filesystem_id = filesystem_id # pylint: disable=assigning-non-slot g.source = get_source(filesystem_id) # pylint: disable=assigning-non-slot return None app.register_blueprint(main.make_blueprint(config)) app.register_blueprint(account.make_blueprint(config), url_prefix="/account") app.register_blueprint(admin.make_blueprint(config), url_prefix="/admin") app.register_blueprint(col.make_blueprint(config), url_prefix="/col") api_blueprint = api.make_blueprint(config) app.register_blueprint(api_blueprint, url_prefix="/api/v1") csrf.exempt(api_blueprint) return app
def create_app(test_config=None): from flowauth.config import get_config from flowauth.models import db from flowauth.cli import ( init_db_command, add_admin_command, make_flowauth_fernet_key, demo_data, ) from .admin import blueprint as admin_blueprint from .users import blueprint as users_blueprint from .groups import blueprint as groups_blueprint from .servers import blueprint as servers_blueprint from .token_management import blueprint as token_management_blueprint from .login import blueprint as login_blueprint from .user_settings import blueprint as user_settings_blueprint from .version import blueprint as version_blueprint app = Flask(__name__) app.config.from_mapping(get_config()) # Connect the logger app.before_first_request(connect_logger) if test_config is not None: # load the test config if passed in app.config.update(test_config) # Connect the db db.init_app(app) # Set up flask-login login_manager = LoginManager() login_manager.init_app(app) # Set up flask-principal for roles management principals = Principal() principals.init_app(app) # Set up csrf protection csrf = CSRFProtect() csrf.init_app(app) csrf.exempt(login_blueprint) csrf.exempt(version_blueprint) app.register_blueprint(login_blueprint) app.register_blueprint(admin_blueprint, url_prefix="/admin") app.register_blueprint(groups_blueprint, url_prefix="/admin") app.register_blueprint(servers_blueprint, url_prefix="/admin") app.register_blueprint(users_blueprint, url_prefix="/admin") app.register_blueprint(token_management_blueprint, url_prefix="/tokens") app.register_blueprint(user_settings_blueprint, url_prefix="/user") app.register_blueprint(version_blueprint) if app.config["DEMO_MODE"]: # Create demo data from flowauth.models import make_demodata app.before_first_request(make_demodata) else: # Initialise the database from flowauth.models import init_db from flowauth.models import add_admin app.before_first_request(lock(partial(init_db, force=app.config["RESET_DB"]))) # Create an admin user app.before_first_request( lock( partial( add_admin, username=app.config["ADMIN_USER"], password=app.config["ADMIN_PASSWORD"], ) ) ) app.before_first_request( app.config["DB_IS_SET_UP"].wait ) # Cause workers to wait for db to set up app.after_request(set_xsrf_cookie) app.errorhandler(CSRFError)(handle_csrf_error) app.errorhandler(InvalidUsage)(handle_invalid_usage) app.before_request(before_request) login_manager.user_loader(load_user) identity_loaded.connect_via(app)(on_identity_loaded) # Add flask <command> CLI commands app.cli.add_command(demo_data) app.cli.add_command(init_db_command) app.cli.add_command(add_admin_command) app.cli.add_command(make_flowauth_fernet_key) return app
def relay_buzz_request(msg): print('we have a buzz') socketio.emit('buzz', msg, namespace='/device_reading') @socketio.on('connect', namespace='/device_reading') @csrf.exempt def get_connected(): global sensor_thread global device_thread with thread_lock: if sensor_thread is None: sensor_thread = socketio.start_background_task( target=sensor_background_thread) if device_thread is None: device_thread = socketio.start_background_task( target=device_background_thread) emit('my_response', {'message': 'Connected'}, namespace='/device_reading') from project.users.views import users_blueprint from project.garden.views import garden_blueprint, get_device_status, get_latest_sensor_readings from project.sheep.views import sheep_blueprint from project.home_library.views import home_library_blueprint app.register_blueprint(users_blueprint) app.register_blueprint(garden_blueprint) app.register_blueprint(sheep_blueprint) app.register_blueprint(home_library_blueprint) csrf.exempt(garden_blueprint)
app.config.from_envvar('ATK_CONFIG') if 'ATK_MANAGEMENT_API_KEY' in os.environ: app.config['ATK_MANAGEMENT_API_KEY'] = os.environ['ATK_MANAGEMENT_API_KEY'] for handler in app.config['LOG_HANDLERS']: app.logger.addHandler(handler) app.logger.setLevel(logging.DEBUG) app.config['CORS_ORIGIN_WHITELIST'].append('https://mytiledriver.com') app.config['CORS_ORIGIN_WHITELIST'].append('https://tdprocess.com') app.config['TILEDRIVER_URL'] = 'https://app.tiledriver.com/' from .views.home import home, main, chain_run_status from .views.manage import manage app.register_blueprint(home) app.register_blueprint(manage) app.jinja_loader.searchpath.insert(0, app.config['ATK_PATH'] + '/templates') csrf = CSRFProtect(app) csrf.exempt(main) csrf.exempt(chain_run_status) @app.context_processor def inject_date(): return dict(date=datetime.datetime.now())
# load config from ../instance/config.py if exists app.config.from_pyfile('config.py', silent=True) db.init_app(app) # enable global csrf protection csrf.init_app(app) login_manager.init_app(app) login_manager.login_message = "You must be logged in to access this page." login_manager.login_view = "auth.login" migrate = Migrate(app, db) from app import models from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint) from .home import home as home_blueprint app.register_blueprint(home_blueprint) from .history import history as history_blueprint app.register_blueprint(history_blueprint) from .api import bp as api_bp # app.register_blueprint(users_api) app.register_blueprint(api_bp, url_prefix='/api') csrf.exempt(api_bp) # return app
from system.forms import * from os import environ, path from shutil import copyfile from routes.ui import routes as main_routes from routes.api import api_bp from flask_caching import Cache global db csrf = CSRFProtect() # disable csrf-protection for http sniffer csrf.exempt("routes.tools.http_sniffer_capture_page") config = config_dict() compress = Compress() db = Database(config) app = Flask(__name__, static_folder=None, template_folder='templates') app.config['DATABASE'] = db app.config['SESSION_PERMANENT'] = False app.config['SESSION_TYPE'] = 'filesystem' app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=5) app.config['SECRET_KEY'] = config['main']['secret']
from forms import LoginForm, SignupForm from models import User, db app = Flask(__name__) app.config.update( SECRET_KEY=os.urandom(32), SQLALCHEMY_TRACK_MODIFICATIONS=False, SQLALCHEMY_DATABASE_URI="sqlite:///db.sqlite3", SESSION_COOKIE_SAMESITE="Lax", ) app.register_blueprint(api_blueprint.api_blueprint) app.register_blueprint(todo_app_blueprint.todo_app_blueprint) csrf = CSRFProtect(app) csrf.exempt(api_blueprint.api_blueprint) login_manager = LoginManager(app) login_manager.login_view = "login" login_manager.login_message_category = "danger" db.init_app(app) with app.app_context(): db.create_all() db.session.commit() @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id))
def create_app(conf='dev'): # Initialize core application and load configuration app = Flask(__name__, instance_relative_config=True) if conf == 'dev': app.config.from_object(DevConfig) elif conf == 'test': app.config.from_object(TestConfig) else: app.config.from_object(ProdConfig) # ensure the instance and storage folders exist try: os.makedirs(app.instance_path) except OSError: pass try: os.makedirs(os.path.join(app.instance_path, 'storage')) except OSError: pass # Ensure responses aren't cached @app.after_request def add_header(response): response.headers[ "Cache-Control"] = "no-cache, no-store, must-revalidate" response.headers["Expires"] = 0 response.headers["Pragma"] = "no-cache" return response # Initialize session Session(app) # Initialize JS integration plugin jsglue.init_app(app) # Initialize database db.init_app(app) # Initialize migration object migrate.init_app(app, db) # Initialize Login manager from photoric.modules.auth import login_manager login_manager.init_app(app) # Initialize permission control from photoric.modules.auth import authorize authorize.init_app(app) # Initialize admin module from photoric.modules.admin import admin_manager admin_manager.init_app(app) # Initialize (de)serialization schemas mm.init_app(app) # Initialize upload managers from photoric.modules.upload import photos, dropzone configure_uploads(app, photos) app.config['UPLOADED_PHOTOS_DEST'] = os.path.join(app.instance_path, 'storage') patch_request_class(app) dropzone.init_app(app) csrf = CSRFProtect(app) with app.app_context(): # register blueprints with views # from .modules.core.modfactory import modfactory from .modules.views import views_bp from .modules.auth import auth_bp from .modules.nav import nav_bp from .modules.search import search_bp from .modules.upload import upload_bp from .modules.images import images_bp from .modules.albums import albums_bp from .modules.admin import admin_bp from .modules.api import api_bp # exclude api routes from WTF csrf protection to avoid error on POST, PUT ... csrf.exempt(api_bp) # app.register_blueprint(modfactory.modfactory) app.register_blueprint(views_bp) app.register_blueprint(auth_bp) app.register_blueprint(nav_bp) app.register_blueprint(search_bp) app.register_blueprint(upload_bp) app.register_blueprint(images_bp) app.register_blueprint(albums_bp) app.register_blueprint(admin_bp) app.register_blueprint(api_bp) # import all models from photoric.modules.auth.models import UserRole, UserGroup, User, Role, Group, load_user from photoric.core.models import AlbumImage, Image, Album, Navbar, NavbarItem, Menu, MenuItem, Config # create database db.create_all() # filters and variables for jinja2 templates @app.template_global() def site_name(): return app.config['SITE_NAME'] # initial setup from .config.initial_setup import initial_setup app.before_first_request(initial_setup) return app
my_oauth2_provider.init_app(app) from app.users_manager.view import blueprint_applications from app.main_page.view import blueprint_main app.register_blueprint(auth.blueprint, url_prefix='/authorize') app.register_blueprint(my_oauth2_provider.blueprint, url_prefix='/oauth') app.register_blueprint(blueprint_applications, url_prefix='/applications') app.register_blueprint(blueprint_main, url_prefix='/') from app.api.users.view import blueprint_users app.register_blueprint(blueprint_users, url_prefix='/api/profile') # disable csrf protection for api urls csrf.exempt(my_oauth2_provider.blueprint) csrf.exempt(blueprint_users) @app.cli.command('initdb') def initdb_command(): """Creates the database tables.""" from app.database import init_db init_db() print('Initialized the database.') @app.context_processor def site_name(): """ inject site name in context
from google_oauth import oauth from instagram_api.blueprints.users.views import users_api_blueprint from flask_wtf.csrf import CSRFProtect app.register_blueprint(users_blueprint, url_prefix="/users") app.register_blueprint(sessions_blueprint, url_prefix="/sessions") app.register_blueprint(images_blueprint, url_prefix="/images") app.register_blueprint(following_blueprint, url_prefix="/following") oauth.init_app(app) assets = Environment(app) assets.register(bundles) app.config.from_object("config") csrf = CSRFProtect(app) csrf.exempt(users_api_blueprint) @app.errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500 @app.errorhandler(405) def internal_server_error(e): return render_template('405.html'), 405 @app.errorhandler(404) def internal_server_error(e): return render_template('404.html'), 404
app = Flask(__name__) app.config.from_object('config') db.init_app(app) app.json_encoder = CustomDecimalJSONEncoder CORS(app) csrf = CSRFProtect(app) from recorder.api.records.views import blueprint_records app.register_blueprint(blueprint_records, url_prefix='/media/api/records') # disable csrf protection for api urls csrf.exempt(blueprint_records) @app.cli.command('initdb') def initdb_command(): """Creates the database tables.""" from recorder.database import init_db init_db() print('Initialized the database.') @app.context_processor def site_name(): """ inject site name in context :return:
patch_request_class) from flask_wtf.csrf import CSRFProtect secrets = json.load(open('config.json')) app = Flask(__name__) app.config['BASE_FE_URL'] = secrets['BASE_FE_URL'] bcrypt = Bcrypt(app) CORS(app) csrf = CSRFProtect(app) app.config['MONGODB_SETTINGS'] = { 'db': 'jboard', 'host': secrets['mlab_host'], 'username': secrets['mlab_username'], 'password': secrets['mlab_password'] } db = MongoEngine(app) from jboardapi.posts.views import posts_blueprint from jboardapi.comments.views import comments_blueprint from jboardapi.forums.views import forums_blueprint # register blueprints blueprints = [posts_blueprint, comments_blueprint, forums_blueprint] for blueprint in blueprints: csrf.exempt(blueprint) CORS(blueprint) app.register_blueprint(blueprint)
def create_app(config: 'SDConfig') -> Flask: app = Flask(__name__, template_folder=config.JOURNALIST_TEMPLATES_DIR, static_folder=path.join(config.SECUREDROP_ROOT, 'static')) app.config.from_object(config.JOURNALIST_APP_FLASK_CONFIG_CLS) app.session_interface = JournalistInterfaceSessionInterface() csrf = CSRFProtect(app) Environment(app) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = config.DATABASE_URI db.init_app(app) v2_enabled = path.exists( path.join(config.SECUREDROP_DATA_ROOT, 'source_v2_url')) v3_enabled = path.exists( path.join(config.SECUREDROP_DATA_ROOT, 'source_v3_url')) app.config.update(V2_ONION_ENABLED=v2_enabled, V3_ONION_ENABLED=v3_enabled) # TODO: Attaching a Storage dynamically like this disables all type checking (and # breaks code analysis tools) for code that uses current_app.storage; it should be refactored app.storage = Storage(config.STORE_DIR, config.TEMP_DIR, config.JOURNALIST_KEY) # TODO: Attaching a CryptoUtil dynamically like this disables all type checking (and # breaks code analysis tools) for code that uses current_app.storage; it should be refactored app.crypto_util = CryptoUtil( scrypt_params=config.SCRYPT_PARAMS, scrypt_id_pepper=config.SCRYPT_ID_PEPPER, scrypt_gpg_pepper=config.SCRYPT_GPG_PEPPER, securedrop_root=config.SECUREDROP_ROOT, word_list=config.WORD_LIST, nouns_file=config.NOUNS, adjectives_file=config.ADJECTIVES, gpg_key_dir=config.GPG_KEY_DIR, ) @app.errorhandler(CSRFError) def handle_csrf_error(e: CSRFError) -> 'Response': # render the message first to ensure it's localized. msg = gettext('You have been logged out due to inactivity.') session.clear() flash(msg, 'error') return redirect(url_for('main.login')) def _handle_http_exception( error: 'HTTPException' ) -> 'Tuple[Union[Response, str], Optional[int]]': # Workaround for no blueprint-level 404/5 error handlers, see: # https://github.com/pallets/flask/issues/503#issuecomment-71383286 handler = list(app.error_handler_spec['api'][error.code].values())[0] if request.path.startswith('/api/') and handler: return handler(error) return render_template('error.html', error=error), error.code for code in default_exceptions: app.errorhandler(code)(_handle_http_exception) i18n.setup_app(config, app) app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True app.jinja_env.globals['version'] = version.__version__ app.jinja_env.filters['rel_datetime_format'] = \ template_filters.rel_datetime_format app.jinja_env.filters['filesizeformat'] = template_filters.filesizeformat @app.before_first_request def expire_blacklisted_tokens() -> None: cleanup_expired_revoked_tokens() @app.before_request def load_instance_config() -> None: app.instance_config = InstanceConfig.get_current() @app.before_request def setup_g() -> 'Optional[Response]': """Store commonly used values in Flask's special g object""" if 'expires' in session and datetime.utcnow() >= session['expires']: session.clear() flash(gettext('You have been logged out due to inactivity.'), 'error') uid = session.get('uid', None) if uid: user = Journalist.query.get(uid) if user and 'nonce' in session and \ session['nonce'] != user.session_nonce: session.clear() flash( gettext('You have been logged out due to password change'), 'error') session['expires'] = datetime.utcnow() + \ timedelta(minutes=getattr(config, 'SESSION_EXPIRATION_MINUTES', 120)) # Work around https://github.com/lepture/flask-wtf/issues/275 # -- after upgrading from Python 2 to Python 3, any existing # session's csrf_token value will be retrieved as bytes, # causing a TypeError. This simple fix, deleting the existing # token, was suggested in the issue comments. This code will # be safe to remove after Python 2 reaches EOL in 2020, and no # supported SecureDrop installations can still have this # problem. if sys.version_info.major > 2 and type( session.get('csrf_token')) is bytes: del session['csrf_token'] uid = session.get('uid', None) if uid: g.user = Journalist.query.get(uid) g.locale = i18n.get_locale(config) g.text_direction = i18n.get_text_direction(g.locale) g.html_lang = i18n.locale_to_rfc_5646(g.locale) g.locales = i18n.get_locale2name() if not app.config['V3_ONION_ENABLED'] or app.config['V2_ONION_ENABLED']: g.show_v2_onion_eol_warning = True if request.path.split('/')[1] == 'api': pass # We use the @token_required decorator for the API endpoints else: # We are not using the API if request.endpoint not in _insecure_views and not logged_in(): return redirect(url_for('main.login')) if request.method == 'POST': filesystem_id = request.form.get('filesystem_id') if filesystem_id: g.filesystem_id = filesystem_id g.source = get_source(filesystem_id) return None app.register_blueprint(main.make_blueprint(config)) app.register_blueprint(account.make_blueprint(config), url_prefix='/account') app.register_blueprint(admin.make_blueprint(config), url_prefix='/admin') app.register_blueprint(col.make_blueprint(config), url_prefix='/col') api_blueprint = api.make_blueprint(config) app.register_blueprint(api_blueprint, url_prefix='/api/v1') csrf.exempt(api_blueprint) return app
@app.cli.command("dbu-sql") def dbu_sql(): """ Generate SQL statements but you will personally have to `run` it on your DB :return: None """ upgrade(sql=True) @app.cli.command("dbu-no-sql") def dbu_no_sql(): """ Bring the DB up to date with your data models. Calls the migrate() :return: None """ upgrade() csrf = CSRFProtect(app) from modelate.models.profiling import User from modelate.controllers.apiv1 import apiv1 from modelate.controllers.frontend import frontend app.register_blueprint(frontend) app.register_blueprint(apiv1, url_prefix='/api/v1.0') # exempt API routes from csrf checks csrf.exempt(apiv1)
from views.my_account import my_account from views.my_files import my_files from views.submit_job import submit_job from flask_wtf.csrf import CSRFProtect from config import app_config from models import db from flask_swagger import swagger from swagger_ui import api_doc import config from apscheduler.schedulers.background import BackgroundScheduler import glob import os app = Flask(__name__) csrf = CSRFProtect(app) csrf.exempt("api") # Register routes app.config.from_object(app_config) # Add API api = Api(app, decorators=[csrf.exempt]) # LDAP api.add_resource(Sudo, '/api/ldap/sudo') api.add_resource(Authenticate, '/api/ldap/authenticate') api.add_resource(Ids, '/api/ldap/ids') api.add_resource(User, '/api/ldap/user') api.add_resource(Users, '/api/ldap/users') api.add_resource(Group, '/api/ldap/group') api.add_resource(Groups, '/api/ldap/groups')
from server.views import administration_users from server.views import administration_emails from server.views import administration_associations from server.views import administration_about from server.views import administration_files from server.views import forms app.register_blueprint(general.mod) app.register_blueprint(administration_general.mod) app.register_blueprint(administration_property.mod) app.register_blueprint(administration_emails.mod) app.register_blueprint(administration_associations.mod) app.register_blueprint(administration_users.mod) app.register_blueprint(administration_about.mod) app.register_blueprint(administration_files.mod) app.register_blueprint(forms.mod) csrf.exempt(forms.mod) # csrf.exempt(administration_about.mod) from server import models from server.models.users import Users @login_manager.user_loader def load_user(id): return Users.query.get(int(id)) #times out user @app.before_request def before_request(): session.permanent = True app.permanent_session_lifetime = datetime.timedelta(minutes=15)
if conf.get('SILENCE_FAB'): logging.getLogger('flask_appbuilder').setLevel(logging.ERROR) if not app.debug: # In production mode, add log handler to sys.stderr. app.logger.addHandler(logging.StreamHandler()) app.logger.setLevel(logging.INFO) logging.getLogger('pyhive.presto').setLevel(logging.INFO) db = SQLA(app) if conf.get('WTF_CSRF_ENABLED'): csrf = CSRFProtect(app) csrf_exempt_list = conf.get('WTF_CSRF_EXEMPT_LIST', []) for ex in csrf_exempt_list: csrf.exempt(ex) utils.pessimistic_connection_handling(db.engine) cache = utils.setup_cache(app, conf.get('CACHE_CONFIG')) tables_cache = utils.setup_cache(app, conf.get('TABLE_NAMES_CACHE_CONFIG')) migrate = Migrate(app, db, directory=APP_DIR + "/migrations") # Logging configuration logging.basicConfig(format=app.config.get('LOG_FORMAT')) logging.getLogger().setLevel(app.config.get('LOG_LEVEL')) if app.config.get('ENABLE_TIME_ROTATE'): logging.getLogger().setLevel(app.config.get('TIME_ROTATE_LOG_LEVEL')) handler = TimedRotatingFileHandler(
assets = Environment(app) assets.register(bundles) csrf = CSRFProtect(app) oauth.init_app(app) login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = "sessions.new" app.redis = Redis.from_url(app.config['REDIS_URL']) app.task_queue = rq.Queue(connection=app.redis) app.register_blueprint(users_blueprint, url_prefix="/users") app.register_blueprint(sessions_blueprint, url_prefix="/sessions") app.register_blueprint(images_blueprint, url_prefix="/images") app.register_blueprint(transactions_blueprint, url_prefix="/transactions") app.register_blueprint(relationships_blueprint, url_prefix="/requests") csrf.exempt(users_api_blueprint) csrf.exempt(sessions_api_blueprint) csrf.exempt(images_api_blueprint) @app.errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500 @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.errorhandler(403)