def create_app(testing=None):
    app = Flask(__name__)
    if testing:
        config.TESTING = True
        m = re.search("_test", config.MONGO_DATABASE)
        if not m:
            config.MONGO_DATABASE = "%s_test" % config.MONGO_DATABASE

        config.ADMIN = "rusty.shackelford"

    app.config.from_object(config)
    app.register_blueprint(admin_bp, url_prefix="/admin")
    app.register_blueprint(manage_bp, url_prefix="/manage")
    app.register_blueprint(engine_bp, url_prefix="/engine")

    mongo, db = HapPyMongo(config)

    custom_filters = {name: function for name, function in getmembers(template_filters) if isfunction(function)}
    app.jinja_env.filters.update(custom_filters)
    app.context_processor(context_functions.utility_processor)

    @app.before_request
    def before_request():
        g.db = db

    views.ProductsView.register(app)
    views.MiscView.register(app)

    return app, db
Beispiel #2
1
def create_app(db_name=None):
    app = Flask(__name__)
    app.config.from_object(config)
    if db_name:
        config.MONGO_DATABASE = db_name

    mongo, db = HapPyMongo(config)
    app.permanent_session_lifetime = timedelta(hours=2)

    auth = CloudAuth(app, db)
    app.context_processor(template_functions.view_functions)

    Admin(app)

    @app.before_first_request
    def logger():
        if not app.debug:
            app.logger.addHandler(logging.StreamHandler())
            app.logger.setLevel(logging.INFO)

    @app.before_request
    def before_request():
        g.db, g.auth = db, auth

    defaults.application_initialize(db, app)
    views.BaseView.register(app)
    views.GlobalManageView.register(app)
    views.QueryView.register(app)

    if db_name:
        return app, db
    else:
        return app
def create_app(debug=False):
    app = Flask(
        __name__.split(".")[0], static_folder=STATIC_ROOT, template_folder=path.join(APPLICATION_ROOT, "templates")
    )

    app.config.from_object(__name__)
    app.debug = debug

    app.register_blueprint(shared_bp)
    app.register_blueprint(blog_bp, url_prefix="/blog")
    app.register_blueprint(admin_bp, url_prefix="/admin")

    register_frontend_routes(app)

    # Configure webassets environment.
    init_assets_environment(app, include_dependencies=debug, auto_build=debug)

    # Initialize SQLAlchemy connection with the application.
    db.init_app(app)

    # Add a Jinja context processor.
    app.context_processor(current_year)
    app.context_processor(current_revision)

    return app
Beispiel #4
1
Datei: main.py Projekt: vddd/rn
def create_app():
    app = Flask(__name__)

    load_config(app)

    app.debug = app.config["DEBUG"]
    app.secret_key = app.config["SECRET_KEY"]

    # init flask extensions
    db.init_app(app)
    mail.init_app(app)
    login_manager.init_app(app)
    app.context_processor(inject_roles)

    # init my modules
    upload.init_app(app)
    filters.init_app(app)
    views.init_app(app)

    # register routes
    app.register_blueprint(views.bp_basic)
    app.register_blueprint(views.bp_responsable)
    app.register_blueprint(views.bp_activite)
    app.register_blueprint(views.bp_brn)

    return app
Beispiel #5
1
def create_app(envar="FLASK_SETTINGS", config_object=None):
    app = Flask(__name__)
    if config_object is None:
        app.config.from_envvar("FLASK_SETTINGS")
    else:
        app.config.from_object(config_object)
    if "local_timezone" not in app.config:
        app.config["local_timezone"] = pytz.timezone("Europe/Vienna")
    if "type2module" not in app.config:
        app.config["type2view"] = {"meetup": "meetups.view_doc", "company": "companies.view_doc"}
    if "LOG_FILE" in app.config:
        handler = logging.handlers.RotatingFileHandler(app.config["LOG_FILE"], backupCount=5, maxBytes=1000000)
        if "LOG_LEVEL" in app.config:
            handler.setLevel(app.config["LOG_LEVEL"])
        else:
            handler.setLevel(logging.INFO)
        app.logger.addHandler(handler)

    app.jinja_env.filters["time"] = filters.timefilter
    app.jinja_env.filters["date"] = filters.datefilter
    app.jinja_env.filters["datecode"] = filters.datecode
    app.jinja_env.filters["datetime"] = filters.datetimefilter
    app.jinja_env.filters["rst"] = filters.rst
    app.jinja_env.filters["urlencode"] = filters.urlencode
    app.jinja_env.filters["urlize"] = filters.urlize
    app.jinja_env.filters["in_future"] = filters.in_future
    app.secret_key = app.config["SECRET_KEY"]

    db.init_app(app)
    postmark.init_app(app)
    auth.init_app(app)
    compass.init_app(app)

    from . import models

    # Register modules
    from .views.account import module as account_module
    from .views.admin import module as admin_module
    from .views.core import module as core_module
    from .views.meetups import module as meetups_module

    app.register_blueprint(core_module, url_prefix="")
    app.register_blueprint(account_module, url_prefix="/account")
    app.register_blueprint(admin_module, url_prefix="/admin")
    app.register_blueprint(meetups_module, url_prefix="/meetups")

    # Register context and request processors
    app.context_processor(context_processors.add_form_generator)

    # Register babel's i18n functions globally in order for Flatland to see
    # them.
    babel.init_app(app)
    oid.init_app(app)
    __builtin__.ugettext = lambda x: get_translations().ugettext(x)
    __builtin__.ungettext = lambda x, s, p: get_translations().ungettext(x, s, p)
    app.error_handlers[409] = utils.handle_conflict
    redis.init_app(app)

    return app
Beispiel #6
1
def create_app(config):

    """A factory that returns an application object from the passed config.

    The factory accepts further configuration from ENV variables. Some simple
    checks for core configuration settings are made to raise errors early
    if vital information is missing.

    """

    import os
    from flask import Flask
    from flask.ext.babel import Babel
    from flask.ext.cors import CORS
    from flask.ext.markdown import Markdown

    #    from flask.ext.assets import Environment, Bundle
    from .components import api, pages
    from .components.commons import context_processors, encoders

    app_label = "web"

    # Get the static and template folder for the passed theme
    static_folder = os.path.join("theme", "static")
    template_folder = os.path.join("theme", "templates")

    # Construct app and service objects
    app = Flask(app_label, template_folder=template_folder, static_folder=static_folder, static_url_path="/static")
    trans = Babel()
    cors = CORS(resources=r"/api/*", allow_headers="Content-Type")
    #    assets = Environment()

    # Configure the app with defaults
    app.config.from_object(config)

    # Set app core services
    trans.init_app(app)
    cors.init_app(app)
    #    assets.init_app(app)
    Markdown(app)

    # Register routable components
    app.register_blueprint(api.blueprint)
    app.register_blueprint(pages.blueprint)

    # Set additional jinja2 extensions
    app.jinja_env.add_extension("jinja2.ext.do")

    # Set custom context processors
    app.context_processor(context_processors.inject_app_data)

    # Set custom encoders
    app.json_encoder = encoders.JSONEncoder

    # Register webassets bundles
    #    sass = Bundle('css/base.scss', filters='pyscss', output='css/base.css')
    #    assets.register('sass', sass)

    return app
Beispiel #7
1
def create_app(source=None, config=None):
    app = Flask("flaskrst")

    # Set default config values
    app.config.setdefault("MODULES", {})
    app.config.setdefault("STYLESHEETS", [])
    app.config.setdefault("FEEDS", [])

    # Load config
    if config:
        app.config.from_pyfile(config)
        config_loaded = True
    # maybe there is a file declared by env
    elif "FLASK_RST_CONFIG" in os.environ:
        app.config.from_envvar("FLASK_RST_CONFIG")
        config_loaded = True
    # no config loaded try again later after source setting
    else:
        config_loaded = False

    # Set source path
    if source:
        app.config["SOURCE"] = source
    elif "FLASK_RST_SOURCE" in os.environ:
        app.config["SOURCE"] = os.environ["FLASK_RST_SOURCE"]
    else:
        # Use current working directory as source
        app.config["SOURCE"] = os.getcwd()

    # If no config already loaded than is a config maybe in source path
    if not config_loaded:
        config_path = os.path.join(app.config["SOURCE"], "config.py")
        app.config.from_pyfile(config_path, silent=True)

    # Set path of static folder
    if "STATIC_FOLDER" in app.config:
        app.static_folder = app.config["STATIC_FOLDER"]
    else:
        # Is a static folder called _static in source path?
        source_static_folder = os.path.join(app.config["SOURCE"], "_static")
        if os.path.isdir(source_static_folder):
            app.static_folder = source_static_folder

    # Load flask-rst modules
    manager.init_app(app)
    manager.load_from_config()

    # Add some jinja globals and context processors
    app.jinja_env.globals["date"] = date
    app.context_processor(inject_navigation)

    @app.errorhandler(404)
    def page_not_found(error):
        return render_template("404.html"), 404

    return app
Beispiel #8
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(os.environ["SETTINGS"])
    register_errorhandlers(app)
    register_blueprints(app)
    register_extensions(app)
    app.context_processor(asset_path_context_processor)
    return app
Beispiel #9
0
class AppFactory(object):
    def __init__(self, config, envvar="PROJECT_SETTINGS", bind_db_object=True):
        self.app_config = config
        self.app_envvar = os.environ.get(envvar, False)
        self.bind_db_object = bind_db_object

    def get_app(self, app_module_name, **kwargs):
        self.app = Flask(app_module_name, **kwargs)
        self.app.config.from_object(self.app_config)
        self.app.config.from_envvar(self.app_envvar, silent=True)

        self._bind_extensions()
        self._register_blueprints()
        self._register_context_processors()
        self._register_template_filters()

        return self.app

    def _get_imported_stuff_by_path(self, path):
        module_name, object_name = path.rsplit(".", 1)
        module = import_string(module_name)

        return module, object_name

    def _bind_extensions(self):
        for ext_path in self.app.config.get("EXTENSIONS", []):
            module, e_name = self._get_imported_stuff_by_path(ext_path)
            if not hasattr(module, e_name):
                raise NoExtensionException("No {e_name} extension found".format(e_name=e_name))
            ext = getattr(module, e_name)
            if getattr(ext, "init_app", False):
                ext.init_app(self.app)
            else:
                ext(self.app)

    def _register_template_filters(self):
        for filter_path in self.app.config.get("TEMPLATE_FILTERS", []):
            module, f_name = self._get_imported_stuff_by_path(filter_path)
            if hasattr(module, f_name):
                self.app.jinja_env.filters[f_name] = getattr(module, f_name)
            else:
                raise NoTemplateFilterException("No {f_name} template filter found".format(f_name=f_name))

    def _register_context_processors(self):
        for processor_path in self.app.config.get("CONTEXT_PROCESSORS", []):
            module, p_name = self._get_imported_stuff_by_path(processor_path)
            if hasattr(module, p_name):
                self.app.context_processor(getattr(module, p_name))
            else:
                raise NoContextProcessorException("No {cp_name} context processor found".format(cp_name=p_name))

    def _register_blueprints(self):
        for blueprint_path in self.app.config.get("BLUEPRINTS", []):
            module, b_name = self._get_imported_stuff_by_path(blueprint_path)
            if hasattr(module, b_name):
                self.app.register_blueprint(getattr(module, b_name))
            else:
                raise NoBlueprintException("No {bp_name} blueprint found".format(bp_name=b_name))
Beispiel #10
0
class CreateApp(object):
    def __init__(self, cfg=BaseConfig, envvar="PROJECT_SETTINGS", bind_db=True):
        self.app_config = cfg
        self.app_envvar = envvar
        self.bind_db = bind_db

    def get_app(self, app_module_name, **kwargs):
        self.app = Flask(app_module_name, **kwargs)
        self.app.config.from_object(self.app_config)
        self.app.config.from_envvar(self.app_envvar, silent=True)
        self.app.config.from_pyfile("local_settings.py", silent=True)

        self._bind_extensions()
        self._register_blueprints()
        self._register_context_processors()

        # self.app.db = db
        # connection = get_connection()
        # self.app.db = connection[self.app.config['MONGO_DBNAME']]

        return self.app

    def _get_imported_stuff_by_path(self, path):
        mo_pa = path.split(".")
        module_name = ".".join(mo_pa[:-1])
        objNam = mo_pa[-1]
        module = __import__(module_name, fromlist=[objNam])

        return module, objNam

    def _bind_extensions(self):
        for ext_path in self.app.config.get("EXTENSIONS", []):
            module, e_name = self._get_imported_stuff_by_path(ext_path)
            if not hasattr(module, e_name):
                raise NoExtensionException("No {e_name} extension found".format(e_name=e_name))
            ext = getattr(module, e_name)
            if getattr(ext, "init_app", False):
                ext.init_app(self.app)
            else:
                ext(self.app)

    def _register_context_processors(self):
        for processor_path in self.app.config.get("CONTEXT_PROCESSORS", []):
            module, p_name = self._get_imported_stuff_by_path(processor_path)
            if hasattr(module, p_name):
                self.app.context_processor(getattr(module, p_name))
            else:
                raise NoContextProcessorException("No {cp_name} context processor found".format(cp_name=p_name))

    def _register_blueprints(self):
        for blueprint_path in self.app.config.get("BLUEPRINTS", []):
            module, b_name = self._get_imported_stuff_by_path(blueprint_path)
            if hasattr(module, b_name):
                self.app.register_blueprint(getattr(module, b_name))
            else:
                raise NoBlueprintException("No {bp_name} blueprint found".format(bp_name=b_name))
Beispiel #11
0
def create_app(**kwargs):
    """
        create a WSGI application that can be used in the
        modules.
    """

    from flask import Flask
    from pyggi.lib.config import config
    import logging

    static_base = "/static"
    if config.has_option("general", "static_url_base"):
        static_base = config.get("general", "static_url_base")
    app = Flask(__name__, static_url_path=static_base)

    # get logging settings
    config_settings = dict(
        level=logging.WARNING, format="[%(asctime)s] %(levelname)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S"
    )

    if config.has_option("log", "file"):
        config_settings["filename"] = config.get("log", "file")

    # activate logging
    logging.basicConfig(**config_settings)

    # register modules to application. the modules come
    # from the configuration file. there is a list of
    # modules to be imported. an item in this list has the
    # form ("module:name","prefix") where name is the name of the module
    # object that should be imported
    for module_desc in config.items("modules"):
        module, prefix = module_desc
        module, attribute = module.rsplit(".", 1)

        # now we try to import the module and register it
        # in our application. otherwise ignore and continue
        try:
            _import = __import__(module, globals(), locals(), [attribute], -1)
            prefix = "" if prefix.strip("/") == "" else "/" + prefix.strip("/")
            app.register_blueprint(getattr(_import, attribute), url_prefix=prefix)
        except Exception as e:
            logging.critical("could not load module '%s': %s", module_desc[0], e)

    # register some filters
    import lib.filters

    app.jinja_env.filters["dateformat"] = lib.filters.format_datetime
    app.jinja_env.filters["diffformat"] = lib.filters.format_diff
    app.jinja_env.filters["timesince"] = lib.filters.humanize_timesince
    app.jinja_env.filters["force_unicode"] = lib.filters.force_unicode
    app.jinja_env.filters["first_line"] = lib.filters.first_line
    app.jinja_env.tests["text"] = lib.filters.is_text
    app.context_processor(lambda: dict(static_url_for=lib.filters.static_url_for))

    return app
Beispiel #12
0
def create_app(config_filename):
    """ An application factory, as explained here:
        http://flask.pocoo.org/docs/patterns/appfactories/
    """
    app = Flask(__name__)
    app.config.from_object(config_filename)
    register_errorhandlers(app)
    register_blueprints(app)
    app.context_processor(asset_path_context_processor)
    return app
Beispiel #13
0
class AppFactory(object):
    def __init__(self, config=None, envvar="PROJECT_SETTINGS", bind_db_object=True):
        self.app_config = config
        self.app_envvar = os.environ.get(envvar, False)
        self.bind_db_object = bind_db_object

    def get_app(self, app_module_name, **kwargs):
        self.app = Flask(app_module_name, **kwargs)
        if self.app_config:
            self.app.config.from_object(self.app_config)
        if self.app_envvar:
            self.app.config.from_object(self.app_envvar)

        self._bind_extensions()
        self._register_blueprints()
        self._register_context_processors()

        return self.app

    def _get_imported_stuff_by_path(self, path):
        module_name, object_name = path.rsplit(".", 1)
        module = import_string(module_name)

        return module, object_name

    def _bind_extensions(self):
        for ext_path in self.app.config.get("EXTENSIONS", []):
            module, e_name = self._get_imported_stuff_by_path(ext_path)
            if not hasattr(module, e_name):
                raise NoExtensionException("No {e_name} extension found".format(e_name=e_name))

            ext = getattr(module, e_name)
            if hasattr(ext, "init_app"):
                ext.init_app(self.app)
            elif callable(ext):
                ext(self.app)
            else:
                raise NoExtensionException("{e_name} extension has no init_app. Can't initialize".format(e_name=e_name))

    def _register_context_processors(self):
        for processor_path in self.app.config.get("CONTEXT_PROCESSORS", []):
            module, p_name = self._get_imported_stuff_by_path(processor_path)
            if hasattr(module, p_name):
                self.app.context_processor(getattr(module, p_name))
            else:
                raise NoContextProcessorException("No {cp_name} context processor found".format(cp_name=p_name))

    def _register_blueprints(self):
        for blueprint_path in self.app.config.get("BLUEPRINTS", []):
            module, b_name = self._get_imported_stuff_by_path(blueprint_path)
            if hasattr(module, b_name):
                self.app.register_blueprint(getattr(module, b_name))
            else:
                raise NoBlueprintException("No {bp_name} blueprint found".format(bp_name=b_name))
Beispiel #14
0
def create_app():
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object("app.config")
    app.config.from_pyfile("config.py", silent=True)

    # Set up application
    configure_blueprints(app)
    configure_extensions(app)

    app.context_processor(context_processor)

    return app
Beispiel #15
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])

    db.init_app(app)
    db.app = app

    if not app.config["TESTING"]:
        configure_custom_settings(app)
    config[config_name].init_app(app)

    thumbnail.init_app(app)
    babel.init_app(app)
    cache.init_app(app)
    login_manager.init_app(app)
    mail.init_app(app)
    setup_themes(app)
    Mobility(app)

    from .utils.filters import register_filters

    register_filters(app)

    from .utils.processors import utility_processor

    app.context_processor(utility_processor)

    from .api import api as api_blueprint

    app.register_blueprint(api_blueprint, url_prefix="/api")

    from .main import main as main_blueprint

    app.register_blueprint(main_blueprint)

    from .account import account as auth_blueprint

    app.register_blueprint(auth_blueprint, url_prefix="/account")

    from .admins import admin

    admin.init_app(app)

    @app.route("/favicon.ico")
    def favicon():
        return send_from_directory(app.static_folder, "favicon.ico", mimetype="image/vnd.microsoft.icon")

    @app.route("/robots.txt")
    def robotstxt():
        return send_from_directory(app.static_folder, "robots.txt")

    return app
Beispiel #16
0
def create_app(config_name):
    app = Flask(__name__)
    app.config["APPENV"] = str(get_appconfig())
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    cache.init_app(app)
    db.init_app(app)
    db.app = app
    login_manager.init_app(app)
    mail.init_app(app)
    setup_themes(app)
    Mobility(app)

    from .utils.filters import register_filters

    register_filters(app)

    from .utils.processors import utility_processor

    app.context_processor(utility_processor)

    from .api import api as api_blueprint

    app.register_blueprint(api_blueprint, url_prefix="/api")

    from .main import main as main_blueprint

    app.register_blueprint(main_blueprint)

    from .account import account as auth_blueprint

    app.register_blueprint(auth_blueprint, url_prefix="/account")

    from .admins import admin

    admin.init_app(app)

    # 暂时解决因Gunicorn中引发ERROR 11而无法正常提交的问题
    @app.teardown_request
    def teardown_request(response_or_exc):
        if app.config["SQLALCHEMY_COMMIT_ON_TEARDOWN"]:
            try:
                db.session.commit()
            except:
                db.session.rollback()
        db.session.remove()

    return app
def create_app(config=None):
    """ An application factory, as explained here:
        http://flask.pocoo.org/docs/patterns/appfactories/
    """
    app = Flask(__name__)

    if not config:
        config = os.environ.get("SETTINGS", "application.config.Config")

    app.config.from_object(config)

    register_errorhandlers(app)
    register_blueprints(app)
    app.context_processor(asset_path_context_processor)
    register_extensions(app)
    register_filters(app)
    return app
Beispiel #18
0
def create_app():
    app = Flask(__name__)

    for k, v in os.environ.iteritems():
        if k.startswith(CONFIG_KEY_PREFIX):
            app.config[k[len(CONFIG_KEY_PREFIX) :]] = v

    if app.config["DEBUG"]:
        from werkzeug.debug import DebuggedApplication

        app.wsgi_app = DebuggedApplication(app.wsgi_app, True)
        app.debug = True

    app.url_map.converters["regex"] = utils.RegexConverter
    database.init_app(app)

    if "NO_INIT_DB" not in app.config:
        from deployer.applications import models

        models.Base.metadata.create_all(app.engine)

        from deployer.hosts import models

        models.Base.metadata.create_all(app.engine)

        from deployer.routing import models

        models.Base.metadata.create_all(app.engine)

    app.register_blueprint(_old.views)
    app.register_blueprint(hosts.views, url_prefix="/hosts")
    app.register_blueprint(applications.views, url_prefix="/apps")

    app.context_processor(context_processors.register_functions)

    for name in filters.__all__:
        app.jinja_env.filters[name] = getattr(filters, name)

    BuildsUpdater(app).start(10, now=True)
    RoutesUpdater(app).start(10, now=True)

    return app
def create_app(db_name=None):
    app = Flask(__name__)
    app.config.from_object(config)
    if db_name:
        config.MONGO_DATABASE = db_name

    Admin(app)
    Engine(app)
    mongo, db = HapPyMongo(config)
    app.permanent_session_lifetime = timedelta(hours=2)
    auth = CloudAuth(app, db)

    custom_filters = {name: function for name, function in getmembers(template_filters) if isfunction(function)}
    app.jinja_env.filters.update(custom_filters)
    app.context_processor(template_functions.utility_processor)

    @app.before_first_request
    def logger():
        if not app.debug:
            app.logger.addHandler(logging.StreamHandler())
            app.logger.setLevel(logging.INFO)

    @app.before_request
    def before_request():
        g.db, g.auth = db, auth

    defaults.application_initialize(db, app)
    views.ProductsView.register(app)
    views.MiscView.register(app)
    views.FeedbackView.register(app)
    views.GlobalManageView.register(app)

    if db_name:
        return app, db
    else:
        return app
Beispiel #20
0
def create_app(config):
    app = Flask("muzyczne-bitwy")
    app.config.from_pyfile(config)

    from application.auth import auth

    auth.init_app(app)

    from application.database import db

    db.init_app(app)

    from application.util import jinja2_utilities

    app.context_processor(jinja2_utilities)

    from application.views import index, songs, phases, battles

    app.register_blueprint(index)
    app.register_blueprint(songs)
    app.register_blueprint(phases)
    app.register_blueprint(battles)

    return app
Beispiel #21
0
                    if menu_item.get("admin_required"):
                        menu_admin.append(menu_item)
                    else:
                        menu_public.append(menu_item)
        except Exception as ex:
            logging.exception("Error importing {0} blueprint.".format(filename))

    # This is the official Flask way to store extra data to the app
    if not hasattr(app, "extensions"):
        app.extensions = {}
    app.extensions["menu"] = {"public": menu_public, "admin": menu_admin}


# Add current_menu to teplates. Need some fiddling with app context.
app.context_processor(
    lambda: dict(current_menu=LocalProxy(lambda: current_app.extensions.get("menu", {"public": [], "admin": []})))
)

from filters import problem_label, fancydate, timestamp, memory_address

app.jinja_env.filters["problem_label"] = problem_label
app.jinja_env.filters["fancydate"] = fancydate
app.jinja_env.filters["timestamp"] = timestamp
app.jinja_env.filters["memory_address"] = memory_address

from utils import cache, fed_raw_name, WebfafJSONEncoder

app.json_encoder = WebfafJSONEncoder


@app.route("/")
Beispiel #22
0
mhn.register_blueprint(ui)

from mhn.auth.views import auth

mhn.register_blueprint(auth)

# Trigger templatetag register.
from mhn.common.templatetags import format_date

mhn.jinja_env.filters["fdate"] = format_date

from mhn.auth.contextprocessors import user_ctx

mhn.context_processor(user_ctx)

from mhn.common.contextprocessors import config_ctx

mhn.context_processor(config_ctx)

import logging
from logging.handlers import RotatingFileHandler

mhn.logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s -  %(pathname)s - %(message)s")
handler = RotatingFileHandler(mhn.config["LOG_FILE_PATH"], maxBytes=10240, backupCount=5)
handler.setLevel(logging.INFO)
handler.setFormatter(formatter)
mhn.logger.addHandler(handler)
if mhn.config["DEBUG"]:
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
        return models.user.User.query.get(int(userid))
    except (TypeError, ValueError):
        pass


@app.before_request
def global_user():
    g.user = login.current_user


@app.teardown_appcontext
def commit_on_success(error=None):
    if error is None:
        session.commit()


@app.teardown_request
def shutdown_session(exception=None):
    session.remove()


@app.context_processor
def inject_user():
    try:
        return {"user": g.user}
    except AttributeError:
        return {"user": None}


app.context_processor(backends)
Beispiel #24
0
class LoginTestCase(unittest.TestCase):
    """ Tests for results of the login_user function """

    def setUp(self):
        self.app = Flask(__name__)
        self.app.config["SECRET_KEY"] = "deterministic"
        self.app.config["SESSION_PROTECTION"] = None
        self.remember_cookie_name = "remember"
        self.app.config["REMEMBER_COOKIE_NAME"] = self.remember_cookie_name
        self.login_manager = LoginManager()
        self.login_manager.init_app(self.app)
        self.login_manager._login_disabled = False

        @self.app.route("/")
        def index():
            return u"Welcome!"

        @self.app.route("/secret")
        def secret():
            return self.login_manager.unauthorized()

        @self.app.route("/login-notch")
        def login_notch():
            return unicode(login_user(notch))

        @self.app.route("/login-notch-remember")
        def login_notch_remember():
            return unicode(login_user(notch, remember=True))

        @self.app.route("/login-notch-permanent")
        def login_notch_permanent():
            session.permanent = True
            return unicode(login_user(notch))

        @self.app.route("/needs-refresh")
        def needs_refresh():
            return self.login_manager.needs_refresh()

        @self.app.route("/confirm-login")
        def _confirm_login():
            confirm_login()
            return u""

        @self.app.route("/username")
        def username():
            if current_user.is_authenticated:
                return current_user.name
            return u"Anonymous"

        @self.app.route("/is-fresh")
        def is_fresh():
            return unicode(login_fresh())

        @self.app.route("/logout")
        def logout():
            return unicode(logout_user())

        @self.login_manager.user_loader
        def load_user(user_id):
            return USERS[int(user_id)]

        @self.login_manager.header_loader
        def load_user_from_header(header_value):
            if header_value.startswith("Basic "):
                header_value = header_value.replace("Basic ", "", 1)
            try:
                user_id = base64.b64decode(header_value)
            except TypeError:
                pass
            return USERS.get(int(user_id))

        @self.login_manager.request_loader
        def load_user_from_request(request):
            user_id = request.args.get("user_id")
            try:
                user_id = int(float(user_id))
            except TypeError:
                pass
            return USERS.get(user_id)

        @self.app.route("/empty_session")
        def empty_session():
            return unicode(u"modified=%s" % session.modified)

        # This will help us with the possibility of typoes in the tests. Now
        # we shouldn't have to check each response to help us set up state
        # (such as login pages) to make sure it worked: we will always
        # get an exception raised (rather than return a 404 response)
        @self.app.errorhandler(404)
        def handle_404(e):
            raise e

        unittest.TestCase.setUp(self)

    def _get_remember_cookie(self, test_client):
        our_cookies = test_client.cookie_jar._cookies["localhost.local"]["/"]
        return our_cookies[self.remember_cookie_name]

    def _delete_session(self, c):
        # Helper method to cause the session to be deleted
        # as if the browser was closed. This will remove
        # the session regardless of the permament flag
        # on the session!
        with c.session_transaction() as sess:
            sess.clear()

    #
    # Login
    #
    def test_test_request_context_users_are_anonymous(self):
        with self.app.test_request_context():
            self.assertTrue(current_user.is_anonymous)

    def test_defaults_anonymous(self):
        with self.app.test_client() as c:
            result = c.get("/username")
            self.assertEqual(u"Anonymous", result.data.decode("utf-8"))

    def test_login_user(self):
        with self.app.test_request_context():
            result = login_user(notch)
            self.assertTrue(result)
            self.assertEqual(current_user.name, u"Notch")

    def test_login_user_not_fresh(self):
        with self.app.test_request_context():
            result = login_user(notch, fresh=False)
            self.assertTrue(result)
            self.assertEqual(current_user.name, u"Notch")
            self.assertIs(login_fresh(), False)

    def test_login_user_emits_signal(self):
        with self.app.test_request_context():
            with listen_to(user_logged_in) as listener:
                login_user(notch)
                listener.assert_heard_one(self.app, user=notch)

    def test_login_inactive_user(self):
        with self.app.test_request_context():
            result = login_user(creeper)
            self.assertTrue(current_user.is_anonymous)
            self.assertFalse(result)

    def test_login_inactive_user_forced(self):
        with self.app.test_request_context():
            login_user(creeper, force=True)
            self.assertEqual(current_user.name, u"Creeper")

    def test_login_user_with_header(self):
        user_id = 2
        user_name = USERS[user_id].name
        self.login_manager.request_callback = None
        with self.app.test_client() as c:
            basic_fmt = "Basic {0}"
            decoded = bytes.decode(base64.b64encode(str.encode(str(user_id))))
            headers = [("Authorization", basic_fmt.format(decoded))]
            result = c.get("/username", headers=headers)
            self.assertEqual(user_name, result.data.decode("utf-8"))

    def test_login_invalid_user_with_header(self):
        user_id = 9000
        user_name = u"Anonymous"
        self.login_manager.request_callback = None
        with self.app.test_client() as c:
            basic_fmt = "Basic {0}"
            decoded = bytes.decode(base64.b64encode(str.encode(str(user_id))))
            headers = [("Authorization", basic_fmt.format(decoded))]
            result = c.get("/username", headers=headers)
            self.assertEqual(user_name, result.data.decode("utf-8"))

    def test_login_user_with_request(self):
        user_id = 2
        user_name = USERS[user_id].name
        with self.app.test_client() as c:
            url = "/username?user_id={user_id}".format(user_id=user_id)
            result = c.get(url)
            self.assertEqual(user_name, result.data.decode("utf-8"))

    def test_login_invalid_user_with_request(self):
        user_id = 9000
        user_name = u"Anonymous"
        with self.app.test_client() as c:
            url = "/username?user_id={user_id}".format(user_id=user_id)
            result = c.get(url)
            self.assertEqual(user_name, result.data.decode("utf-8"))

    #
    # Logout
    #
    def test_logout_logs_out_current_user(self):
        with self.app.test_request_context():
            login_user(notch)
            logout_user()
            self.assertTrue(current_user.is_anonymous)

    def test_logout_emits_signal(self):
        with self.app.test_request_context():
            login_user(notch)
            with listen_to(user_logged_out) as listener:
                logout_user()
                listener.assert_heard_one(self.app, user=notch)

    def test_logout_without_current_user(self):
        with self.app.test_request_context():
            login_user(notch)
            del session["user_id"]
            with listen_to(user_logged_out) as listener:
                logout_user()
                listener.assert_heard_one(self.app, user=ANY)

    #
    # Unauthorized
    #
    def test_unauthorized_fires_unauthorized_signal(self):
        with self.app.test_client() as c:
            with listen_to(user_unauthorized) as listener:
                c.get("/secret")
                listener.assert_heard_one(self.app)

    def test_unauthorized_flashes_message_with_login_view(self):
        self.login_manager.login_view = "/login"

        expected_message = self.login_manager.login_message = u"Log in!"
        expected_category = self.login_manager.login_message_category = "login"

        with self.app.test_client() as c:
            c.get("/secret")
            msgs = get_flashed_messages(category_filter=[expected_category])
            self.assertEqual([expected_message], msgs)

    def test_unauthorized_flash_message_localized(self):
        def _gettext(msg):
            if msg == u"Log in!":
                return u"Einloggen"

        self.login_manager.login_view = "/login"
        self.login_manager.localize_callback = _gettext
        self.login_manager.login_message = u"Log in!"

        expected_message = u"Einloggen"
        expected_category = self.login_manager.login_message_category = "login"

        with self.app.test_client() as c:
            c.get("/secret")
            msgs = get_flashed_messages(category_filter=[expected_category])
            self.assertEqual([expected_message], msgs)
        self.login_manager.localize_callback = None

    def test_unauthorized_uses_authorized_handler(self):
        @self.login_manager.unauthorized_handler
        def _callback():
            return Response("This is secret!", 401)

        with self.app.test_client() as c:
            result = c.get("/secret")
            self.assertEqual(result.status_code, 401)
            self.assertEqual(u"This is secret!", result.data.decode("utf-8"))

    def test_unauthorized_aborts_with_401(self):
        with self.app.test_client() as c:
            result = c.get("/secret")
            self.assertEqual(result.status_code, 401)

    def test_unauthorized_redirects_to_login_view(self):
        self.login_manager.login_view = "login"

        @self.app.route("/login")
        def login():
            return "Login Form Goes Here!"

        with self.app.test_client() as c:
            result = c.get("/secret")
            self.assertEqual(result.status_code, 302)
            self.assertEqual(result.location, "http://localhost/login?next=%2Fsecret")

    def test_unauthorized_uses_blueprint_login_view(self):
        with self.app.app_context():

            first = Blueprint("first", "first")
            second = Blueprint("second", "second")

            @self.app.route("/app_login")
            def app_login():
                return "Login Form Goes Here!"

            @self.app.route("/first_login")
            def first_login():
                return "Login Form Goes Here!"

            @self.app.route("/second_login")
            def second_login():
                return "Login Form Goes Here!"

            @self.app.route("/protected")
            @login_required
            def protected():
                return u"Access Granted"

            @first.route("/protected")
            @login_required
            def first_protected():
                return u"Access Granted"

            @second.route("/protected")
            @login_required
            def second_protected():
                return u"Access Granted"

            self.app.register_blueprint(first, url_prefix="/first")
            self.app.register_blueprint(second, url_prefix="/second")

            set_login_view("app_login")
            set_login_view("first_login", blueprint=first)
            set_login_view("second_login", blueprint=second)

            with self.app.test_client() as c:

                result = c.get("/protected")
                self.assertEqual(result.status_code, 302)
                expected = "http://localhost/" "app_login?next=%2Fprotected"
                self.assertEqual(result.location, expected)

                result = c.get("/first/protected")
                self.assertEqual(result.status_code, 302)
                expected = "http://localhost/" "first_login?next=%2Ffirst%2Fprotected"
                self.assertEqual(result.location, expected)

                result = c.get("/second/protected")
                self.assertEqual(result.status_code, 302)
                expected = "http://localhost/" "second_login?next=%2Fsecond%2Fprotected"
                self.assertEqual(result.location, expected)

    def test_set_login_view_without_blueprints(self):
        with self.app.app_context():

            @self.app.route("/app_login")
            def app_login():
                return "Login Form Goes Here!"

            @self.app.route("/protected")
            @login_required
            def protected():
                return u"Access Granted"

            set_login_view("app_login")

            with self.app.test_client() as c:

                result = c.get("/protected")
                self.assertEqual(result.status_code, 302)
                expected = "http://localhost/app_login?next=%2Fprotected"
                self.assertEqual(result.location, expected)

    #
    # Session Persistence/Freshness
    #
    def test_login_persists(self):
        with self.app.test_client() as c:
            c.get("/login-notch")
            result = c.get("/username")

            self.assertEqual(u"Notch", result.data.decode("utf-8"))

    def test_logout_persists(self):
        with self.app.test_client() as c:
            c.get("/login-notch")
            c.get("/logout")
            result = c.get("/username")
            self.assertEqual(result.data.decode("utf-8"), u"Anonymous")

    def test_incorrect_id_logs_out(self):
        # Ensure that any attempt to reload the user by the ID
        # will seem as if the user is no longer valid
        @self.login_manager.user_loader
        def new_user_loader(user_id):
            return

        with self.app.test_client() as c:
            # Successfully logs in
            c.get("/login-notch")
            result = c.get("/username")

            self.assertEqual(u"Anonymous", result.data.decode("utf-8"))

    def test_authentication_is_fresh(self):
        with self.app.test_client() as c:
            c.get("/login-notch-remember")
            result = c.get("/is-fresh")
            self.assertEqual(u"True", result.data.decode("utf-8"))

    def test_remember_me(self):
        with self.app.test_client() as c:
            c.get("/login-notch-remember")
            self._delete_session(c)
            result = c.get("/username")
            self.assertEqual(u"Notch", result.data.decode("utf-8"))

    def test_remember_me_uses_custom_cookie_parameters(self):
        name = self.app.config["REMEMBER_COOKIE_NAME"] = "myname"
        duration = self.app.config["REMEMBER_COOKIE_DURATION"] = timedelta(days=2)
        path = self.app.config["REMEMBER_COOKIE_PATH"] = "/mypath"
        domain = self.app.config["REMEMBER_COOKIE_DOMAIN"] = ".localhost.local"

        with self.app.test_client() as c:
            c.get("/login-notch-remember")

            # TODO: Is there a better way to test this?
            self.assertIn(domain, c.cookie_jar._cookies, "Custom domain not found as cookie domain")
            domain_cookie = c.cookie_jar._cookies[domain]
            self.assertIn(path, domain_cookie, "Custom path not found as cookie path")
            path_cookie = domain_cookie[path]
            self.assertIn(name, path_cookie, "Custom name not found as cookie name")
            cookie = path_cookie[name]

            expiration_date = datetime.utcfromtimestamp(cookie.expires)
            expected_date = datetime.utcnow() + duration
            difference = expected_date - expiration_date

            fail_msg = "The expiration date {0} was far from the expected {1}"
            fail_msg = fail_msg.format(expiration_date, expected_date)
            self.assertLess(difference, timedelta(seconds=10), fail_msg)
            self.assertGreater(difference, timedelta(seconds=-10), fail_msg)

    def test_remember_me_is_unfresh(self):
        with self.app.test_client() as c:
            c.get("/login-notch-remember")
            self._delete_session(c)
            self.assertEqual(u"False", c.get("/is-fresh").data.decode("utf-8"))

    def test_login_persists_with_signle_x_forwarded_for(self):
        self.app.config["SESSION_PROTECTION"] = "strong"
        with self.app.test_client() as c:
            c.get("/login-notch", headers=[("X-Forwarded-For", "10.1.1.1")])
            result = c.get("/username", headers=[("X-Forwarded-For", "10.1.1.1")])
            self.assertEqual(u"Notch", result.data.decode("utf-8"))
            result = c.get("/username", headers=[("X-Forwarded-For", "10.1.1.1")])
            self.assertEqual(u"Notch", result.data.decode("utf-8"))

    def test_login_persists_with_many_x_forwarded_for(self):
        self.app.config["SESSION_PROTECTION"] = "strong"
        with self.app.test_client() as c:
            c.get("/login-notch", headers=[("X-Forwarded-For", "10.1.1.1")])
            result = c.get("/username", headers=[("X-Forwarded-For", "10.1.1.1")])
            self.assertEqual(u"Notch", result.data.decode("utf-8"))
            result = c.get("/username", headers=[("X-Forwarded-For", "10.1.1.1, 10.1.1.2")])
            self.assertEqual(u"Notch", result.data.decode("utf-8"))

    def test_user_loaded_from_cookie_fired(self):
        with self.app.test_client() as c:
            c.get("/login-notch-remember")
            self._delete_session(c)
            with listen_to(user_loaded_from_cookie) as listener:
                c.get("/username")
                listener.assert_heard_one(self.app, user=notch)

    def test_user_loaded_from_header_fired(self):
        user_id = 1
        user_name = USERS[user_id].name
        self.login_manager.request_callback = None
        with self.app.test_client() as c:
            with listen_to(user_loaded_from_header) as listener:
                headers = [("Authorization", "Basic %s" % (bytes.decode(base64.b64encode(str.encode(str(user_id))))))]
                result = c.get("/username", headers=headers)
                self.assertEqual(user_name, result.data.decode("utf-8"))
                listener.assert_heard_one(self.app, user=USERS[user_id])

    def test_user_loaded_from_request_fired(self):
        user_id = 1
        user_name = USERS[user_id].name
        with self.app.test_client() as c:
            with listen_to(user_loaded_from_request) as listener:
                url = "/username?user_id={user_id}".format(user_id=user_id)
                result = c.get(url)
                self.assertEqual(user_name, result.data.decode("utf-8"))
                listener.assert_heard_one(self.app, user=USERS[user_id])

    def test_logout_stays_logged_out_with_remember_me(self):
        with self.app.test_client() as c:
            c.get("/login-notch-remember")
            c.get("/logout")
            result = c.get("/username")
            self.assertEqual(result.data.decode("utf-8"), u"Anonymous")

    def test_needs_refresh_uses_handler(self):
        @self.login_manager.needs_refresh_handler
        def _on_refresh():
            return u"Needs Refresh!"

        with self.app.test_client() as c:
            c.get("/login-notch-remember")
            result = c.get("/needs-refresh")
            self.assertEqual(u"Needs Refresh!", result.data.decode("utf-8"))

    def test_needs_refresh_fires_needs_refresh_signal(self):
        with self.app.test_client() as c:
            c.get("/login-notch-remember")
            with listen_to(user_needs_refresh) as listener:
                c.get("/needs-refresh")
                listener.assert_heard_one(self.app)

    def test_needs_refresh_fires_flash_when_redirect_to_refresh_view(self):
        self.login_manager.refresh_view = "/refresh_view"

        self.login_manager.needs_refresh_message = u"Refresh"
        self.login_manager.needs_refresh_message_category = "refresh"
        category_filter = [self.login_manager.needs_refresh_message_category]

        with self.app.test_client() as c:
            c.get("/login-notch-remember")
            c.get("/needs-refresh")
            msgs = get_flashed_messages(category_filter=category_filter)
            self.assertIn(self.login_manager.needs_refresh_message, msgs)

    def test_needs_refresh_flash_message_localized(self):
        def _gettext(msg):
            if msg == u"Refresh":
                return u"Aktualisieren"

        self.login_manager.refresh_view = "/refresh_view"
        self.login_manager.localize_callback = _gettext

        self.login_manager.needs_refresh_message = u"Refresh"
        self.login_manager.needs_refresh_message_category = "refresh"
        category_filter = [self.login_manager.needs_refresh_message_category]

        with self.app.test_client() as c:
            c.get("/login-notch-remember")
            c.get("/needs-refresh")
            msgs = get_flashed_messages(category_filter=category_filter)
            self.assertIn(u"Aktualisieren", msgs)
        self.login_manager.localize_callback = None

    def test_needs_refresh_aborts_401(self):
        with self.app.test_client() as c:
            c.get("/login-notch-remember")
            result = c.get("/needs-refresh")
            self.assertEqual(result.status_code, 401)

    def test_redirects_to_refresh_view(self):
        @self.app.route("/refresh-view")
        def refresh_view():
            return ""

        self.login_manager.refresh_view = "refresh_view"
        with self.app.test_client() as c:
            c.get("/login-notch-remember")
            result = c.get("/needs-refresh")
            self.assertEqual(result.status_code, 302)
            expected = "http://localhost/refresh-view?next=%2Fneeds-refresh"
            self.assertEqual(result.location, expected)

    def test_confirm_login(self):
        with self.app.test_client() as c:
            c.get("/login-notch-remember")
            self._delete_session(c)
            self.assertEqual(u"False", c.get("/is-fresh").data.decode("utf-8"))
            c.get("/confirm-login")
            self.assertEqual(u"True", c.get("/is-fresh").data.decode("utf-8"))

    def test_user_login_confirmed_signal_fired(self):
        with self.app.test_client() as c:
            with listen_to(user_login_confirmed) as listener:
                c.get("/confirm-login")
                listener.assert_heard_one(self.app)

    def test_session_not_modified(self):
        with self.app.test_client() as c:
            # Within the request we think we didn't modify the session.
            self.assertEquals(u"modified=False", c.get("/empty_session").data.decode("utf-8"))
            # But after the request, the session could be modified by the
            # "after_request" handlers that call _update_remember_cookie.
            # Ensure that if nothing changed the session is not modified.
            self.assertFalse(session.modified)

    #
    # Session Protection
    #
    def test_session_protection_basic_passes_successive_requests(self):
        self.app.config["SESSION_PROTECTION"] = "basic"
        with self.app.test_client() as c:
            c.get("/login-notch-remember")
            username_result = c.get("/username")
            self.assertEqual(u"Notch", username_result.data.decode("utf-8"))
            fresh_result = c.get("/is-fresh")
            self.assertEqual(u"True", fresh_result.data.decode("utf-8"))

    def test_session_protection_strong_passes_successive_requests(self):
        self.app.config["SESSION_PROTECTION"] = "strong"
        with self.app.test_client() as c:
            c.get("/login-notch-remember")
            username_result = c.get("/username")
            self.assertEqual(u"Notch", username_result.data.decode("utf-8"))
            fresh_result = c.get("/is-fresh")
            self.assertEqual(u"True", fresh_result.data.decode("utf-8"))

    def test_session_protection_basic_marks_session_unfresh(self):
        self.app.config["SESSION_PROTECTION"] = "basic"
        with self.app.test_client() as c:
            c.get("/login-notch-remember")
            username_result = c.get("/username", headers=[("User-Agent", "different")])
            self.assertEqual(u"Notch", username_result.data.decode("utf-8"))
            fresh_result = c.get("/is-fresh")
            self.assertEqual(u"False", fresh_result.data.decode("utf-8"))

    def test_session_protection_basic_fires_signal(self):
        self.app.config["SESSION_PROTECTION"] = "basic"

        with self.app.test_client() as c:
            c.get("/login-notch-remember")
            with listen_to(session_protected) as listener:
                c.get("/username", headers=[("User-Agent", "different")])
                listener.assert_heard_one(self.app)

    def test_session_protection_basic_skips_when_remember_me(self):
        self.app.config["SESSION_PROTECTION"] = "basic"

        with self.app.test_client() as c:
            c.get("/login-notch-remember")
            # clear session to force remember me (and remove old session id)
            self._delete_session(c)
            # should not trigger protection because "sess" is empty
            with listen_to(session_protected) as listener:
                c.get("/username")
                listener.assert_heard_none(self.app)

    def test_session_protection_strong_skips_when_remember_me(self):
        self.app.config["SESSION_PROTECTION"] = "strong"

        with self.app.test_client() as c:
            c.get("/login-notch-remember")
            # clear session to force remember me (and remove old session id)
            self._delete_session(c)
            # should not trigger protection because "sess" is empty
            with listen_to(session_protected) as listener:
                c.get("/username")
                listener.assert_heard_none(self.app)

    def test_permanent_strong_session_protection_marks_session_unfresh(self):
        self.app.config["SESSION_PROTECTION"] = "strong"
        with self.app.test_client() as c:
            c.get("/login-notch-permanent")
            username_result = c.get("/username", headers=[("User-Agent", "different")])
            self.assertEqual(u"Notch", username_result.data.decode("utf-8"))
            fresh_result = c.get("/is-fresh")
            self.assertEqual(u"False", fresh_result.data.decode("utf-8"))

    def test_permanent_strong_session_protection_fires_signal(self):
        self.app.config["SESSION_PROTECTION"] = "strong"

        with self.app.test_client() as c:
            c.get("/login-notch-permanent")
            with listen_to(session_protected) as listener:
                c.get("/username", headers=[("User-Agent", "different")])
                listener.assert_heard_one(self.app)

    def test_session_protection_strong_deletes_session(self):
        self.app.config["SESSION_PROTECTION"] = "strong"
        with self.app.test_client() as c:
            # write some unrelated data in the session, to ensure it does not
            # get destroyed
            with c.session_transaction() as sess:
                sess["foo"] = "bar"
            c.get("/login-notch-remember")
            username_result = c.get("/username", headers=[("User-Agent", "different")])
            self.assertEqual(u"Anonymous", username_result.data.decode("utf-8"))
            with c.session_transaction() as sess:
                self.assertIn("foo", sess)
                self.assertEqual("bar", sess["foo"])

    def test_session_protection_strong_fires_signal_user_agent(self):
        self.app.config["SESSION_PROTECTION"] = "strong"

        with self.app.test_client() as c:
            c.get("/login-notch-remember")
            with listen_to(session_protected) as listener:
                c.get("/username", headers=[("User-Agent", "different")])
                listener.assert_heard_one(self.app)

    def test_session_protection_strong_fires_signal_x_forwarded_for(self):
        self.app.config["SESSION_PROTECTION"] = "strong"

        with self.app.test_client() as c:
            c.get("/login-notch-remember", headers=[("X-Forwarded-For", "10.1.1.1")])
            with listen_to(session_protected) as listener:
                c.get("/username", headers=[("X-Forwarded-For", "10.1.1.2")])
                listener.assert_heard_one(self.app)

    def test_session_protection_skip_when_off_and_anonymous(self):
        with self.app.test_client() as c:
            # no user access
            with listen_to(user_accessed) as user_listener:
                results = c.get("/")
                user_listener.assert_heard_none(self.app)

            # access user with no session data
            with listen_to(session_protected) as session_listener:
                results = c.get("/username")
                self.assertEqual(results.data.decode("utf-8"), u"Anonymous")
                session_listener.assert_heard_none(self.app)

            # verify no session data has been set
            self.assertFalse(session)

    def test_session_protection_skip_when_basic_and_anonymous(self):
        self.app.config["SESSION_PROTECTION"] = "basic"

        with self.app.test_client() as c:
            # no user access
            with listen_to(user_accessed) as user_listener:
                results = c.get("/")
                user_listener.assert_heard_none(self.app)

            # access user with no session data
            with listen_to(session_protected) as session_listener:
                results = c.get("/username")
                self.assertEqual(results.data.decode("utf-8"), u"Anonymous")
                session_listener.assert_heard_none(self.app)

            # verify no session data has been set
            self.assertFalse(session)

    #
    # Custom Token Loader
    #
    def test_custom_token_loader(self):
        @self.login_manager.token_loader
        def load_token(token):
            return USER_TOKENS.get(token)

        with self.app.test_client() as c:
            c.get("/login-notch-remember")
            self._delete_session(c)

            # Test that remember me functionality still works
            self.assertEqual(u"Notch", c.get("/username").data.decode("utf-8"))

            # Test that we used the custom authentication token
            remember_cookie = self._get_remember_cookie(c)
            expected_value = make_secure_token(u"Notch", key="deterministic")
            self.assertEqual(expected_value, remember_cookie.value)

    def test_change_api_key_with_token_loader(self):
        @self.login_manager.token_loader
        def load_token(token):
            return USER_TOKENS.get(token)

        with self.app.test_client() as c:
            c.get("/login-notch-remember")
            self._delete_session(c)
            self.app.config["SECRET_KEY"] = "ima change this now"

            result = c.get("/username")
            self.assertEqual(result.data.decode("utf-8"), u"Notch")

    def test_custom_token_loader_with_no_user(self):
        @self.login_manager.token_loader
        def load_token(token):
            return

        with self.app.test_client() as c:
            c.get("/login-notch-remember")
            self._delete_session(c)

            result = c.get("/username")
            self.assertEqual(result.data.decode("utf-8"), u"Anonymous")

    #
    # Lazy Access User
    #
    def test_requests_without_accessing_session(self):
        with self.app.test_client() as c:
            c.get("/login-notch")

            # no session access
            with listen_to(user_accessed) as listener:
                c.get("/")
                listener.assert_heard_none(self.app)

            # should have a session access
            with listen_to(user_accessed) as listener:
                result = c.get("/username")
                listener.assert_heard_one(self.app)
                self.assertEqual(result.data.decode("utf-8"), u"Notch")

    #
    # View Decorators
    #
    def test_login_required_decorator(self):
        @self.app.route("/protected")
        @login_required
        def protected():
            return u"Access Granted"

        with self.app.test_client() as c:
            result = c.get("/protected")
            self.assertEqual(result.status_code, 401)

            c.get("/login-notch")
            result2 = c.get("/protected")
            self.assertIn(u"Access Granted", result2.data.decode("utf-8"))

    def test_decorators_are_disabled(self):
        @self.app.route("/protected")
        @login_required
        @fresh_login_required
        def protected():
            return u"Access Granted"

        self.app.login_manager._login_disabled = True

        with self.app.test_client() as c:
            result = c.get("/protected")
            self.assertIn(u"Access Granted", result.data.decode("utf-8"))

    def test_fresh_login_required_decorator(self):
        @self.app.route("/very-protected")
        @fresh_login_required
        def very_protected():
            return "Access Granted"

        with self.app.test_client() as c:
            result = c.get("/very-protected")
            self.assertEqual(result.status_code, 401)

            c.get("/login-notch-remember")
            logged_in_result = c.get("/very-protected")
            self.assertEqual(u"Access Granted", logged_in_result.data.decode("utf-8"))

            self._delete_session(c)
            stale_result = c.get("/very-protected")
            self.assertEqual(stale_result.status_code, 401)

            c.get("/confirm-login")
            refreshed_result = c.get("/very-protected")
            self.assertEqual(u"Access Granted", refreshed_result.data.decode("utf-8"))

    #
    # Misc
    #
    @unittest.skipIf(werkzeug_version.startswith("0.9"), "wait for upstream implementing RFC 5987")
    def test_chinese_user_agent(self):
        with self.app.test_client() as c:
            result = c.get("/", headers=[("User-Agent", u"中文")])
            self.assertEqual(u"Welcome!", result.data.decode("utf-8"))

    @unittest.skipIf(werkzeug_version.startswith("0.9"), "wait for upstream implementing RFC 5987")
    def test_russian_cp1251_user_agent(self):
        with self.app.test_client() as c:
            headers = [("User-Agent", u"ЯЙЮя".encode("cp1251"))]
            response = c.get("/", headers=headers)
            self.assertEqual(response.data.decode("utf-8"), u"Welcome!")

    def test_make_secure_token_default_key(self):
        # Old test: 0f05743a2b617b2625362ab667c0dbdf4c9ec13a
        # New test with sha512:
        h1 = "47bec94a46a5d3939ca0671b01bafd5d7d5353941791734ec1e4734de40e5ce0"
        h2 = "a45c05c17cd33b8a18840991bb1cc154fa4ee8ef2f80a572b5a6a24b3a3afc20"
        with self.app.test_request_context():
            self.assertEqual(make_secure_token("foo"), h1 + h2)

    def test_user_context_processor(self):
        with self.app.test_request_context():
            _ucp = self.app.context_processor(_user_context_processor)
            self.assertIsInstance(_ucp()["current_user"], AnonymousUserMixin)
Beispiel #25
0
db.init_app(app)

from calepin.signals import *

from calepin.auth import login_manager

login_manager.setup_app(app)


from calepin.api import api
from calepin.frontend import frontend, context

app.register_blueprint(api, url_prefix="/api")
app.register_blueprint(frontend)

app.context_processor(context)


@app.errorhandler(404)
def page_not_found(e):
    return render_template("404.html"), 404


@app.errorhandler(ErrorResponse)
def dropbox_api_error(error):
    app.logger.warning(str(error))
    return redirect(url_for("frontend.site"))


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 6444)), debug=True)
Beispiel #26
0
@app.route("/data")
def data():
    last = int(request.args.get("l", 0))
    return Response(
        "{{ {} }}".format(",".join('"{}":{}'.format(i + last, x) for i, x in enumerate(db_mem[last:]))),
        mimetype="application/json",
    )


def main():
    dir = "mem-samples.{}".format(int(time.time()))

    os.makedirs(dir)
    i = 0

    procrank_file = open("{}/procrank".format(dir), "w")
    meminfo_file = open("{}/meminfo".format(dir), "w")


if __name__ == "__main__":
    remote_host = sys.argv[1]
    app.context_processor(lambda: dict(remote_host=remote_host))
    thread = GatherThread(remote_host)
    thread.daemon = True
    thread.start()
    # app.run(host='0.0.0.0', debug=True)
    app.run(host="0.0.0.0")
    thread.running = False
    thread.join()
    sys.exit()
Beispiel #27
0
class AppFactory(object):
    """
    Flask application factory.

    >>> from settings import TestingConfig
    >>> app = AppFactory(TestingConfig).get_app(__name__)

    """

    def __init__(self, config, envvar="PROJECT_SETTINGS", bind_db_object=True):
        """
        Defines default application settings

        :param config: an object to load initial configuration from
        :param envvar: The name of an environment variable to update configuration from
        :param bind_db_object:
        """
        self.app_config = config
        self.app_envvar = os.environ.get(envvar, False)
        self.bind_db_object = bind_db_object

    def get_app(self, app_module_name, **kwargs):
        """
        Actually instanciates a Flask application with active settings,
        and taking care of registering extensions and blueprints

        :param app_module_name: the name of the application package, see :py:class:`~flask.Flask`

        :param kwargs: keyword arguments passed to the Flask constructor
        :return: A new WSGI application object
        """
        self.app = Flask(app_module_name, **kwargs)
        self.app.config.from_object(self.app_config)
        self.app.config.from_envvar(self.app_envvar, silent=True)

        self._bind_extensions()
        self._register_blueprints()
        self._register_context_processors()

        return self.app

    def _get_imported_stuff_by_path(self, path):
        """
        Splits a python object's path into `(module, object_name)`,
        and imports the module.

        For example, if `path='base.context_processors.navigation'`,
        then the whole `base.context_processors` module is imported,
        and the method returns the tuple `
        `(base.context_processors, 'navigation')

        :param path: basestring the full path of object
        :return: a tuple of
            * the imported parent module
            * the object name
        """
        module_name, object_name = path.rsplit(".", 1)
        module = import_string(module_name)

        return module, object_name

    def _bind_extensions(self):
        """


        :raise:
        """
        for ext_path in self.app.config.get("EXTENSIONS", []):
            module, e_name = self._get_imported_stuff_by_path(ext_path)
            if not hasattr(module, e_name):
                raise NoExtensionException("No {e_name} extension found".format(e_name=e_name))
            ext = getattr(module, e_name)
            if getattr(ext, "init_app", False):
                ext.init_app(self.app)
            else:
                ext(self.app)

    def _register_context_processors(self):
        """
        Calls :meth:`flask.Flask.context_processor` for all entries
        in the `CONTEXT_PROCESSORS` configuration value, for which defaults
        are set in :mod;`settings`.

        :return:
        """
        for processor_path in self.app.config.get("CONTEXT_PROCESSORS", []):
            module, p_name = self._get_imported_stuff_by_path(processor_path)
            if hasattr(module, p_name):
                self.app.context_processor(getattr(module, p_name))
            else:
                raise NoContextProcessorException("No {cp_name} context processor found".format(cp_name=p_name))

    def _register_blueprints(self):
        """
        Calls :meth:`flask.Flask.register_blueprint` for all entries
        in the `BLUEPRINTS` configuration value, for which defaults
        are set in :mod;`settings`.

        .. todo::
           It is not possible for now to specify settings for the blueprint,
           e.g. `url_prefix`.

        :return:
        """
        for blueprint_path in self.app.config.get("BLUEPRINTS", []):
            module, b_name = self._get_imported_stuff_by_path(blueprint_path)
            if hasattr(module, b_name):
                self.app.register_blueprint(getattr(module, b_name))
            else:
                raise NoBlueprintException("No {bp_name} blueprint found".format(bp_name=b_name))
Beispiel #28
0
import json

settings = {}
with open(os.path.join(os.path.dirname(__file__), "settings.json")) as f:
    settings = json.loads(f.read())

icectf = Flask(__name__)
icectf.config["DEBUG"] = True
icectf.secret_key = settings["cookie_secret"]


def context_processor():
    return dict()


icectf.context_processor(context_processor)


env = assets.Environment(icectf)
env.load_path = [
    os.path.join(os.path.dirname(__file__), "static", "scss"),
    os.path.join(os.path.dirname(__file__), "static", "coffee"),
    os.path.join(os.path.dirname(__file__), "static"),
]
env.register(
    "js_comp",
    assets.Bundle(
        "components/js/jquery/jquery.min.js",
        "components/js/underscore/underscore.js",
        "components/js/materialize/materialize.js",
        "components/js/timecircles/TimeCircles.js",
Beispiel #29
0
class AppFactory(object):

    """Create a Flask app (Flask Application Factory)."""

    def __init__(self):
        super(AppFactory, self).__init__()

        self.app_config = None
        self.app = None

    def __call__(self, app_name=None, config=None, config_obj=None, **kwargs):
        # initialize the application
        self.app_config = config
        self.app = Flask(app_name or DevelopmentConfig.PROJECT, instance_relative_config=True, **kwargs)

        self._configure_app(config_obj=config_obj)
        self._bind_extensions()
        self._register_blueprints()
        self._configure_logging()
        self._configure_template_filters()
        self._configure_error_handlers()

        return self.app

    def _configure_app(self, config_obj=None):
        """Configure the app in different ways."""
        # http://flask.pocoo.org/docs/api/#configuration
        self.app.config.from_object(config_obj or DevelopmentConfig)

        # user custom config
        # http://flask.pocoo.org/docs/config/#instance-folders
        default_config = os.path.join(self.app.instance_path, "{}.cfg".format(self.app.name))
        self.app.config.from_pyfile(self.app_config or default_config, silent=True)

    def _bind_extensions(self):
        """Bind extensions to the app dynamically."""
        for ext_path in self.app.config.get("EXTENSIONS", []):
            module, object_name = get_imported_stuff_by_path(ext_path)

            if not hasattr(module, object_name):
                raise NoExtensionException("No {} extension found".format(object_name))

            extension = getattr(module, object_name)

            if getattr(extension, "init_app", False):
                extension.init_app(self.app)

            else:
                extension(self.app)

    def _register_blueprints(self):
        """Configure blueprints in views."""
        for blueprint_path, url_prefix in self.app.config.get("BLUEPRINTS", []):
            module, object_name = get_imported_stuff_by_path(blueprint_path)

            if hasattr(module, object_name):
                self.app.register_blueprint(getattr(module, object_name), url_prefix=url_prefix)

            else:
                raise NoBlueprintException("No {} blueprint found".format(object_name))

    def _register_context_processors(self):
        """Register extra contexts for Jinja templates."""
        for processor_path in self.app.config.get("CONTEXT_PROCESSORS", []):
            module, object_name = get_imported_stuff_by_path(processor_path)

            if hasattr(module, object_name):
                self.app.context_processor(getattr(module, object_name))

            else:
                raise NoContextProcessorException("No {} context processor found".format(object_name))

    def _configure_logging(self):
        """Configure file(info) and email(error) logging"""
        if self.app.debug or self.app.testing:
            # Skip debug and test mode; just check standard output
            return

        import logging
        from .log import TlsSMTPHandler

        # Set info level on logger which might be overwritten by handlers
        # Suppress DEBUG messages
        self.app.logger.setLevel(logging.INFO)

        stream_handler = logging.StreamHandler()
        stream_handler.setLevel(logging.INFO)
        stream_handler.setFormatter(
            logging.Formatter("%(asctime)s - %(name)s - %(levelname)s: %(message)s " "[in %(pathname)s:%(lineno)d]")
        )
        self.app.logger.addHandler(stream_handler)

        # also write default Weekzeug log (INFO) to the main log-file
        # note: this is only relevant when not running behind gunicorn
        werkzeug_log = logging.getLogger("werkzeug")
        werkzeug_log.setLevel(logging.INFO)
        werkzeug_log.addHandler(stream_handler)

        mail_handler = TlsSMTPHandler(
            mailhost=self.app.config["MAIL_SERVER"],
            fromaddr=self.app.config["MAIL_USERNAME"],
            toaddrs=self.app.config["ADMINS"],
            subject="O_ops... {} failed!".format(self.app.name),
            credentials=(self.app.config["MAIL_USERNAME"], self.app.config["MAIL_PASSWORD"]),
        )
        mail_handler.setLevel(logging.ERROR)
        mail_handler.setFormatter(
            logging.Formatter("%(asctime)s - %(name)s - %(levelname)s: %(message)s " "[in %(pathname)s:%(lineno)d]")
        )
        self.app.logger.addHandler(mail_handler)
        werkzeug_log.addHandler(mail_handler)

    def _configure_error_handlers(self):
        """Configure error handlers to the corresponding error pages."""

        @self.app.errorhandler(403)
        def forbidden_page(error):
            """Render the forbidden error page on 403 errors."""
            return render_template("errors/forbidden_page.html", error=error), 403

        @self.app.errorhandler(404)
        def page_not_found(error):
            """Render the page not found page on 404 errors."""
            return render_template("errors/page_not_found.html", error=error), 404

        @self.app.errorhandler(500)
        def server_error_page(error):
            """Render the server error page on 500 errors."""
            return render_template("errors/server_error.html", error=error), 500

    def _configure_template_filters(self):
        """Configure custom Jinja2 template filters."""

        @self.app.template_filter()
        def human_date(value):
            time_zone = current_app.config["TIME_ZONE"]
            return arrow.get(value).replace(tzinfo=dateutil.tz.gettz(time_zone)).humanize()

        @self.app.template_filter()
        def format_date(value, format="%Y-%m-%d"):
            return value.strftime(format)

        @self.app.template_filter()
        def initials(value):
            parts = value.split(" ")
            letters = (part[0] for part in parts)
            return "".join(letters)

        @self.app.template_filter()
        def client_filter(value):
            """Pass through variable in Jinja2 to client side template.

      The filter tells Jinja2 that a variable is for a client side
      template engine.

      If the variable is undefined, its name will be used in the
      client side template, otherwise, its content will be used.
      """

            if is_undefined(value):
                return "{{{{{}}}}}".format(value._undefined_name)
            if type(value) is bool:
                value = repr(value).lower()
            return "{{{{{}}}}}".format(value)

        @self.app.template_filter()
        def human_decimal(number, ndigits=4):
            """Return a standard representation of a decimal number.

      Args:
        number (float): number to humanize
        ndigits (int, optional): max number of digits to round to

      Return:
        str: humanized string of the decimal number
      """
            min_number = 10 ^ -ndigits

            if number is None:
                # NaN
                return "-"
            elif number == 0:
                # avoid confusion over what is rounded and what is actually 0
                return 0
            elif number < min_number:
                # make human readable and sane
                return "&lt; {}".format(min_number)
            else:
                # round all other numbers
                return round(number, ndigits)

        @self.app.template_filter()
        def url_decode(string):
            """Decode a string with encoded hex values."""
            return urllib2.unquote(string)
Beispiel #30
0
def create_app(cyd=None):
    """Create the web interface WSGI application"""

    if cyd is None:
        cyd = cydra.Cydra()

    from flask import Flask
    from flaskext.csrf import csrf
    from cydra.web.themes import IThemeProvider, ThemedTemplateLoader, patch_static

    app = Flask(__name__)

    # register themes
    theme_providers = ExtensionPoint(IThemeProvider, component_manager=cyd)
    app.config["cydra_themes"] = dict([(theme.name, theme) for theme in theme_providers.get_themes()])

    default_theme = cyd.config.get("web").get("default_theme")
    if default_theme is not None and default_theme in app.config["cydra_themes"]:
        default_theme = app.config["cydra_themes"][default_theme]
        logger.debug("Default theme: %s", default_theme.name)
    else:
        default_theme = None
    theme_detector = ThemeDetector(default_theme)
    app.before_request(theme_detector)

    # replace default loader
    app.jinja_options = Flask.jinja_options.copy()
    app.jinja_options["loader"] = ThemedTemplateLoader(app)

    # patch static file resolver
    patch_static(app)

    # secret key for cookies
    app.secret_key = os.urandom(24)

    # consider the cydra instance to be a form of configuration
    # and therefore store it in the config dict.
    app.config["cydra"] = cyd

    # common views
    app.add_url_rule("/login", "login", login)

    # Add shorthands to context
    app.context_processor(add_shorthands_to_context)

    # load frontend and backend
    from cydra.web.frontend import blueprint as frontend_blueprint

    patch_static(frontend_blueprint, "frontend")
    # from cydra.web.admin import blueprint as admin_blueprint
    # patch_static(admin_blueprint, 'admin')

    app.register_blueprint(frontend_blueprint)
    # app.register_blueprint(admin_blueprint)

    # load additional blueprints
    pages = ExtensionPoint(IBlueprintProvider, component_manager=cyd)
    for bpprovider in pages:
        bp = bpprovider.get_blueprint()
        patch_static(bp, bp.name)
        app.register_blueprint(bp)

    # some utility template filters
    from cydra.web.filters import filters

    # map(app.template_filter(), filters)
    _ = [app.template_filter()(f) for f in filters]

    # prevent flask from handling exceptions
    app.debug = True

    # add CSRF protection
    csrf(app)

    # wrap in authentication middleware
    from cydra.web.wsgihelper import AuthenticationMiddleware

    app = AuthenticationMiddleware(cyd, app)

    # enable debugging for certain users
    debugusers = cyd.config.get("web").get("debug_users", [])
    if debugusers:
        from cydra.web.debugging import DebuggingMiddleware

        app = DebuggingMiddleware(app, debugusers)

    return app