コード例 #1
0
    def __init__(self, import_name):
        super().__init__(import_name,
                         static_url_path='',
                         static_folder=os.path.join(os.getcwd(), 'web', 'static'),
                         template_folder=os.path.join(os.getcwd(), 'web', 'templates', 'public'))
        self.wsgi_app = ProxyFix(self.wsgi_app)
        self.data_store_client = datastore.Client()
        self.client_secret = CLIENT_SECRET
        self.firebase_admin_secret = FIREBASE_ADMIN_SECRET
        self.firebase_admin_credentials = FIREBASE_ADMIN_CREDENTIALS
        firebase_admin.initialize_app(self.firebase_admin_credentials)

        # database

        self.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI
        # self.config["SQLALCHEMY_ECHO"] = SQLALCHEMY_ECHO
        self.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = SQLALCHEMY_TRACK_MODIFICATIONS
        self.config["SQLALCHEMY_POOL_TIMEOUT"] = SQLALCHEMY_POOL_TIMEOUT
        self.config["SQLALCHEMY_MAX_OVERFLOW"] = SQLALCHEMY_MAX_OVERFLOW
        self.config['SWAGGER_UI_DOC_EXPANSION'] = SWAGGER_UI_DOC_EXPANSION
        self.config['RESTPLUS_VALIDATE'] = RESTPLUS_VALIDATE
        self.config['RESTPLUS_MASK_SWAGGER'] = RESTPLUS_MASK_SWAGGER
        self.config['ERROR_404_HELP'] = ERROR_404_HELP

        self.db = db
        self.db.init_app(self)
        self.app_context().push()

        with self.app_context():
            self.db.create_all()  # Create database tables for our data models

        self.flow = None
        self.session = dict()

        self.cache = Cache(app=self, config={'CACHE_TYPE': 'simple'})
        self.config['SITEMAP_INCLUDE_RULES_WITHOUT_PARAMS'] = False  # true for listing every route available
        self.flask_sitemap = Sitemap(app=self)
        # keep a sitemap only for the pages that does not require authentication (may add special cases later)
        self.flask_sitemap.register_generator(self.root_sitemap)

        self.add_url_rule('/', view_func=self.landing, methods=['GET'])
        self.add_url_rule('/profile', view_func=self.profile, methods=['GET'])
        self.add_url_rule('/dashboard', view_func=self.dashboard, methods=['GET'])
        self.add_url_rule('/categories', view_func=self.categories, methods=['GET', 'POST'])
        self.add_url_rule('/add_category', view_func=self.add_category, methods=['GET', 'POST'])
        self.add_url_rule('/delete_category/<int:category_id>', view_func=self.delete_category, methods=['GET'])
        self.add_url_rule('/my_projects', view_func=self.my_projects, methods=['GET'])
        self.add_url_rule('/add_project', view_func=self.add_project, methods=['GET', 'POST'])
        self.add_url_rule('/see_project/<int:project_id>', view_func=self.see_project, methods=['GET'])
        self.add_url_rule('/delete_project/<int:project_id>', view_func=self.delete_project, methods=['GET'])
        self.add_url_rule('/my_jobs', view_func=self.my_jobs, methods=['GET'])
        self.add_url_rule('/see_job/<int:job_id>', view_func=self.see_job, methods=['GET'])
        self.add_url_rule('/delete_job/<int:job_id>', view_func=self.delete_job, methods=['GET'])
        self.add_url_rule('/add_job', view_func=self.add_job, methods=['GET', 'POST'])
        self.add_url_rule('/marketplace', view_func=self.marketplace, methods=['GET'])
        self.add_url_rule('/product/<int:product_id>', view_func=self.product, methods=['GET'])
        self.add_url_rule('/logout', view_func=self.logout, methods=['GET'])
        self.add_url_rule('/login', view_func=self.login, methods=['GET'])

        # APIs endpoints
        blueprint = Blueprint('api', __name__, url_prefix='/api')
        api.init_app(blueprint)
        api.add_namespace(categories_namespace)
        api.add_namespace(jobs_namespace)
        api.add_namespace(attachments_namespace)
        api.add_namespace(biddings_namespace)
        api.add_namespace(projects_namespace)
        api.add_namespace(projects_assets_namespace)
        api.add_namespace(marketplace_namespace)
        api.add_namespace(assets_namespace)
        self.register_blueprint(blueprint)

        self.register_error_handler(500, self.server_error)
        self.register_error_handler(404, self.not_found)
コード例 #2
0
ファイル: main.py プロジェクト: djoek/Flask-Auth0
import os

from flask import Flask, request, make_response
from flask_auth0 import AuthorizationCodeFlow

from werkzeug.middleware.proxy_fix import ProxyFix

from cachelib import FileSystemCache

app = Flask(__name__, template_folder='templates')
app.wsgi_app = ProxyFix(app.wsgi_app,
                        x_for=1,
                        x_proto=1,
                        x_host=1,
                        x_port=1,
                        x_prefix=1)

app.secret_key = os.getenv('SECRET_KEY')

# You can add the config to the app or to the ext
app.config['AUTH0_CLIENT_ID'] = os.getenv('AUTH0_CLIENT_ID')
app.config['AUTH0_CLIENT_SECRET'] = os.getenv('AUTH0_CLIENT_SECRET')

# Initialize the extension
auth = AuthorizationCodeFlow(
    app=app,  # or use auth.init_app() later
    scope='profile',
    base_url=os.getenv('AUTH0_BASE_URL'),  # The base url of your SSO
    # All your instances need to be able to access this path,
    # or use another backend like Redis
    cache=FileSystemCache('/tmp/flask_auth0_cache'))
コード例 #3
0
ファイル: app.py プロジェクト: Kiku-Reise/forget
        csp += "connect-src 'self' https://sentry.io/;"
    else:
        csp += "script-src 'self' 'unsafe-eval';"
        csp += "connect-src 'self';"

    if 'CSP_REPORT_URI' in app.config:
        csp += "report-uri " + app.config.get('CSP_REPORT_URI')

    if app.config.get('HTTPS'):
        resp.headers.set('strict-transport-security',
                         'max-age={}'.format(60 * 60 * 24 * 365))
        csp += "; upgrade-insecure-requests"

    resp.headers.set('Content-Security-Policy', csp)
    resp.headers.set('referrer-policy', 'no-referrer')
    resp.headers.set('x-content-type-options', 'nosniff')
    resp.headers.set('x-frame-options', 'DENY')
    resp.headers.set('x-xss-protection', '1')

    return resp


mimetypes.add_type('image/webp', '.webp')

libforget.brotli.brotli(app)

imgproxy = (libforget.img_proxy.ImgProxyCache(
    redis_uri=app.config.get('REDIS_URI')))

app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)
コード例 #4
0
ファイル: app.py プロジェクト: Nexite/discord0
    else:
        out = '''An unhandled error occurred linking your accounts.
Please contact a staff member so we can resolve the issue'''
    session.clear()
    return out


def async_update(data):
    webhook = DiscordWebhook(
        url=webhookurl,
        content=
        f"a~update <@{data['response']['body']['user_metadata']['discord_id']}>"
    )
    response = webhook.execute()
    while not response.ok:
        if response.status_code == 429:
            sleep(1)
            response = webhook.execute()
        else:
            print(response)


@app.route('/update_hook', methods=['POST'])
def update_hook():
    data = request.json
    Thread(target=async_update, args=tuple([data])).start()
    return make_response("OK", 200)


app = ProxyFix(app, x_for=1, x_host=1)
コード例 #5
0
ファイル: __init__.py プロジェクト: saneshdealwis/backend
def create_app(test_config=None):
    app = Flask(__name__)

    app.config.from_mapping(
        SECRET_KEY='c5282ad3ea38420ab8ac0326a48d3a8c',
        SQLALCHEMY_DATABASE_URI=DATA_SOURCE,
        SQLALCHEMY_TRACK_MODIFICATIONS=False,
        SECURITY_TRACKABLE=True,
        SECURITY_PASSWORD_SALT='bf9797d59d094abb92fdca167494a7ee',
        SECURITY_UNAUTHORIZED_VIEW='/login',
        SECURITY_REGISTERABLE=False)

    CORS(app)

    ma.init_app(app)

    migrate = Migrate(app, Base)

    app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_host=1)

    from api.users.models import User, Role

    user_datastore = SQLAlchemySessionUserDatastore(db_session, User, Role)

    security.init_app(app, datastore=user_datastore, register_blueprint=False)

    # @app.before_request
    # def before_request_func():
    #     if not current_user.is_authenticated:
    #         return 'not loged in'

    def register_api(view, endpoint, url, pk='id', pk_type='int'):
        view_func = view.as_view(endpoint)
        app.add_url_rule(url,
                         defaults={pk: None},
                         view_func=view_func,
                         methods=[
                             'GET',
                         ])
        app.add_url_rule(url, view_func=view_func, methods=[
            'POST',
        ])
        app.add_url_rule('%s<%s:%s>' % (url, pk_type, pk),
                         view_func=view_func,
                         methods=['GET', 'PUT', 'DELETE'])

    from api.items import ItemsAPI
    from api.distributors import DistributorsAPI
    from api.clients import ClientsAPI
    from api.payments import PaymentsAPI
    from api.bill import BillsAPI

    register_api(ItemsAPI, 'items_api', '/items/', pk='item_code')
    register_api(DistributorsAPI, 'distributor_api', '/distributors/', pk='id')
    register_api(ClientsAPI, 'clients_api', '/clients/', pk='id')
    register_api(PaymentsAPI, 'payments_api', '/payments/', pk='id')
    register_api(BillsAPI, 'bills_api', '/bills/', pk='id')

    from api.users import users_bp

    app.register_blueprint(users_bp, url_prefix='/users')

    @app.teardown_appcontext
    def shutdown_session(exception=None):
        from api.database import db_session
        db_session.remove()

    return app
コード例 #6
0
ファイル: run.py プロジェクト: jin-hao-chen/filegoback
def main():
    app.wsgi_app = ProxyFix(app.wsgi_app)
    app.run()
コード例 #7
0
# -*- coding: utf-8 -*-
import cv2
import numpy as np
from flask import Flask, render_template, request, redirect, url_for, send_file
from werkzeug.utils import secure_filename
import hashlib
import uuid
import threading
import time
from queue import Queue, Empty
from werkzeug.middleware.proxy_fix import ProxyFix

app = Flask(__name__)
# App is behind one proxy that sets the -For and -Host headers.
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_host=1)
requests_queue = Queue()
BATCH_SIZE = 1
CHECK_INTERVAL = 0.1
net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
classes = []
with open("coco.names", "r") as f:
    classes = [line.strip() for line in f.readlines()]
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]


# request handling
def handle_requests_by_batch():
    try:
        while True:
            requests_batch = []
コード例 #8
0
ファイル: __init__.py プロジェクト: modulexcite/CTFd
def create_app(config='CTFd.config.Config'):
    app = CTFdFlask(__name__)
    with app.app_context():
        app.config.from_object(config)

        theme_loader = ThemeLoader(os.path.join(app.root_path, 'themes'),
                                   followlinks=True)
        app.jinja_loader = theme_loader

        from CTFd.models import db, Teams, Solves, Challenges, Fails, Flags, Tags, Files, Tracking  # noqa: F401

        url = create_database()

        # This allows any changes to the SQLALCHEMY_DATABASE_URI to get pushed back in
        # This is mostly so we can force MySQL's charset
        app.config['SQLALCHEMY_DATABASE_URI'] = str(url)

        # Register database
        db.init_app(app)

        # Register Flask-Migrate
        migrations.init_app(app, db)

        # Alembic sqlite support is lacking so we should just create_all anyway
        if url.drivername.startswith('sqlite'):
            db.create_all()
            stamp()
        else:
            # This creates tables instead of db.create_all()
            # Allows migrations to happen properly
            upgrade()

        from CTFd.models import ma

        ma.init_app(app)

        app.db = db
        app.VERSION = __version__

        from CTFd.cache import cache

        cache.init_app(app)
        app.cache = cache

        reverse_proxy = app.config.get('REVERSE_PROXY')
        if reverse_proxy:
            if ',' in reverse_proxy:
                proxyfix_args = [int(i) for i in reverse_proxy.split(',')]
                app.wsgi_app = ProxyFix(app.wsgi_app, None, *proxyfix_args)
            else:
                app.wsgi_app = ProxyFix(app.wsgi_app,
                                        num_proxies=None,
                                        x_for=1,
                                        x_proto=1,
                                        x_host=1,
                                        x_port=1,
                                        x_prefix=1)

        version = utils.get_config('ctf_version')

        # Upgrading from an older version of CTFd
        if version and (StrictVersion(version) < StrictVersion(__version__)):
            if confirm_upgrade():
                run_upgrade()
            else:
                exit()

        if not version:
            utils.set_config('ctf_version', __version__)

        if not utils.get_config('ctf_theme'):
            utils.set_config('ctf_theme', 'core')

        update_check(force=True)

        init_request_processors(app)
        init_template_filters(app)
        init_template_globals(app)

        # Importing here allows tests to use sensible names (e.g. api instead of api_bp)
        from CTFd.views import views
        from CTFd.teams import teams
        from CTFd.users import users
        from CTFd.challenges import challenges
        from CTFd.scoreboard import scoreboard
        from CTFd.auth import auth
        from CTFd.admin import admin
        from CTFd.api import api
        from CTFd.events import events
        from CTFd.errors import page_not_found, forbidden, general_error, gateway_error

        app.register_blueprint(views)
        app.register_blueprint(teams)
        app.register_blueprint(users)
        app.register_blueprint(challenges)
        app.register_blueprint(scoreboard)
        app.register_blueprint(auth)
        app.register_blueprint(api)
        app.register_blueprint(events)

        app.register_blueprint(admin)

        app.register_error_handler(404, page_not_found)
        app.register_error_handler(403, forbidden)
        app.register_error_handler(500, general_error)
        app.register_error_handler(502, gateway_error)

        init_logs(app)
        init_events(app)
        init_plugins(app)

        return app
コード例 #9
0
ファイル: pages.py プロジェクト: alethiophile/openakun
if ('secret_key' not in config['openakun']
        or len(config['openakun']['secret_key']) == 0):  # noqa: E129
    raise ConfigError("Secret key not provided")

app.config['SECRET_KEY'] = config['openakun']['secret_key']
login_mgr.init_app(app)
login_mgr.login_view = 'login'
socketio = SocketIO(app,
                    logger=app.config['DEBUG'],
                    engineio_logger=app.config['DEBUG'])

# to make the proxy_fix apply to the socketio as well, this has to be done
# after the socketio is constructed
if config.getboolean('openakun', 'proxy_fix', fallback=False):
    print("adding ProxyFix")
    app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1)

app.jinja_env.add_extension('jinja2.ext.do')

# Import needs to be here, since it imports variables from pages.py itself.
# Importing alone has all the side effects needed.
from . import realtime  # noqa


def jinja_global(f):
    app.jinja_env.globals[f.__name__] = f
    return f


app.jinja_env.globals['models'] = models
コード例 #10
0
from app import application
from werkzeug.middleware.proxy_fix import ProxyFix
import google.cloud.logging

application.wsgi_app = ProxyFix(application.wsgi_app, x_proto=1)

client = google.cloud.logging.Client()
client.setup_logging()

if __name__ == "__main__":
    application.run()
コード例 #11
0
    def __init__(
        self,
        name,
        service,
        favicon_url=None,
        template_404=None,
        template_500=None,
        *args,
        **kwargs
    ):
        super().__init__(name, *args, **kwargs)

        self.service = service

        self.config["SECRET_KEY"] = os.getenv("SECRET_KEY", "base_secret")

        self.url_map.strict_slashes = False
        self.url_map.converters["regex"] = RegexConverter

        if self.debug:
            self.wsgi_app = DebuggedApplication(self.wsgi_app)

        self.wsgi_app = ProxyFix(self.wsgi_app)

        self.before_request(clear_trailing_slash)

        self.before_request(
            prepare_redirects(
                path=os.path.join(self.root_path, "..", "redirects.yaml")
            )
        )
        self.before_request(
            prepare_redirects(
                path=os.path.join(
                    self.root_path, "..", "permanent-redirects.yaml"
                ),
                permanent=True,
            )
        )
        self.before_request(
            prepare_deleted(
                path=os.path.join(self.root_path, "..", "deleted.yaml")
            )
        )

        self.context_processor(base_context)

        talisker.flask.register(self)
        talisker.logs.set_global_extra({"service": self.service})

        # Default error handlers
        if template_404:

            @self.errorhandler(404)
            def not_found_error(error):
                return flask.render_template(template_404), 404

        if template_500:

            @self.errorhandler(500)
            def internal_error(error):
                return flask.render_template(template_500), 500

        # Default routes
        if favicon_url:

            @self.route("/favicon.ico")
            def favicon():
                return flask.redirect(favicon_url)

        robots_path = os.path.join(self.root_path, "..", "robots.txt")
        humans_path = os.path.join(self.root_path, "..", "humans.txt")

        if os.path.isfile(robots_path):

            @self.route("/robots.txt")
            def robots():
                return flask.send_file(robots_path)

        if os.path.isfile(humans_path):

            @self.route("/humans.txt")
            def humans():
                return flask.send_file(humans_path)
コード例 #12
0
ファイル: app.py プロジェクト: dthonon/GeoNature
def create_app(with_external_mods=True):
    app = Flask(__name__.split('.')[0], static_folder="../static")

    app.config.update(config)
    api_uri = urlsplit(app.config['API_ENDPOINT'])
    app.config['APPLICATION_ROOT'] = api_uri.path
    app.config['PREFERRED_URL_SCHEME'] = api_uri.scheme
    if 'SCRIPT_NAME' not in os.environ:
        os.environ['SCRIPT_NAME'] = app.config['APPLICATION_ROOT'].rstrip('/')
    app.config['TEMPLATES_AUTO_RELOAD'] = True
    # disable cache for downloaded files (PDF file stat for ex)
    app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0

    if len(app.config['SECRET_KEY']) < 20:
        raise Exception("The SECRET_KEY config option must have a length "
                        "greater or equals to 20 characters.")

    # set from headers HTTP_HOST, SERVER_NAME, and SERVER_PORT
    app.wsgi_app = ProxyFix(app.wsgi_app, x_host=1)

    app.json_encoder = MyJSONEncoder

    # set logging config
    config_loggers(app.config)

    db.init_app(app)
    migrate.init_app(app,
                     DB,
                     directory=BACKEND_DIR / 'geonature' / 'migrations')
    MA.init_app(app)
    CORS(app, supports_credentials=True)

    # Emails configuration
    if app.config["MAIL_CONFIG"]:
        conf = app.config.copy()
        conf.update(app.config["MAIL_CONFIG"])
        app.config = conf
        MAIL.init_app(app)

    # Pass parameters to the usershub authenfication sub-module, DONT CHANGE THIS
    app.config["DB"] = DB
    # Pass parameters to the submodules
    app.config["MA"] = MA

    # For deleting files on "delete" media
    @before_models_committed.connect_via(app)
    def on_before_models_committed(sender, changes):
        for obj, change in changes:
            if change == "delete" and hasattr(obj, "__before_commit_delete__"):
                obj.__before_commit_delete__()

    # setting g.current_user on each request
    @app.before_request
    def load_current_user():
        try:
            g.current_user = user_from_token(request.cookies['token']).role
        except (KeyError, UnreadableAccessRightsError,
                AccessRightsExpiredError):
            g.current_user = None

    admin.init_app(app)

    # Pass the ID_APP to the submodule to avoid token conflict between app on the same server
    with app.app_context():
        try:
            gn_app = Application.query.filter_by(
                code_application=config['CODE_APPLICATION']).one()
        except (ProgrammingError, NoResultFound):
            logging.warning(
                "Warning: unable to find GeoNature application, database not yet initialized?"
            )
        else:
            app.config["ID_APP"] = app.config[
                "ID_APPLICATION_GEONATURE"] = gn_app.id_application

    for blueprint_path, url_prefix in [
        ('pypnusershub.routes:routes', '/auth'),
        ('pypn_habref_api.routes:routes', '/habref'),
        ('pypnusershub.routes_register:bp', '/pypn/register'),
        ('pypnnomenclature.routes:routes', '/nomenclatures'),
        ('geonature.core.gn_commons.routes:routes', '/gn_commons'),
        ('geonature.core.gn_permissions.routes:routes', '/permissions'),
        ('geonature.core.gn_permissions.backoffice.views:routes',
         '/permissions_backoffice'),
        ('geonature.core.routes:routes', '/'),
        ('geonature.core.users.routes:routes', '/users'),
        ('geonature.core.gn_synthese.routes:routes', '/synthese'),
        ('geonature.core.gn_meta.routes:routes', '/meta'),
        ('geonature.core.ref_geo.routes:routes', '/geo'),
        ('geonature.core.auth.routes:routes', '/gn_auth'),
        ('geonature.core.gn_monitoring.routes:routes', '/gn_monitoring'),
        ('geonature.core.gn_profiles.routes:routes', '/gn_profiles'),
    ]:
        module_name, blueprint_name = blueprint_path.split(':')
        blueprint = getattr(import_module(module_name), blueprint_name)
        app.register_blueprint(blueprint, url_prefix=url_prefix)

    with app.app_context():
        # register errors handlers
        import geonature.core.errors

        # Loading third-party modules
        if with_external_mods:
            try:
                for module_object, module_config, module_blueprint in import_backend_enabled_modules(
                ):
                    app.config[module_config['MODULE_CODE']] = module_config
                    app.register_blueprint(
                        module_blueprint,
                        url_prefix=module_config['MODULE_URL'])
            except ProgrammingError as sqla_error:
                if isinstance(sqla_error.orig, UndefinedTable):
                    logging.warning(
                        "Warning: database not yet initialized, skipping loading of external modules"
                    )
                else:
                    raise

    return app
コード例 #13
0
def create_app(config="CTFd.config.Config"):
    app = CTFdFlask(__name__)
    with app.app_context():
        app.config.from_object(config)

        app.theme_loader = ThemeLoader(
            os.path.join(app.root_path, "themes"), followlinks=True
        )
        # Weird nested solution for accessing plugin templates
        app.plugin_loader = jinja2.PrefixLoader(
            {
                "plugins": jinja2.FileSystemLoader(
                    searchpath=os.path.join(app.root_path, "plugins"), followlinks=True
                )
            }
        )
        # Load from themes first but fallback to loading from the plugin folder
        app.jinja_loader = jinja2.ChoiceLoader([app.theme_loader, app.plugin_loader])

        from CTFd.models import (  # noqa: F401
            db,
            Teams,
            Solves,
            Challenges,
            Fails,
            Flags,
            Tags,
            Files,
            Tracking,
        )

        url = create_database()

        # This allows any changes to the SQLALCHEMY_DATABASE_URI to get pushed back in
        # This is mostly so we can force MySQL's charset
        app.config["SQLALCHEMY_DATABASE_URI"] = str(url)

        # Register database
        db.init_app(app)

        # Register Flask-Migrate
        migrations.init_app(app, db)

        # Alembic sqlite support is lacking so we should just create_all anyway
        if url.drivername.startswith("sqlite"):
            # Enable foreign keys for SQLite. This must be before the
            # db.create_all call because tests use the in-memory SQLite
            # database (each connection, including db creation, is a new db).
            # https://docs.sqlalchemy.org/en/13/dialects/sqlite.html#foreign-key-support
            from sqlalchemy.engine import Engine
            from sqlalchemy import event

            @event.listens_for(Engine, "connect")
            def set_sqlite_pragma(dbapi_connection, connection_record):
                cursor = dbapi_connection.cursor()
                cursor.execute("PRAGMA foreign_keys=ON")
                cursor.close()

            db.create_all()
            stamp_latest_revision()
        else:
            # This creates tables instead of db.create_all()
            # Allows migrations to happen properly
            upgrade()

        from CTFd.models import ma

        ma.init_app(app)

        app.db = db
        app.VERSION = __version__
        app.CHANNEL = __channel__

        from CTFd.cache import cache

        cache.init_app(app)
        app.cache = cache

        reverse_proxy = app.config.get("REVERSE_PROXY")
        if reverse_proxy:
            if type(reverse_proxy) is str and "," in reverse_proxy:
                proxyfix_args = [int(i) for i in reverse_proxy.split(",")]
                app.wsgi_app = ProxyFix(app.wsgi_app, *proxyfix_args)
            else:
                app.wsgi_app = ProxyFix(
                    app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_port=1, x_prefix=1
                )

        version = utils.get_config("ctf_version")

        # Upgrading from an older version of CTFd
        if version and (StrictVersion(version) < StrictVersion(__version__)):
            if confirm_upgrade():
                run_upgrade()
            else:
                exit()

        if not version:
            utils.set_config("ctf_version", __version__)

        if not utils.get_config("ctf_theme"):
            utils.set_config("ctf_theme", "core")

        update_check(force=True)

        init_request_processors(app)
        init_template_filters(app)
        init_template_globals(app)

        # Importing here allows tests to use sensible names (e.g. api instead of api_bp)
        from CTFd.views import views
        from CTFd.teams import teams
        from CTFd.users import users
        from CTFd.challenges import challenges
        from CTFd.scoreboard import scoreboard
        from CTFd.auth import auth
        from CTFd.admin import admin
        from CTFd.api import api
        from CTFd.events import events
        from CTFd.errors import page_not_found, forbidden, general_error, gateway_error

        app.register_blueprint(views)
        app.register_blueprint(teams)
        app.register_blueprint(users)
        app.register_blueprint(challenges)
        app.register_blueprint(scoreboard)
        app.register_blueprint(auth)
        app.register_blueprint(api)
        app.register_blueprint(events)

        app.register_blueprint(admin)

        app.register_error_handler(404, page_not_found)
        app.register_error_handler(403, forbidden)
        app.register_error_handler(500, general_error)
        app.register_error_handler(502, gateway_error)

        init_logs(app)
        init_events(app)
        init_plugins(app)

        return app
コード例 #14
0
        return callback


app = Flask(__name__)

if os.environ.get('ENABLE_CORS', config.ENABLE_CORS):
    cors = CORS(app,
                resources={
                    r"*": {
                        "origins":
                        os.environ.get('CORS_ORIGINS', config.CORS_ORIGINS)
                    }
                })

app.wsgi_app = WSGIRawBody(ProxyFix(app.wsgi_app))

app.debug = config.DEBUG
app.secret_key = config.FLASK_SESSION_SECRET_KEY

app.jinja_env.filters['status_class'] = status_class
app.jinja_env.filters['friendly_time'] = friendly_time
app.jinja_env.filters['friendly_size'] = friendly_size
app.jinja_env.filters['to_qs'] = to_qs
app.jinja_env.filters['approximate_time'] = approximate_time
app.jinja_env.filters['exact_time'] = exact_time
app.jinja_env.filters['short_date'] = short_date

from .views import views
from .api import api
コード例 #15
0
ファイル: app.py プロジェクト: zuiwanting/flink-ai-extended
def create_app(config=None, session=None, testing=False, app_name="Airflow"):
    global app, appbuilder
    app = Flask(__name__)
    if conf.getboolean('webserver', 'ENABLE_PROXY_FIX'):
        app.wsgi_app = ProxyFix(app.wsgi_app,
                                num_proxies=conf.get("webserver",
                                                     "PROXY_FIX_NUM_PROXIES",
                                                     fallback=None),
                                x_for=conf.getint("webserver",
                                                  "PROXY_FIX_X_FOR",
                                                  fallback=1),
                                x_proto=conf.getint("webserver",
                                                    "PROXY_FIX_X_PROTO",
                                                    fallback=1),
                                x_host=conf.getint("webserver",
                                                   "PROXY_FIX_X_HOST",
                                                   fallback=1),
                                x_port=conf.getint("webserver",
                                                   "PROXY_FIX_X_PORT",
                                                   fallback=1),
                                x_prefix=conf.getint("webserver",
                                                     "PROXY_FIX_X_PREFIX",
                                                     fallback=1))
    app.secret_key = conf.get('webserver', 'SECRET_KEY')

    session_lifetime_days = conf.getint('webserver',
                                        'SESSION_LIFETIME_DAYS',
                                        fallback=30)
    app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(
        days=session_lifetime_days)

    app.config.from_pyfile(settings.WEBSERVER_CONFIG, silent=True)
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['APP_NAME'] = app_name
    app.config['TESTING'] = testing

    app.config['SESSION_COOKIE_HTTPONLY'] = True
    app.config['SESSION_COOKIE_SECURE'] = conf.getboolean(
        'webserver', 'COOKIE_SECURE')
    app.config['SESSION_COOKIE_SAMESITE'] = conf.get('webserver',
                                                     'COOKIE_SAMESITE')

    if config:
        app.config.from_mapping(config)

    csrf.init_app(app)

    db = SQLA(app)

    from airflow import api
    api.load_auth()
    api.API_AUTH.api_auth.init_app(app)

    # flake8: noqa: F841
    cache = Cache(app=app,
                  config={
                      'CACHE_TYPE': 'filesystem',
                      'CACHE_DIR': '/tmp'
                  })

    from airflow.www_rbac.blueprints import routes
    app.register_blueprint(routes)

    configure_logging()
    configure_manifest_files(app)

    with app.app_context():
        from airflow.www_rbac.security import AirflowSecurityManager
        security_manager_class = app.config.get('SECURITY_MANAGER_CLASS') or \
            AirflowSecurityManager

        if not issubclass(security_manager_class, AirflowSecurityManager):
            raise Exception(
                """Your CUSTOM_SECURITY_MANAGER must now extend AirflowSecurityManager,
                 not FAB's security manager.""")

        appbuilder = AppBuilder(app,
                                db.session if not session else session,
                                security_manager_class=security_manager_class,
                                base_template='airflow/master.html',
                                update_perms=conf.getboolean(
                                    'webserver', 'UPDATE_FAB_PERMS'))

        def init_views(appbuilder):
            from airflow.www_rbac import views
            # Remove the session from scoped_session registry to avoid
            # reusing a session with a disconnected connection
            appbuilder.session.remove()
            appbuilder.add_view_no_menu(views.Airflow())
            appbuilder.add_view_no_menu(views.DagModelView())
            appbuilder.add_view(views.DagRunModelView,
                                "DAG Runs",
                                category="Browse",
                                category_icon="fa-globe")
            appbuilder.add_view(views.JobModelView, "Jobs", category="Browse")
            appbuilder.add_view(views.LogModelView, "Logs", category="Browse")
            appbuilder.add_view(views.SlaMissModelView,
                                "SLA Misses",
                                category="Browse")
            appbuilder.add_view(views.TaskInstanceModelView,
                                "Task Instances",
                                category="Browse")
            appbuilder.add_view(views.TaskExecutionModelView,
                                "Task Executions",
                                category="Browse")
            appbuilder.add_view(views.EventModelView,
                                "Events",
                                category="Browse")
            appbuilder.add_view(views.ConfigurationView,
                                "Configurations",
                                category="Admin",
                                category_icon="fa-user")
            appbuilder.add_view(views.ConnectionModelView,
                                "Connections",
                                category="Admin")
            appbuilder.add_view(views.PoolModelView, "Pools", category="Admin")
            appbuilder.add_view(views.VariableModelView,
                                "Variables",
                                category="Admin")
            appbuilder.add_view(views.XComModelView, "XComs", category="Admin")

            if "dev" in version.version:
                airflow_doc_site = "https://airflow.readthedocs.io/en/latest"
            else:
                airflow_doc_site = 'https://airflow.apache.org/docs/{}'.format(
                    version.version)

            appbuilder.add_link("Documentation",
                                href=airflow_doc_site,
                                category="Docs",
                                category_icon="fa-cube")
            appbuilder.add_link("GitHub",
                                href='https://github.com/apache/airflow',
                                category="Docs")
            appbuilder.add_view(views.VersionView,
                                'Version',
                                category='About',
                                category_icon='fa-th')

            def integrate_plugins():
                """Integrate plugins to the context"""
                from airflow.plugins_manager import (
                    flask_appbuilder_views, flask_appbuilder_menu_links)

                for v in flask_appbuilder_views:
                    log.debug("Adding view %s", v["name"])
                    appbuilder.add_view(v["view"],
                                        v["name"],
                                        category=v["category"])
                for ml in sorted(flask_appbuilder_menu_links,
                                 key=lambda x: x["name"]):
                    log.debug("Adding menu link %s", ml["name"])
                    appbuilder.add_link(ml["name"],
                                        href=ml["href"],
                                        category=ml["category"],
                                        category_icon=ml["category_icon"])

            integrate_plugins()
            # Garbage collect old permissions/views after they have been modified.
            # Otherwise, when the name of a view or menu is changed, the framework
            # will add the new Views and Menus names to the backend, but will not
            # delete the old ones.

        def init_plugin_blueprints(app):
            from airflow.plugins_manager import flask_blueprints

            for bp in flask_blueprints:
                log.debug("Adding blueprint %s:%s", bp["name"],
                          bp["blueprint"].import_name)
                app.register_blueprint(bp["blueprint"])

        init_views(appbuilder)
        init_plugin_blueprints(app)

        if conf.getboolean('webserver', 'UPDATE_FAB_PERMS'):
            security_manager = appbuilder.sm
            security_manager.sync_roles()

        from airflow.www_rbac.api.experimental import endpoints as e
        # required for testing purposes otherwise the module retains
        # a link to the default_auth
        if app.config['TESTING']:
            if six.PY2:
                reload(e)  # noqa
            else:
                import importlib
                importlib.reload(e)

        app.register_blueprint(e.api_experimental,
                               url_prefix='/api/experimental')

        server_timezone = conf.get('core', 'default_timezone')
        if server_timezone == "system":
            server_timezone = pendulum.local_timezone().name
        elif server_timezone == "utc":
            server_timezone = "UTC"

        default_ui_timezone = conf.get('webserver', 'default_ui_timezone')
        if default_ui_timezone == "system":
            default_ui_timezone = pendulum.local_timezone().name
        elif default_ui_timezone == "utc":
            default_ui_timezone = "UTC"
        if not default_ui_timezone:
            default_ui_timezone = server_timezone

        @app.context_processor
        def jinja_globals():  # pylint: disable=unused-variable

            globals = {
                'server_timezone':
                server_timezone,
                'default_ui_timezone':
                default_ui_timezone,
                'hostname':
                socket.getfqdn() if conf.getboolean(
                    'webserver', 'EXPOSE_HOSTNAME', fallback=True) else
                'redact',
                'navbar_color':
                conf.get('webserver', 'NAVBAR_COLOR'),
                'log_fetch_delay_sec':
                conf.getint('webserver', 'log_fetch_delay_sec', fallback=2),
                'log_auto_tailing_offset':
                conf.getint('webserver',
                            'log_auto_tailing_offset',
                            fallback=30),
                'log_animation_speed':
                conf.getint('webserver', 'log_animation_speed', fallback=1000)
            }

            if 'analytics_tool' in conf.getsection('webserver'):
                globals.update({
                    'analytics_tool':
                    conf.get('webserver', 'ANALYTICS_TOOL'),
                    'analytics_id':
                    conf.get('webserver', 'ANALYTICS_ID')
                })

            return globals

        @app.teardown_appcontext
        def shutdown_session(exception=None):
            settings.Session.remove()

        @app.before_request
        def before_request():
            _force_log_out_after = conf.getint('webserver',
                                               'FORCE_LOG_OUT_AFTER',
                                               fallback=0)
            if _force_log_out_after > 0:
                flask.session.permanent = True
                app.permanent_session_lifetime = datetime.timedelta(
                    minutes=_force_log_out_after)
                flask.session.modified = True
                flask.g.user = flask_login.current_user

        @app.after_request
        def apply_caching(response):
            _x_frame_enabled = conf.getboolean('webserver',
                                               'X_FRAME_ENABLED',
                                               fallback=True)
            if not _x_frame_enabled:
                response.headers["X-Frame-Options"] = "DENY"
            return response

        @app.before_request
        def make_session_permanent():
            flask_session.permanent = True

    return app, appbuilder
コード例 #16
0
        if not tags:
            tags = ["default"]

        operation_id = inflection.underscore(operation.operation_id)

        return '{}.{}_controller.{}'.format("api", tags[0], operation_id)


def send_static():
    return flask.send_file("static{}".format(flask.request.path))


app = connexion.FlaskApp(__name__, specification_dir='../schema')
app.app.json_encoder = encoder.JSONEncoder
app.app.wsgi_app = ProxyFix(app.app.wsgi_app, x_proto=1)

api_cors_config = {
    "origins": ["http://localhost:3000"],
    "methods": ["OPTIONS", "GET", "POST"],
    "allow_headers": ["Authorization", "Content-Type"]
}

CORS(app.app, supports_credentials=True, resources={r"/*": api_cors_config})
app.app.secret_key = 'super secret key'

# Add explicit rules for each file in the static directory
for f in [f for f in glob.glob("static/**/*.*", recursive=True)]:
    f = f[6:]
    app.app.add_url_rule(f, f, send_static)
コード例 #17
0
ファイル: __main__.py プロジェクト: dginovker/ruqqus
from sqlalchemy import *
from sqlalchemy.pool import QueuePool
import threading
import requests
import random
import redis
import gevent

from redis import BlockingConnectionPool

from werkzeug.middleware.proxy_fix import ProxyFix

_version = "2.35.59"

app = Flask(__name__, template_folder='./templates', static_folder='./static')
app.wsgi_app = ProxyFix(app.wsgi_app, num_proxies=3)
app.url_map.strict_slashes = False

app.config["SITE_NAME"] = environ.get("SITE_NAME", "ruqqus").lstrip().rstrip()

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['DATABASE_URL'] = environ.get("DATABASE_CONNECTION_POOL_URL",
                                         environ.get("DATABASE_URL"))

app.config['SQLALCHEMY_READ_URIS'] = [
    environ.get("DATABASE_CONNECTION_READ_01_URL"),
    environ.get("DATABASE_CONNECTION_READ_02_URL"),
    environ.get("DATABASE_CONNECTION_READ_03_URL")
]

app.config['SECRET_KEY'] = environ.get('MASTER_KEY')
コード例 #18
0
def create_app(config=None, session=None, testing=False, app_name="Airflow"):
    global app, appbuilder
    app = Flask(__name__)
    if conf.getboolean('webserver', 'ENABLE_PROXY_FIX'):
        app.wsgi_app = ProxyFix(app.wsgi_app,
                                num_proxies=None,
                                x_for=1,
                                x_proto=1,
                                x_host=1,
                                x_port=1,
                                x_prefix=1)
    app.secret_key = conf.get('webserver', 'SECRET_KEY')

    app.config.from_pyfile(settings.WEBSERVER_CONFIG, silent=True)
    app.config['APP_NAME'] = app_name
    app.config['TESTING'] = testing
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    app.config['SESSION_COOKIE_HTTPONLY'] = True
    app.config['SESSION_COOKIE_SECURE'] = conf.getboolean(
        'webserver', 'COOKIE_SECURE')
    app.config['SESSION_COOKIE_SAMESITE'] = conf.get('webserver',
                                                     'COOKIE_SAMESITE')

    if config:
        app.config.from_mapping(config)

    # Configure the JSON encoder used by `|tojson` filter from Flask
    app.json_encoder = AirflowJsonEncoder

    csrf.init_app(app)

    db = SQLA(app)

    from airflow import api
    api.load_auth()
    api.API_AUTH.api_auth.init_app(app)

    Cache(app=app, config={'CACHE_TYPE': 'filesystem', 'CACHE_DIR': '/tmp'})

    from airflow.www.blueprints import routes
    app.register_blueprint(routes)

    configure_logging()
    configure_manifest_files(app)

    with app.app_context():
        from airflow.www.security import AirflowSecurityManager
        security_manager_class = app.config.get('SECURITY_MANAGER_CLASS') or \
            AirflowSecurityManager

        if not issubclass(security_manager_class, AirflowSecurityManager):
            raise Exception(
                """Your CUSTOM_SECURITY_MANAGER must now extend AirflowSecurityManager,
                 not FAB's security manager.""")

        appbuilder = AppBuilder(app,
                                db.session if not session else session,
                                security_manager_class=security_manager_class,
                                base_template='appbuilder/baselayout.html',
                                update_perms=conf.getboolean(
                                    'webserver', 'UPDATE_FAB_PERMS'))

        def init_views(appbuilder):
            from airflow.www import views
            # Remove the session from scoped_session registry to avoid
            # reusing a session with a disconnected connection
            appbuilder.session.remove()
            appbuilder.add_view_no_menu(views.Airflow())
            appbuilder.add_view_no_menu(views.DagModelView())
            appbuilder.add_view_no_menu(views.ConfigurationView())
            appbuilder.add_view_no_menu(views.VersionView())
            appbuilder.add_view(views.DagRunModelView,
                                "DAG Runs",
                                category="Browse",
                                category_icon="fa-globe")
            appbuilder.add_view(views.JobModelView, "Jobs", category="Browse")
            appbuilder.add_view(views.LogModelView, "Logs", category="Browse")
            appbuilder.add_view(views.SlaMissModelView,
                                "SLA Misses",
                                category="Browse")
            appbuilder.add_view(views.TaskInstanceModelView,
                                "Task Instances",
                                category="Browse")
            appbuilder.add_link("Configurations",
                                href='/configuration',
                                category="Admin",
                                category_icon="fa-user")
            appbuilder.add_view(views.ConnectionModelView,
                                "Connections",
                                category="Admin")
            appbuilder.add_view(views.PoolModelView, "Pools", category="Admin")
            appbuilder.add_view(views.VariableModelView,
                                "Variables",
                                category="Admin")
            appbuilder.add_view(views.XComModelView, "XComs", category="Admin")
            appbuilder.add_link("Documentation",
                                href='https://airflow.apache.org/',
                                category="Docs",
                                category_icon="fa-cube")
            appbuilder.add_link("GitHub",
                                href='https://github.com/apache/airflow',
                                category="Docs")
            appbuilder.add_link('Version',
                                href='/version',
                                category='About',
                                category_icon='fa-th')

            def integrate_plugins():
                """Integrate plugins to the context"""
                from airflow.plugins_manager import (
                    flask_appbuilder_views, flask_appbuilder_menu_links)

                for v in flask_appbuilder_views:
                    log.debug("Adding view %s", v["name"])
                    appbuilder.add_view(v["view"],
                                        v["name"],
                                        category=v["category"])
                for ml in sorted(flask_appbuilder_menu_links,
                                 key=lambda x: x["name"]):
                    log.debug("Adding menu link %s", ml["name"])
                    appbuilder.add_link(ml["name"],
                                        href=ml["href"],
                                        category=ml["category"],
                                        category_icon=ml["category_icon"])

            integrate_plugins()
            # Garbage collect old permissions/views after they have been modified.
            # Otherwise, when the name of a view or menu is changed, the framework
            # will add the new Views and Menus names to the backend, but will not
            # delete the old ones.

        def init_plugin_blueprints(app):
            from airflow.plugins_manager import flask_blueprints

            for bp in flask_blueprints:
                log.debug("Adding blueprint %s:%s", bp["name"],
                          bp["blueprint"].import_name)
                app.register_blueprint(bp["blueprint"])

        init_views(appbuilder)
        init_plugin_blueprints(app)

        if conf.getboolean('webserver', 'UPDATE_FAB_PERMS'):
            security_manager = appbuilder.sm
            security_manager.sync_roles()

        from airflow.www.api.experimental import endpoints as e
        # required for testing purposes otherwise the module retains
        # a link to the default_auth
        if app.config['TESTING']:
            import importlib
            importlib.reload(e)

        app.register_blueprint(e.api_experimental,
                               url_prefix='/api/experimental')

        @app.context_processor
        def jinja_globals():  # pylint: disable=unused-variable

            globals = {
                'hostname': socket.getfqdn(),
                'navbar_color': conf.get('webserver', 'NAVBAR_COLOR'),
            }

            if 'analytics_tool' in conf.getsection('webserver'):
                globals.update({
                    'analytics_tool':
                    conf.get('webserver', 'ANALYTICS_TOOL'),
                    'analytics_id':
                    conf.get('webserver', 'ANALYTICS_ID')
                })

            return globals

        @app.teardown_appcontext
        def shutdown_session(exception=None):  # pylint: disable=unused-variable
            settings.Session.remove()

    return app, appbuilder
コード例 #19
0
def add_werkzeug_proxy_fix(app: Flask):
    from werkzeug.middleware.proxy_fix import ProxyFix

    app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)
    app.logger.info("Add ProxyFix to serve swagger.json over https.")
コード例 #20
0
def create_app(config=None):
    from . import models, routes, services
    from .assets import assets
    app = Flask(__name__)

    # Read log level from environment variable
    log_level_name = os.environ.get('PDNS_ADMIN_LOG_LEVEL', 'WARNING')
    log_level = logging.getLevelName(log_level_name.upper())
    # Setting logger
    logging.basicConfig(
       level=log_level,
        format=
        "[%(asctime)s] [%(filename)s:%(lineno)d] %(levelname)s - %(message)s")

    # If we use Docker + Gunicorn, adjust the
    # log handler
    if "GUNICORN_LOGLEVEL" in os.environ:
        gunicorn_logger = logging.getLogger("gunicorn.error")
        app.logger.handlers = gunicorn_logger.handlers
        app.logger.setLevel(gunicorn_logger.level)

    # Proxy
    app.wsgi_app = ProxyFix(app.wsgi_app)

    # CSRF protection
    csrf = SeaSurf(app)
    csrf.exempt(routes.index.dyndns_checkip)
    csrf.exempt(routes.index.dyndns_update)
    csrf.exempt(routes.index.saml_authorized)
    csrf.exempt(routes.api.api_login_create_zone)
    csrf.exempt(routes.api.api_login_delete_zone)
    csrf.exempt(routes.api.api_generate_apikey)
    csrf.exempt(routes.api.api_delete_apikey)
    csrf.exempt(routes.api.api_update_apikey)
    csrf.exempt(routes.api.api_zone_subpath_forward)
    csrf.exempt(routes.api.api_zone_forward)
    csrf.exempt(routes.api.api_create_zone)
    csrf.exempt(routes.api.api_create_account)
    csrf.exempt(routes.api.api_delete_account)
    csrf.exempt(routes.api.api_update_account)
    csrf.exempt(routes.api.api_create_user)
    csrf.exempt(routes.api.api_delete_user)
    csrf.exempt(routes.api.api_update_user)
    csrf.exempt(routes.api.api_list_account_users)
    csrf.exempt(routes.api.api_add_account_user)
    csrf.exempt(routes.api.api_remove_account_user)

    # Load config from env variables if using docker
    if os.path.exists(os.path.join(app.root_path, 'docker_config.py')):
        app.config.from_object('powerdnsadmin.docker_config')
    else:
        # Load default configuration
        app.config.from_object('powerdnsadmin.default_config')

    # Load config file from FLASK_CONF env variable
    if 'FLASK_CONF' in os.environ:
        app.config.from_envvar('FLASK_CONF')

    # Load app sepecified configuration
    if config is not None:
        if isinstance(config, dict):
            app.config.update(config)
        elif config.endswith('.py'):
            app.config.from_pyfile(config)

    # HSTS
    if app.config.get('HSTS_ENABLED'):
        from flask_sslify import SSLify
        _sslify = SSLify(app)  # lgtm [py/unused-local-variable]

    # Load Flask-Session
    if app.config.get('FILESYSTEM_SESSIONS_ENABLED'):
        app.config['SESSION_TYPE'] = 'filesystem'
        sess = Session()
        sess.init_app(app)

    # SMTP
    app.mail = Mail(app)

    # Load app's components
    assets.init_app(app)
    models.init_app(app)
    routes.init_app(app)
    services.init_app(app)

    # Register filters
    app.jinja_env.filters['display_record_name'] = utils.display_record_name
    app.jinja_env.filters['display_master_name'] = utils.display_master_name
    app.jinja_env.filters['display_second_to_time'] = utils.display_time
    app.jinja_env.filters[
        'email_to_gravatar_url'] = utils.email_to_gravatar_url
    app.jinja_env.filters[
        'display_setting_state'] = utils.display_setting_state
    app.jinja_env.filters['pretty_domain_name'] = utils.pretty_domain_name

    # Register context proccessors
    from .models.setting import Setting

    @app.context_processor
    def inject_sitename():
        setting = Setting().get('site_name')
        return dict(SITE_NAME=setting)

    @app.context_processor
    def inject_setting():
        setting = Setting()
        return dict(SETTING=setting)

    @app.context_processor
    def inject_mode():
        setting = app.config.get('OFFLINE_MODE', False)
        return dict(OFFLINE_MODE=setting)

    return app
コード例 #21
0
ファイル: application.py プロジェクト: khan786-dev/server
import os

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from werkzeug.middleware.proxy_fix import ProxyFix

# Application
app = Flask(__name__)

# Database
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://{}:{}@{}/{}".format(
    os.environ["MYSQL_USERNAME"], os.environ["MYSQL_PASSWORD"],
    os.environ["MYSQL_HOST"], os.environ["MYSQL_DATABASE"])
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)

# ProxyFix
app.wsgi_app = ProxyFix(
    app.wsgi_app, x_proto=1)  # http://stackoverflow.com/a/23504684/5156190


@app.route("/")
def hello():
    rows = db.session.execute("SELECT 'hello, world'")
    return rows.first()[0]
コード例 #22
0
def reg_middlewares(app):
    app.wsgi_app = ProxyFix(app.wsgi_app)
    return None
コード例 #23
0
ファイル: server.py プロジェクト: goddess5321/app
def create_app() -> Flask:
    app = Flask(__name__)
    # SimpleLogin is deployed behind NGINX
    app.wsgi_app = ProxyFix(app.wsgi_app, num_proxies=1)
    limiter.init_app(app)

    app.url_map.strict_slashes = False

    app.config["SQLALCHEMY_DATABASE_URI"] = DB_URI
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    # enable to print all queries generated by sqlalchemy
    # app.config["SQLALCHEMY_ECHO"] = True

    app.secret_key = FLASK_SECRET

    app.config["TEMPLATES_AUTO_RELOAD"] = True

    # to avoid conflict with other cookie
    app.config["SESSION_COOKIE_NAME"] = SESSION_COOKIE_NAME
    if URL.startswith("https"):
        app.config["SESSION_COOKIE_SECURE"] = True
    app.config["SESSION_COOKIE_SAMESITE"] = "Lax"

    setup_error_page(app)

    init_extensions(app)
    register_blueprints(app)
    set_index_page(app)
    jinja2_filter(app)

    setup_favicon_route(app)
    setup_openid_metadata(app)

    init_admin(app)
    setup_paddle_callback(app)
    setup_do_not_track(app)

    if FLASK_PROFILER_PATH:
        LOG.d("Enable flask-profiler")
        app.config["flask_profiler"] = {
            "enabled": True,
            "storage": {"engine": "sqlite", "FILE": FLASK_PROFILER_PATH},
            "basicAuth": {
                "enabled": True,
                "username": "******",
                "password": FLASK_PROFILER_PASSWORD,
            },
            "ignore": ["^/static/.*", "/git", "/exception"],
        }
        flask_profiler.init_app(app)

    # enable CORS on /api endpoints
    cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

    # set session to permanent so user stays signed in after quitting the browser
    # the cookie is valid for 7 days
    @app.before_request
    def make_session_permanent():
        session.permanent = True
        app.permanent_session_lifetime = timedelta(days=7)

    return app
コード例 #24
0
def create_app(config="CTFd.config.Config"):
    app = CTFdFlask(__name__)
    with app.app_context():
        app.config.from_object(config)

        loaders = []
        # We provide a `DictLoader` which may be used to override templates
        app.overridden_templates = {}
        loaders.append(jinja2.DictLoader(app.overridden_templates))
        # A `ThemeLoader` with no `theme_name` will load from the current theme
        loaders.append(ThemeLoader())
        # If `THEME_FALLBACK` is set and true, we add another loader which will
        # load from the `DEFAULT_THEME` - this mirrors the order implemented by
        # `config.ctf_theme_candidates()`
        if bool(app.config.get("THEME_FALLBACK")):
            loaders.append(ThemeLoader(theme_name=DEFAULT_THEME))
        # All themes including admin can be accessed by prefixing their name
        prefix_loader_dict = {ADMIN_THEME: ThemeLoader(theme_name=ADMIN_THEME)}
        for theme_name in CTFd.utils.config.get_themes():
            prefix_loader_dict[theme_name] = ThemeLoader(theme_name=theme_name)
        loaders.append(jinja2.PrefixLoader(prefix_loader_dict))
        # Plugin templates are also accessed via prefix but we just point a
        # normal `FileSystemLoader` at the plugin tree rather than validating
        # each plugin here (that happens later in `init_plugins()`). We
        # deliberately don't add this to `prefix_loader_dict` defined above
        # because to do so would break template loading from a theme called
        # `prefix` (even though that'd be weird).
        plugin_loader = jinja2.FileSystemLoader(searchpath=os.path.join(
            app.root_path, "plugins"),
                                                followlinks=True)
        loaders.append(jinja2.PrefixLoader({"plugins": plugin_loader}))
        # Use a choice loader to find the first match from our list of loaders
        app.jinja_loader = jinja2.ChoiceLoader(loaders)

        from CTFd.models import (  # noqa: F401
            db, Teams, Solves, Challenges, Fails, Flags, Tags, Files, Tracking,
        )

        url = create_database()

        # This allows any changes to the SQLALCHEMY_DATABASE_URI to get pushed back in
        # This is mostly so we can force MySQL's charset
        app.config["SQLALCHEMY_DATABASE_URI"] = str(url)

        # Register database
        db.init_app(app)

        # Register Flask-Migrate
        migrations.init_app(app, db)

        # Alembic sqlite support is lacking so we should just create_all anyway
        if url.drivername.startswith("sqlite"):
            # Enable foreign keys for SQLite. This must be before the
            # db.create_all call because tests use the in-memory SQLite
            # database (each connection, including db creation, is a new db).
            # https://docs.sqlalchemy.org/en/13/dialects/sqlite.html#foreign-key-support
            from sqlalchemy.engine import Engine
            from sqlalchemy import event

            @event.listens_for(Engine, "connect")
            def set_sqlite_pragma(dbapi_connection, connection_record):
                cursor = dbapi_connection.cursor()
                cursor.execute("PRAGMA foreign_keys=ON")
                cursor.close()

            db.create_all()
            stamp_latest_revision()
        else:
            # This creates tables instead of db.create_all()
            # Allows migrations to happen properly
            upgrade()

        from CTFd.models import ma

        ma.init_app(app)

        app.db = db
        app.VERSION = __version__
        app.CHANNEL = __channel__

        from CTFd.cache import cache

        cache.init_app(app)
        app.cache = cache

        reverse_proxy = app.config.get("REVERSE_PROXY")
        if reverse_proxy:
            if type(reverse_proxy) is str and "," in reverse_proxy:
                proxyfix_args = [int(i) for i in reverse_proxy.split(",")]
                app.wsgi_app = ProxyFix(app.wsgi_app, *proxyfix_args)
            else:
                app.wsgi_app = ProxyFix(app.wsgi_app,
                                        x_for=1,
                                        x_proto=1,
                                        x_host=1,
                                        x_port=1,
                                        x_prefix=1)

        version = utils.get_config("ctf_version")

        # Upgrading from an older version of CTFd
        if version and (StrictVersion(version) < StrictVersion(__version__)):
            if confirm_upgrade():
                run_upgrade()
            else:
                exit()

        if not version:
            utils.set_config("ctf_version", __version__)

        if not utils.get_config("ctf_theme"):
            utils.set_config("ctf_theme", DEFAULT_THEME)

        update_check(force=True)

        init_request_processors(app)
        init_template_filters(app)
        init_template_globals(app)

        # Importing here allows tests to use sensible names (e.g. api instead of api_bp)
        from CTFd.views import views
        from CTFd.teams import teams
        from CTFd.users import users
        from CTFd.challenges import challenges
        from CTFd.scoreboard import scoreboard
        from CTFd.auth import auth
        from CTFd.admin import admin
        from CTFd.api import api
        from CTFd.events import events
        from CTFd.errors import render_error

        app.register_blueprint(views)
        app.register_blueprint(teams)
        app.register_blueprint(users)
        app.register_blueprint(challenges)
        app.register_blueprint(scoreboard)
        app.register_blueprint(auth)
        app.register_blueprint(api)
        app.register_blueprint(events)

        app.register_blueprint(admin)

        for code in {403, 404, 500, 502}:
            app.register_error_handler(code, render_error)

        init_logs(app)
        init_events(app)
        init_plugins(app)

        return app
コード例 #25
0
ファイル: app.py プロジェクト: talhasch/lander-tools
def __flask_setup():
    global app, cache

    app = Flask(__name__, static_folder=None)

    app.wsgi_app = ProxyFix(app.wsgi_app)

    cache_config = {
        'CACHE_TYPE': 'filesystem',
        'CACHE_THRESHOLD': 10000,
        'CACHE_DEFAULT_TIMEOUT': 86400,
        'CACHE_DIR': os.path.join(tempfile.gettempdir(), 'i-p')
    }
    cache = Cache(with_jinja2_ext=False, config=cache_config)
    cache.init_app(app)

    @app.route('/i-p-s')
    def index():
        return 'HELLO'

    @app.route('/i-p/<code>')
    @app.route('/i-p/<code>/<size>')
    def serve(code, size=None):

        cache_key = code

        if size is not None:
            try:
                width, height = [int(x) for x in size.split('x')]
                assert 20 <= width <= 1000
                assert 20 <= height <= 1000
                cache_key = '{}/{}/{}'.format(cache_key, width, height)
            except BaseException:
                abort(406)

        rv = cache.get(cache_key)

        try:
            url = base64.b64decode(code).decode('utf-8')
        except BaseException:
            abort(404)
            return

        if rv is None:

            try:
                resp = requests.get(url)
            except BaseException:
                abort(404)
                return

            if resp.status_code != 200:
                abort(404)
                return

            rv = resp.content

            if size:
                im_io = BytesIO()
                im = Image.open(BytesIO(rv))
                im.thumbnail((width, height))
                im.save(im_io, im.format, quality=96)
                im_io.seek(0)
                rv = im_io.read()

            cache.set(cache_key, rv)

        response = make_response(rv)
        response.set_etag(code)

        mime_type = magic.from_buffer(rv, mime=True)

        response.headers.set('Content-Type', mime_type)
        response.headers.add('Last-Modified', 'Fri, 10 Jan 2020 00:00:10 GMT')
        response.headers.add('Expires', 'Fri, 10 Jan 2030 00:00:10 GMT')

        return response
コード例 #26
0
ファイル: app.py プロジェクト: Anonyymi/lautasofta-service
# init os.environ from file if not initialized
if os.getenv('DB_HOST') is None:
    import common.setenv

import json
import awsgi
from flask import Flask
from flask_cors import (CORS)
from werkzeug.middleware.proxy_fix import (ProxyFix)
from api.api_main import api_main
from api.api_admin import api_admin

# init flask app
app = Flask(__name__)
CORS(app, resources={r'/*': {'origins': '*'}})
ProxyFix(app.wsgi_app, 1)
app.register_blueprint(api_main)
app.register_blueprint(api_admin)


def lambda_handler(evt, ctx):
    """AWS Lambda entrypoint"""

    try:
        return awsgi.response(app, evt, ctx)
    except Exception as err:
        print(f'{err}')

        return {
            'statusCode': 500,
            'body': json.dumps({
コード例 #27
0
                # remove trailing slash to avoid infinite redirect on the index
                # see https://github.com/searx/searx/issues/2729
                self.script_name = self.script_name[:-1]
            self.scheme = base_url.scheme
            self.server = base_url.netloc

    def __call__(self, environ, start_response):
        script_name = self.script_name or environ.get('HTTP_X_SCRIPT_NAME', '')
        if script_name:
            environ['SCRIPT_NAME'] = script_name
            path_info = environ['PATH_INFO']
            if path_info.startswith(script_name):
                environ['PATH_INFO'] = path_info[len(script_name):]

        scheme = self.scheme or environ.get('HTTP_X_SCHEME', '')
        if scheme:
            environ['wsgi.url_scheme'] = scheme

        server = self.server or environ.get('HTTP_X_FORWARDED_HOST', '')
        if server:
            environ['HTTP_HOST'] = server
        return self.app(environ, start_response)


application = app
# patch app to handle non root url-s behind proxy & wsgi
app.wsgi_app = ReverseProxyPathFix(ProxyFix(application.wsgi_app))

if __name__ == "__main__":
    run()
コード例 #28
0
ファイル: run.py プロジェクト: mmushtaq201/ihatemoney
def create_app(configuration=None,
               instance_path="/etc/ihatemoney",
               instance_relative_config=True):
    app = Flask(
        __name__,
        instance_path=instance_path,
        instance_relative_config=instance_relative_config,
    )

    # If a configuration object is passed, use it. Otherwise try to find one.
    load_configuration(app, configuration)
    app.wsgi_app = PrefixedWSGI(app)

    # Get client's real IP
    # Note(0livd): When running in a non-proxy setup, is vulnerable to requests
    # with a forged X-FORWARDED-FOR header
    app.wsgi_app = ProxyFix(app.wsgi_app)

    validate_configuration(app)
    app.register_blueprint(web_interface)
    app.register_blueprint(apiv1)
    app.register_error_handler(404, page_not_found)

    # Configure the a, root="main"pplication
    setup_database(app)

    # Setup Currency Cache
    CurrencyConverter()

    mail = Mail()
    mail.init_app(app)
    app.mail = mail

    # Jinja filters
    app.jinja_env.globals["static_include"] = static_include
    app.jinja_env.globals["locale_from_iso"] = locale_from_iso
    app.jinja_env.filters["minimal_round"] = minimal_round

    # Translations and time zone (used to display dates).  The timezone is
    # taken from the BABEL_DEFAULT_TIMEZONE settings, and falls back to
    # the local timezone of the server OS by using LOCALTZ.
    babel = Babel(app, default_timezone=str(LOCALTZ))

    # Undocumented currencyformat filter from flask_babel is forwarding to Babel format_currency
    # We overwrite it to remove the currency sign ¤ when there is no currency
    @contextfilter
    def currency(context, number, currency=None, *args, **kwargs):
        if currency is None:
            currency = context.get("g").project.default_currency
        """
        Same as flask_babel.Babel.currencyformat, but without the "no currency ¤" sign
        when there is no currency.
        """
        return format_currency(
            number,
            currency if currency != CurrencyConverter.no_currency else "",
            *args, **kwargs).strip()

    app.jinja_env.filters["currency"] = currency

    @babel.localeselector
    def get_locale():
        # get the lang from the session if defined, fallback on the browser "accept
        # languages" header.
        lang = session.get(
            "lang",
            request.accept_languages.best_match(
                app.config["SUPPORTED_LANGUAGES"]),
        )
        setattr(g, "lang", lang)
        return lang

    return app
コード例 #29
0
from mongoengine import connect
from werkzeug.middleware.proxy_fix import ProxyFix
from flask_jwt_extended import JWTManager

from config import get_config
from controller.user_controller import ns as ns_user
from controller.session_controller import ns as ns_session
from controller.devis_controller import ns as ns_devis

app = Flask(__name__)
CORS(app,
     origins=["https://devis.uni-roulotte.fr"],
     supports_credentials=True,
     allow_headers=["Access-Control-Allow-Credentials", "Content-Type"])
app.config.from_object(get_config())
app.wsgi_app = ProxyFix(app.wsgi_app)

app.url_map.strict_slashes = False

app.config['JWT_TOKEN_LOCATION'] = ['cookies']
app.config['JWT_COOKIE_SECURE'] = False
app.config['JWT_COOKIE_CSRF_PROTECT'] = False
jwt = JWTManager(app)

api = Api(app, version='3.0', title='Simulateur de devis')

api.add_namespace(ns_user, path='/api/user')
api.add_namespace(ns_session, path='/api/session')
api.add_namespace(ns_devis, path='/api/devis')

if __name__ == "__main__":
コード例 #30
0
def init(app,
         db,
         config,
         base_prefix='/auth',
         root_uri='/',
         providers=['google', 'facebook', 'github'],
         smtp=None,
         fix_ssl=True):
    """
    Initalize framework

    Args:
        app: Flask app
        db: pyaltt2.db.Database object
        config: configuration dict
        base_prefix: base prefix for auth urls
        root_uri: default next uri
        providers: oauth2 providers list
        smtp: pyaltt2.mail.SMTP object, required if email confirmations are
        used
        fix_ssl: force SSL everywhere (True by default)
    """

    if not app.config.get('SECRET_KEY'):
        app.config['SECRET_KEY'] = gen_random_str()

    _d.x_prefix, _d.dot_prefix = _format_prefix(base_prefix)
    _d.db = db.clone(rq_func=rq)
    _d.kv = KVStorage(db=db, table_name='webauth_kv')
    _d.root_uri = root_uri
    _d.smtp = smtp

    if fix_ssl:
        from werkzeug.middleware.proxy_fix import ProxyFix
        app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1)

    def init_db():
        from sqlalchemy import (MetaData, Table, Column, BigInteger, VARCHAR,
                                JSON, CHAR, DateTime, ForeignKey, Index,
                                Boolean, Numeric)
        meta = MetaData()
        user = Table(
            'webauth_user', meta,
            Column('id', BigInteger(), primary_key=True, autoincrement=True),
            Column('email', VARCHAR(255), nullable=True, unique=True),
            Column('password', CHAR(64), nullable=True),
            Column('api_key', CHAR(32), nullable=True, unique=True),
            Index('webauth_user_api_key', 'api_key'),
            Column('d_created', DateTime(timezone=True), nullable=False),
            Column('d_active', DateTime(timezone=True), nullable=True),
            Column('confirmed', Boolean, nullable=False, server_default='0'),
            Column('otp', Numeric(1, 0), nullable=False, server_default='0'),
            Column('otp_secret', CHAR(16), nullable=True))
        user_auth = Table(
            f'webauth_user_auth', meta,
            Column('id', BigInteger(), primary_key=True, autoincrement=True),
            Column('user_id',
                   BigInteger(),
                   ForeignKey('webauth_user.id', ondelete='CASCADE'),
                   nullable=False),
            Index('webauth_user_auth_user_id', 'user_id'),
            Column('provider', VARCHAR(15), nullable=False),
            Column('sub', VARCHAR(255), nullable=False),
            Column('name', VARCHAR(255), nullable=True),
            Index('webauth_user_auth_sub_provider',
                  'sub',
                  'provider',
                  unique=True))
        user_log = Table(
            f'webauth_user_log', meta,
            Column('id', BigInteger(), primary_key=True, autoincrement=True),
            Column('user_id', BigInteger(), nullable=False),
            Index('webauth_user_log_user_id', 'user_id'),
            Column('d', DateTime(timezone=True), nullable=False),
            Column('event', VARCHAR(1024), nullable=False),
            Column('ip', VARCHAR(45), nullable=False))
        meta.create_all(db.connect())

    def handle_authorize(remote, token, user_info):
        if user_info:
            try:
                provider = remote if isinstance(remote, str) else remote.name
                user_id = _handle_user_auth(user_info, provider=provider)
                touch(user_id)
                session[f'{_d.x_prefix}user_id'] = user_id
                session[f'{_d.x_prefix}user_picture'] = user_info.picture
                session[f'{_d.x_prefix}user_name'] = _get_oauth_user_name(
                    user_info, provider)
                session[f'{_d.x_prefix}user_confirmed'] = True
                _call_handler('account.login', user_id=user_id)
                _log_user_event(f'account.login:{provider}')
                return redirect(_next_uri())
            except ResourceAlreadyExists:
                response = _call_handler('exception.provider_exists')
                return response if response else Response(
                    'oauth provider is already ' +
                    'registered for another account',
                    status=409)
            except AccessDenied:
                response = _call_handler('exception.registration_denied')
                return response if response else Response(
                    'account registration is disabled', status=403)
            # session.permanent = True
        else:
            response = _call_handler('exception.provider_failed')
            return response if response else Response('forbidden', status=403)

    def google_login():
        redirect_uri = url_for(f'{_d.dot_prefix}google.auth', _external=True)
        return oauth.google.authorize_redirect(redirect_uri)

    def google_auth():
        token = oauth.google.authorize_access_token()
        user_info = oauth.google.parse_id_token(token)
        return handle_authorize('google', token, user_info)

    for k in config:
        app.config[k.upper().replace('-', '_')] = config_value(config=config,
                                                               config_path=k)
    oauth = OAuth(app)
    app.add_url_rule(f'{base_prefix}/logout',
                     f'{_d.dot_prefix}.logout',
                     logout,
                     methods=['GET'])
    app.add_url_rule(f'{base_prefix}/confirm/<key>',
                     f'{_d.dot_prefix}confirm',
                     handle_confirm,
                     methods=['GET'])
    for p in providers:
        if p == 'google':
            oauth.register(
                'google',
                server_metadata_url=
                'https://accounts.google.com/.well-known/openid-configuration',
                client_kwargs={'scope': 'openid profile'},
            )
            app.add_url_rule(f'{base_prefix}/google/login',
                             f'{_d.dot_prefix}google.login',
                             google_login,
                             methods=['GET'])
            app.add_url_rule(f'{base_prefix}/google/auth',
                             f'{_d.dot_prefix}google.auth',
                             google_auth,
                             methods=['GET'])
        else:
            blueprint = loginpass.create_flask_blueprint(
                _provider_mod[p], oauth, handle_authorize)
            app.register_blueprint(blueprint, url_prefix=f'{base_prefix}/{p}')
    init_db()
    return