Ejemplo n.º 1
0
SESSION_OPTIONS = {
    'session.auto': True,
    'session.cookie_expires': False,
    #This is a security risk if this is false as it means that if
    #anyone gets access to your session cookie or just uses your
    #computer while your away, they'll be able to access your
    #account details.
    #
    #There is usually a balance between usability and security
    #as it will be annoying to login too often.
    #
    #for the purpose of this tutorial, I'm leaving it as false.
}

#Add Beakers Session management
application = SessionMiddleware(app, SESSION_OPTIONS)

if __name__ == '__main__':
    #Actually start running the application. If run from here, it will be using
    #the debug server. Run this module externally and use 'application' to start.

    print "Starting Message Board App..."

    if len(sys.argv) > 1:
        if sys.argv[1] == '--init-db':
            #We're going to drop tables if they exists
            #then create them.
            #This will reset all topics and messages
            import SQLiteAdapter
            SQLiteAdapter.initialize_db()
Ejemplo n.º 2
0
    if domain:
        session.domain = domain
    if not environ['PATH_INFO'].startswith('/nosave'):
        session.save()
    start_response('200 OK', [('Content-type', 'text/plain')])
    msg = 'The current value is: %d and cookie is %s' % (session['value'], session)
    return [msg.encode('utf-8')]


def test_increment():
    options = {'session.validate_key':'hoobermas',
               'session.type':'cookie'}
    app = TestApp(SessionMiddleware(simple_app, **options))
    res = app.get('/')
    assert 'current value is: 1' in res

    res = app.get('/', extra_environ=dict(domain='.hoop.com',
                                          HTTP_HOST='www.hoop.com'))
    assert 'current value is: 1' in res
    assert 'Domain=.hoop.com' in res.headers['Set-Cookie']

    res = app.get('/', extra_environ=dict(HTTP_HOST='www.hoop.com'))
    assert 'Domain=.hoop.com' in res.headers['Set-Cookie']
    assert 'current value is: 2' in res


if __name__ == '__main__':
    from paste import httpserver
    wsgi_app = SessionMiddleware(simple_app, {})
    httpserver.serve(wsgi_app, host='127.0.0.1', port=8080)
Ejemplo n.º 3
0
        'session.type':
        'memory',
        'session.cookie_expires':
        True,
        'session.auto':
        True,
        'session.key':
        "{}.beaker.session.id".format(
            urlparse.urlparse(conf.BASE).netloc.replace(":", "."))
    }

    CLIENTS = OIDCClients(conf)
    SERVER_ENV.update({"template_lookup": LOOKUP, "base_url": conf.BASE})

    SRV = wsgiserver.CherryPyWSGIServer(
        ('0.0.0.0', int(args.port)),
        SessionMiddleware(application, session_opts))

    if conf.BASE.startswith("https"):
        from cherrypy.wsgiserver import ssl_pyopenssl

        SRV.ssl_adapter = ssl_pyopenssl.pyOpenSSLAdapter(
            conf.SERVER_CERT, conf.SERVER_KEY, conf.CA_BUNDLE)

    LOGGER.info("RP server starting listening on port:%s" % args.port)
    print("RP server starting listening on port:%s" % args.port)
    try:
        SRV.start()
    except KeyboardInterrupt:
        SRV.stop()
Ejemplo n.º 4
0
def make_app(global_conf, full_stack=True, static_files=True, **app_conf):
    """Create a Pylons WSGI application and return it

    ``global_conf``
        The inherited configuration for this application. Normally from
        the [DEFAULT] section of the Paste ini file.

    ``full_stack``
        Whether this application provides a full WSGI stack (by default,
        meaning it handles its own exceptions and errors). Disable
        full_stack when this application is "managed" by another WSGI
        middleware.

    ``static_files``
        Whether this application serves its own static files; disable
        when another web server is responsible for serving them.

    ``app_conf``
        The application's local configuration. Normally specified in
        the [app:<name>] section of the Paste ini file (where <name>
        defaults to main).

    """
    # Configure the Pylons environment
    config = load_environment(global_conf, app_conf)
    alembic_migrations = MediaDropMigrator.from_config(config, log=log)
    db_is_current = True
    if not alembic_migrations.is_db_scheme_current():
        log.warn(
            'Running with an outdated database scheme. Please upgrade your database.'
        )
        db_is_current = False
    plugin_mgr = config['pylons.app_globals'].plugin_mgr
    db_current_for_plugins = plugin_mgr.is_db_scheme_current_for_all_plugins()
    if db_is_current and not db_current_for_plugins:
        log.warn(db_current_for_plugins.message)
        db_is_current = False
    if db_is_current:
        events.Environment.database_ready()

    # The Pylons WSGI app
    app = PylonsApp(config=config)

    # Allow the plugin manager to tweak our WSGI app
    app = plugin_mgr.wrap_pylons_app(app)

    # Routing/Session/Cache Middleware
    app = RoutesMiddleware(app, config['routes.map'], singleton=False)
    app = SessionMiddleware(app, config)

    # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)

    # add repoze.who middleware with our own authorization library
    app = add_auth(app, config)

    # ToscaWidgets Middleware
    app = setup_tw_middleware(app, config)

    # Strip the name of the .fcgi script, if using one, from the SCRIPT_NAME
    app = FastCGIScriptStripperMiddleware(app)

    # If enabled, set up the proxy prefix for routing behind
    # fastcgi and mod_proxy based deployments.
    if config.get('proxy_prefix', None):
        app = setup_prefix_middleware(app, global_conf, config['proxy_prefix'])

    # END CUSTOM MIDDLEWARE

    if asbool(full_stack):
        # Handle Python exceptions
        app = ErrorHandler(app, global_conf, **config['pylons.errorware'])

        # by default Apache uses  a global alias for "/error" in the httpd.conf
        # which means that users can not send error reports through MediaDrop's
        # error page (because that POSTs to /error/report).
        # To make things worse Apache (at least up to 2.4) has no "unalias"
        # functionality. So we work around the issue by using the "/errors"
        # prefix (extra "s" at the end)
        error_path = '/errors/document'
        # Display error documents for 401, 403, 404 status codes (and
        # 500 when debug is disabled)
        if asbool(config['debug']):
            app = StatusCodeRedirect(app, path=error_path)
        else:
            app = StatusCodeRedirect(app,
                                     errors=(400, 401, 403, 404, 500),
                                     path=error_path)

    # Cleanup the DBSession only after errors are handled
    app = DBSessionRemoverMiddleware(app)

    # Establish the Registry for this application
    app = RegistryManager(app)

    app = setup_db_sanity_checks(app, config)

    if asbool(static_files):
        # Serve static files from our public directory
        public_app = StaticURLParser(config['pylons.paths']['static_files'])

        static_urlmap = URLMap()
        # Serve static files from all plugins
        for dir, path in plugin_mgr.public_paths().iteritems():
            static_urlmap[dir] = StaticURLParser(path)

        # Serve static media and podcast images from outside our public directory
        for image_type in ('media', 'podcasts'):
            dir = '/images/' + image_type
            path = os.path.join(config['image_dir'], image_type)
            static_urlmap[dir] = StaticURLParser(path)

        # Serve appearance directory outside of public as well
        dir = '/appearance'
        path = os.path.join(config['app_conf']['cache_dir'], 'appearance')
        static_urlmap[dir] = StaticURLParser(path)

        # We want to serve goog closure code for debugging uncompiled js.
        if config['debug']:
            goog_path = os.path.join(config['pylons.paths']['root'], '..',
                                     'closure-library', 'closure', 'goog')
            if os.path.exists(goog_path):
                static_urlmap['/scripts/goog'] = StaticURLParser(goog_path)

        app = Cascade([public_app, static_urlmap, app])

    if asbool(config.get('enable_gzip', 'true')):
        app = setup_gzip_middleware(app, global_conf)

    app.config = config
    return app
Ejemplo n.º 5
0
def make_app(global_conf, full_stack=True, static_files=True, **app_conf):
    """Create a Pylons WSGI application and return it

    ``global_conf``
        The inherited configuration for this application. Normally from
        the [DEFAULT] section of the Paste ini file.

    ``full_stack``
        Whether this application provides a full WSGI stack (by default,
        meaning it handles its own exceptions and errors). Disable
        full_stack when this application is "managed" by another WSGI
        middleware.

    ``static_files``
        Whether this application serves its own static files; disable
        when another web server is responsible for serving them.

    ``app_conf``
        The application's local configuration. Normally specified in
        the [app:<name>] section of the Paste ini file (where <name>
        defaults to main).

    """
    # Configure the Pylons environment
    load_environment(global_conf, app_conf)

    # The Pylons WSGI app
    app = PylonsApp()

    for plugin in PluginImplementations(IMiddleware):
        app = plugin.make_middleware(app, config)

    # Routing/Session/Cache Middleware
    app = RoutesMiddleware(app, config['routes.map'])
    app = SessionMiddleware(app, config)
    app = CacheMiddleware(app, config)

    # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)
    #app = QueueLogMiddleware(app)

    if asbool(full_stack):
        # Handle Python exceptions
        app = ErrorHandler(app, global_conf, **config['pylons.errorware'])

        # Display error documents for 401, 403, 404 status codes (and
        # 500 when debug is disabled)
        if asbool(config['debug']):
            app = StatusCodeRedirect(app, [400, 404])
        else:
            app = StatusCodeRedirect(app, [400, 404, 500])

    # Initialize repoze.who
    who_parser = WhoConfig(global_conf['here'])
    who_parser.parse(open(app_conf['who.config_file']))

    if asbool(config.get('openid_enabled', 'true')):
        from repoze.who.plugins.openid.identification import OpenIdIdentificationPlugin
        # Monkey patches for repoze.who.openid
        # Fixes #1659 - enable log-out when CKAN mounted at non-root URL
        from ckan.lib import repoze_patch
        OpenIdIdentificationPlugin.identify = repoze_patch.identify
        OpenIdIdentificationPlugin.redirect_to_logged_in = repoze_patch.redirect_to_logged_in
        OpenIdIdentificationPlugin._redirect_to_loginform = repoze_patch._redirect_to_loginform
        OpenIdIdentificationPlugin.challenge = repoze_patch.challenge

        who_parser.identifiers = [i for i in who_parser.identifiers if \
                not isinstance(i, OpenIdIdentificationPlugin)]
        who_parser.challengers = [i for i in who_parser.challengers if \
                not isinstance(i, OpenIdIdentificationPlugin)]

    app = PluggableAuthenticationMiddleware(
        app,
        who_parser.identifiers,
        who_parser.authenticators,
        who_parser.challengers,
        who_parser.mdproviders,
        who_parser.request_classifier,
        who_parser.challenge_decider,
        logging.getLogger('repoze.who'),
        logging.WARN,  # ignored
        who_parser.remote_user_key,
    )

    # Establish the Registry for this application
    app = RegistryManager(app)

    if asbool(static_files):
        # Serve static files
        static_max_age = None if not asbool(config.get('ckan.cache_enabled')) \
            else int(config.get('ckan.static_max_age', 3600))

        static_app = StaticURLParser(config['pylons.paths']['static_files'],
                                     cache_max_age=static_max_age)
        static_parsers = [static_app, app]

        # Configurable extra static file paths
        extra_static_parsers = []
        for public_path in config.get('extra_public_paths', '').split(','):
            if public_path.strip():
                extra_static_parsers.append(
                    StaticURLParser(public_path.strip(),
                                    cache_max_age=static_max_age))
        app = Cascade(extra_static_parsers + static_parsers)

    return app
Ejemplo n.º 6
0
    distributor_wallet = j.clients.stellar.get(FAUCET_WALLET)

    asset = distributor_wallet.get_asset("TFT")  # asset.code:asset.issuer
    import nacl
    from nacl import hash

    hashed_wallet = hash.blake2b(destination.encode("utf-8"),
                                 encoder=nacl.encoding.RawEncoder)
    txes = distributor_wallet.list_transactions(address=destination)
    for tx in txes:
        if tx.memo_hash is not None:
            decoded_memo_hash = base64.b64decode(tx.memo_hash)
            if decoded_memo_hash == hashed_wallet:
                raise j.exceptions.Base("user already requested tokens")

    try:
        distributor_wallet.transfer(
            destination_address=destination,
            amount=TRANSFER_AMOUNT,
            asset=f"{asset.code}:{asset.issuer}",
            memo_hash=hashed_wallet,
        )
    except Exception as e:
        raise j.exceptions.Base(e)

    return j.data.serializers.json.dumps({"data": "Transfer complete"})


app = SessionMiddleware(app, SESSION_OPTS)
Ejemplo n.º 7
0
import json
import html
import yaml
import bcrypt
import requests
import shutil
from bottle import app, route, template, static_file, redirect, abort, request, response
from beaker.middleware import SessionMiddleware
from steam_buddy.config import PLATFORMS, SSH_KEY_HANDLER, AUTHENTICATOR, SETTINGS_HANDLER, STEAMGRID_HANDLER, FTP_SERVER, RESOURCE_DIR, BANNER_DIR, CONTENT_DIR, SHORTCUT_DIR, UPLOADS_DIR, SESSION_OPTIONS
from steam_buddy.functions import load_shortcuts, sanitize, upsert_file, delete_file, generate_banner
from steam_buddy.auth_decorator import authenticate
from steam_buddy.platforms.epic_store import EpicStore
from steam_buddy.platforms.flathub import Flathub
from steam_buddy.platforms.gog import GOG

server = SessionMiddleware(app(), SESSION_OPTIONS)

tmpfiles = {}

PLATFORM_HANDLERS = {
    "epic-store": EpicStore(),
    "flathub": Flathub(),
    "gog": GOG(),
}


def authenticate_platform(selected_platform):
    if selected_platform in PLATFORM_HANDLERS:
        if not PLATFORM_HANDLERS[selected_platform].is_authenticated():
            redirect(
                '/platforms/{platform}'.format(platform=selected_platform))
Ejemplo n.º 8
0
from up_admin import app_user_list
from up_admin import app_psn_list
from up_admin import app_psn_add
from up_admin import app_psn_channel_suggestions

from up_kickbot import app_kickbot

app = selector.Selector()
app.add('/userpage/slackauth', GET=app_slackauth)
app.add('/userpage/logout', POST=valid_session(app_logout))
app.add('/userpage/privs', GET=valid_session(app_privs))
app.add('/userpage/profile', GET=valid_session(app_profile))

app.add('/userpage/user', GET=admin_session(app_user_list))
app.add('/userpage/psn', GET=admin_session(app_psn_list))
app.add('/userpage/psn/add', POST=admin_session(app_psn_add))
app.add('/userpage/suggest/psn_channel',
        GET=admin_session(app_psn_channel_suggestions))

app.add('/kickbot/slackendpoint', POST=app_kickbot)

beaker_config = {
    'session.key': 'id',
    'session.type': 'file',
    'session.data_dir': '/var/easn/userpage/beaker',
    'session.cookie_expires': 'true',
    'session.secure': 'true'
}

application = SessionMiddleware(app, beaker_config)
Ejemplo n.º 9
0
                session['functions'] = [
                    tex._['functions'][fn]['math'] for fn in tex._['functions']
                ]
                session['history'] = tex.history
            except (ValueError, SyntaxError, IndexError) as err:
                status = '400 Bad Request'
                output = 'Invalid Tex'
    else:
        status = '500 Internal Server Error'
        output = status

    output = output.encode('utf-8')

    headers = [('Content-type', content_type),
               ('Access-control-allow-origin', '*'),
               ('Content-Length', str(len(output)))]

    session.save()

    start_response(status, headers)
    return [output]


wsgi_app = SessionMiddleware(
    app, {
        'session.type': 'file',
        'session.cookie_expires': True,
        'session.data_dir': '/tmp'
    })

serve(wsgi_app)
Ejemplo n.º 10
0
    'session.timeout': 60
}

# Adapt beaker interface to Flask sessions
class BeakerSessionInterface(SessionInterface):
    def open_session(self, app, request):
        session = request.environ['beaker.session']
        return session

    def save_session(self, app, session, response):
        session.save()

application = flask.Flask(__name__)
application.config.from_object("settings")
# wrap Flask WSGI application in Beaker session WSGI middleware
application.wsgi_app = SessionMiddleware(application.wsgi_app, session_opts)
application.session_interface = BeakerSessionInterface()

@application.route('/')
def show_entries():
    cursor = g.db.cursor()
    cursor.execute("SELECT title, body, posted_at, posted_by, @@session.time_zone as timezone FROM entries ORDER BY id DESC")
    entries = [dict(title=row[0], text=row[1], posted_at=row[2], posted_by=row[3], timezone=row[4]) for row in cursor.fetchall()]
    return render_template('show_entries.html', entries=entries)

@application.route('/add', methods=['POST'])
def add_entry():
    if not session.get('logged_in'):
        abort(401)
    cursor = g.db.cursor()
    cursor.execute("INSERT INTO entries (title, body, posted_at, posted_by) VALUES (%s, %s, NOW(), %s)",
Ejemplo n.º 11
0
def test_no_save():
    options = {'session.data_dir': './cache', 'session.secret': 'blah'}
    app = TestApp(SessionMiddleware(no_save_app, **options))
    res = app.get('/')
    assert 'current value is: None' in res
    assert [] == res.headers.getall('Set-Cookie')
Ejemplo n.º 12
0
from beaker.middleware import SessionMiddleware

file_path = './test'

session_opts = {
    'session.cookie_expires': False,
    'session.encrypt_key':
    'bpvSpCLaswxnSwmCifsEnnWIGXtqTiaUWhjIIkrNeplDqsaBIF',
    'session.httponly': True,
    'session.type': 'cookie',
    'session.validate_key': True
}

cork = Cork('authconf')
auth = cork.make_auth_decorator(fail_redirect='/login', role='admin')
app = SessionMiddleware(make_app(), session_opts)

file = Path(file_path)
file.touch()
with file.open(newline='') as f:
    text = f.read()
    filesep = ([sep
                for sep in ['\r\n', '\r', '\n'] if sep in text] + [linesep])[0]


@get('/login')
def login_form():
    return template('login')


@post('/login')
Ejemplo n.º 13
0
    **This function doesn't need to be changed.**

    """
    return static_file(path, root="assets")


# Configuration options for sessions.
# Used by alerts module
session_options = {
    'session.type': 'cookie',
    'session.validate_key': 'super-secret'
}

# Configures the app to use sessions middleware
message_app = app()
message_app = SessionMiddleware(message_app, session_options)

if __name__ == '__main__':
    # Set up a command line argument parser
    parser = argparse.ArgumentParser(
        description='Run the RocketTalk Messaging Application')

    # A required --port argument, so that the user knows which port
    # they're binding to.
    parser.add_argument('--port',
                        type=int,
                        required=True,
                        help='The port number to listen on.')

    # Allow the user to specify a hostname, defaulting to 0.0.0.0
    # (i.e., "Bind to all network interfaces")
Ejemplo n.º 14
0
 def __init__(self, app):
     self.app = SessionMiddleware(app, _session_opts)
     self.nacl = j.data.nacl.default
Ejemplo n.º 15
0
    return redirect('/user')

#after user login, they will stay on the same page (query_page || result_page)
@route('/user')
def user_login():
    session = request.environ.get('beaker.session')
    if current_page == 'query_page':
        return template('./templates/query_page.tpl', login = True, 
            user_email = session["user_email"], recent_words = user_recent_words_index.get_recent_words(session["user_email"]))
    else:
        return template('./templates/result_page.tpl', keywords = keywords, words_count = words_count, corrected_keywords=corrected_keywords,
            login = True, user_email = session["user_email"], recent_words = user_recent_words_index.get_recent_words(session["user_email"]),
            history = user_history_index.get_history(session["user_email"]).get_popular(),first_word = first_word, document = document, 
            cur_page_num = cur_page_num, num_per_page = num_per_page, page_num_counts = page_num_counts,calculation_result = calculation_result)

# routes of assets (css, js, images)
@route('/assets/<filename:path>')
def send_assets(filename):
    return static_file(filename, root='./assets')

# route of templates
@route('/templates/<filename:path>')
def send_templates(filename):
    return static_file(filename, root='./templates')

if __name__ == "__main__":
    app = SessionMiddleware(app(), sessions_opts)
    # run server
    run(app=app, host='localhost', port=8081, debug=True)
Ejemplo n.º 16
0
@app.route('/sitemap.xml')
def sitemap(db):
	response.content_type = 'application/xml'
	return template('sitemap', db=db)



# and now, setup the session middleware

@app.hook('before_request')
def setup_request():
	request.session = request.environ['beaker.session']

app = SessionMiddleware(app, {
	'session.type': 'file',
	'session.data_dir': './session/',
	'session.auto': True
})


if __name__ == '__main__':
	import socket
	if socket.gethostname() == 'pip':
		bottle.run(app=app, host='efw27.user.srcf.net', port=8898, server='cherrypy')
	else:
		bottle.run(app=app, host='localhost', port=8080, debug=True, reloader=True)
else:
	bottle.debug(True)

Ejemplo n.º 17
0

@route('/issn')
def issn():
    return template("/home/JackZhang1012/mysite/modulus")


@route('/modulus', method="POST")
def modulus_app():
    weight = [8, 7, 6, 5, 4, 3, 2]
    issn = str(request.forms.get("issn"))
    if len(issn) == 7:
        thesum = 0
        for i in range(0, 7):
            thesum += weight[i] * int(issn[i])
        d = 11 - thesum % 11
        issn += str(d)
        parameters = {"issnresult": "Full ISSN is " + issn}
        return template("/home/JackZhang1012/mysite/issnresult", parameters)
    else:
        return template("/home/JackZhang1012/mysite/issnresultr")


#application = default_app()
application = SessionMiddleware(default_app(), session_opts)


@error(404)
def errorredirect(error):
    return template("/home/JackZhang1012/mysite/errorredirect")
Ejemplo n.º 18
0
    join(PYLOAD_DIR, "locale"),
    languages=[config.get("general", "language"), "en"],
    fallback=True)
translation.install(True)
env.install_gettext_translations(translation)

from beaker.middleware import SessionMiddleware

session_opts = {
    'session.type': 'file',
    'session.cookie_expires': False,
    'session.data_dir': './tmp',
    'session.auto': False
}

web = StripPathMiddleware(SessionMiddleware(app(), session_opts))
web = GZipMiddleWare(web)

if PREFIX:
    web = PrefixMiddleware(web, prefix=PREFIX)

import pyload.webui.app


def run_simple(host="0.0.0.0", port="8000"):
    run(app=web, host=host, port=port, quiet=True)


def run_lightweight(host="0.0.0.0", port="8000"):
    run(app=web, host=host, port=port, server="bjoern", quiet=True)
import os
import click
from bottle import static_file, Bottle, run, TEMPLATE_PATH
from beaker.middleware import SessionMiddleware

from super_bottle import settings
from super_bottle.routes import Routes


TEMPLATE_PATH.insert(0, settings.TEMPLATE_PATH)
session_opts = {
    'session.type': 'file',
    'session.auto': True
}

app = SessionMiddleware(Bottle(), session_opts)

# Bottle Routes
app.wrap_app.merge(Routes)


@app.wrap_app.route('/assets/<path:path>', name='assets')
def assets(path):
    yield static_file(path, root=settings.STATIC_PATH)


@click.group()
def cmds():
    pass

Ejemplo n.º 20
0
def _make_core_app(root, global_conf, full_stack=True, **app_conf):
    """
    Set allura up with the settings found in the PasteDeploy configuration
    file used.

    :param root: The controller module containing the TG root
    :param global_conf: The global settings for allura (those
        defined under the ``[DEFAULT]`` section).
    :type global_conf: dict
    :param full_stack: Should the whole TG2 stack be set up?
    :type full_stack: str or bool
    :return: The allura application with all the relevant middleware
        loaded.

    This is the PasteDeploy factory for the allura application.

    ``app_conf`` contains all the application-specific settings (those defined
    under ``[app:main]``.


    """
    # Run all the initialization code here
    mimetypes.init([pkg_resources.resource_filename('allura', 'etc/mime.types')] + mimetypes.knownfiles)

    # Configure MongoDB
    ming.configure(**app_conf)

    # Configure ActivityStream
    if asbool(app_conf.get('activitystream.recording.enabled', False)):
        activitystream.configure(**h.convert_bools(app_conf, prefix='activitystream.'))

    # Configure EW variable provider
    ew.render.TemplateEngine.register_variable_provider(get_tg_vars)

    # Set FormEncode language to english, as we don't support any other locales
    formencode.api.set_stdtranslation(domain='FormEncode', languages=['en'])

    # Create base app
    base_config = ForgeConfig(root)
    load_environment = base_config.make_load_environment()

    # Code adapted from tg.configuration, replacing the following lines:
    #     make_base_app = base_config.setup_tg_wsgi_app(load_environment)
    #     app = make_base_app(global_conf, full_stack=True, **app_conf)

    # Configure the Pylons environment
    load_environment(global_conf, app_conf)

    app = tg.TGApp()

    for mw_ep in h.iter_entry_points('allura.middleware'):
        Middleware = mw_ep.load()
        if getattr(Middleware, 'when', 'inner') == 'inner':
            app = Middleware(app, config)

    # Required for pylons
    app = RoutesMiddleware(app, config['routes.map'])
    # Required for sessions
    app = SessionMiddleware(app, config)
    # Handle "Remember me" functionality
    app = RememberLoginMiddleware(app, config)
    # Redirect 401 to the login page
    app = LoginRedirectMiddleware(app)
    # Add instrumentation
    app = AlluraTimerMiddleware(app, app_conf)
    # Clear cookies when the CSRF field isn't posted
    if not app_conf.get('disable_csrf_protection'):
        app = CSRFMiddleware(app, '_session_id')
    if asbool(config.get('cors.enabled', False)):
        # Handle CORS requests
        allowed_methods = aslist(config.get('cors.methods'))
        allowed_headers = aslist(config.get('cors.headers'))
        cache_duration = asint(config.get('cors.cache_duration', 0))
        app = CORSMiddleware(app, allowed_methods, allowed_headers, cache_duration)
    # Setup the allura SOPs
    app = allura_globals_middleware(app)
    # Ensure http and https used per config
    if config.get('override_root') != 'task':
        app = SSLMiddleware(app, app_conf.get('no_redirect.pattern'),
                            app_conf.get('force_ssl.pattern'),
                            app_conf.get('force_ssl.logged_in'))
    # Setup resource manager, widget context SOP
    app = ew.WidgetMiddleware(
        app,
        compress=not asbool(global_conf['debug']),
        # compress=True,
        script_name=app_conf.get('ew.script_name', '/_ew_resources/'),
        url_base=app_conf.get('ew.url_base', '/_ew_resources/'),
        extra_headers=eval(app_conf.get('ew.extra_headers', 'None')),
        cache_max_age=asint(app_conf.get('ew.cache_header_seconds', 60*60*24*365)),
    )
    # Handle static files (by tool)
    app = StaticFilesMiddleware(app, app_conf.get('static.script_name'))
    # Handle setup and flushing of Ming ORM sessions
    app = MingMiddleware(app)
    # Set up the registry for stacked object proxies (SOPs).
    #    streaming=true ensures they won't be cleaned up till
    #    the WSGI application's iterator is exhausted
    app = RegistryManager(app, streaming=True)

    # "task" wsgi would get a 2nd request to /error/document if we used this middleware
    if config.get('override_root') != 'task':
        # Converts exceptions to HTTP errors, shows traceback in debug mode
        # don't use TG footer with extra CSS & images that take time to load
        tg.error.footer_html = '<!-- %s %s -->'
        app = tg.error.ErrorHandler(
            app, global_conf, **config['pylons.errorware'])

        # Redirect some status codes to /error/document
        if asbool(config['debug']):
            app = StatusCodeRedirect(app, base_config.handle_status_codes)
        else:
            app = StatusCodeRedirect(
                app, base_config.handle_status_codes + [500])

    for mw_ep in h.iter_entry_points('allura.middleware'):
        Middleware = mw_ep.load()
        if getattr(Middleware, 'when', 'inner') == 'outer':
            app = Middleware(app, config)

    return app
Ejemplo n.º 21
0
def make_pylons_stack(conf, full_stack=True, static_files=True, **app_conf):
    """Create a Pylons WSGI application and return it

    ``conf``
        The inherited configuration for this application. Normally from
        the [DEFAULT] section of the Paste ini file.

    ``full_stack``
        Whether this application provides a full WSGI stack (by default,
        meaning it handles its own exceptions and errors). Disable
        full_stack when this application is "managed" by another WSGI
        middleware.

    ``static_files``
        Whether this application serves its own static files; disable
        when another web server is responsible for serving them.

    ``app_conf``
        The application's local configuration. Normally specified in
        the [app:<name>] section of the Paste ini file (where <name>
        defaults to main).

    """
    # Configure the Pylons environment
    load_environment(conf, app_conf)

    # The Pylons WSGI app
    app = PylonsApp()
    # set pylons globals
    app_globals.reset()

    for plugin in PluginImplementations(IMiddleware):
        app = plugin.make_middleware(app, config)

    # Routing/Session/Cache Middleware
    app = RoutesMiddleware(app, config['routes.map'])
    # we want to be able to retrieve the routes middleware to be able to update
    # the mapper.  We store it in the pylons config to allow this.
    config['routes.middleware'] = app
    app = SessionMiddleware(app, config)
    app = CacheMiddleware(app, config)

    # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)
    # app = QueueLogMiddleware(app)
    if asbool(config.get('ckan.use_pylons_response_cleanup_middleware', True)):
        app = execute_on_completion(app, config, cleanup_pylons_response_string)

    # Fanstatic
    if asbool(config.get('debug', False)):
        fanstatic_config = {
            'versioning': True,
            'recompute_hashes': True,
            'minified': False,
            'bottom': True,
            'bundle': False,
        }
    else:
        fanstatic_config = {
            'versioning': True,
            'recompute_hashes': False,
            'minified': True,
            'bottom': True,
            'bundle': True,
        }
    app = Fanstatic(app, **fanstatic_config)

    for plugin in PluginImplementations(IMiddleware):
        try:
            app = plugin.make_error_log_middleware(app, config)
        except AttributeError:
            log.critical('Middleware class {0} is missing the method'
                         'make_error_log_middleware.'.format(plugin.__class__.__name__))

    if asbool(full_stack):
        # Handle Python exceptions
        app = ErrorHandler(app, conf, **config['pylons.errorware'])

        # Display error documents for 400, 403, 404 status codes (and
        # 500 when debug is disabled)
        if asbool(config['debug']):
            app = StatusCodeRedirect(app, [400, 403, 404])
        else:
            app = StatusCodeRedirect(app, [400, 403, 404, 500])

    # Initialize repoze.who
    who_parser = WhoConfig(conf['here'])
    who_parser.parse(open(app_conf['who.config_file']))

    app = PluggableAuthenticationMiddleware(
        app,
        who_parser.identifiers,
        who_parser.authenticators,
        who_parser.challengers,
        who_parser.mdproviders,
        who_parser.request_classifier,
        who_parser.challenge_decider,
        logging.getLogger('repoze.who'),
        logging.WARN,  # ignored
        who_parser.remote_user_key
    )

    # Establish the Registry for this application
    app = RegistryManager(app)

    app = I18nMiddleware(app, config)

    if asbool(static_files):
        # Serve static files
        static_max_age = None if not asbool(config.get('ckan.cache_enabled')) \
            else int(config.get('ckan.static_max_age', 3600))

        static_app = StaticURLParser(config['pylons.paths']['static_files'],
                                     cache_max_age=static_max_age)
        static_parsers = [static_app, app]

        storage_directory = uploader.get_storage_path()
        if storage_directory:
            path = os.path.join(storage_directory, 'storage')
            try:
                os.makedirs(path)
            except OSError, e:
                # errno 17 is file already exists
                if e.errno != 17:
                    raise

            storage_app = StaticURLParser(path, cache_max_age=static_max_age)
            static_parsers.insert(0, storage_app)

        # Configurable extra static file paths
        extra_static_parsers = []
        for public_path in config.get('extra_public_paths', '').split(','):
            if public_path.strip():
                extra_static_parsers.append(
                    StaticURLParser(public_path.strip(),
                                    cache_max_age=static_max_age)
                )
        app = Cascade(extra_static_parsers + static_parsers)
Ejemplo n.º 22
0
from model.evento import Evento
from model.carrinho import Carrinho
from model.ingresso import Ingresso
from model.categoria import Categoria
from model.ibge import IBGE
from model.servico import Servico
from model.venda import Venda

TEMPLATE_PATH.insert(0, "view")
_session_opts = {
    'session.type': 'memory',
    '_session.cookie_expires': 600,
    '_session.auto': True
}

app = SessionMiddleware(app(), _session_opts)


def has_session():
    _session = request.environ.get('beaker.session')
    if not _session or 'usuario_id' not in _session:
        return redirect('/login')


def set_session(key, value):
    _session = request.environ['beaker.session']
    _session[key] = value
    _session.save()


def del_session():
Ejemplo n.º 23
0
import bottle
from beaker.middleware import SessionMiddleware

session_opts = {
    'session.type': 'memory',
    'session.cookie_expires': 300,
    'session.auto': True
}
app = SessionMiddleware(bottle.app(), session_opts)


@bottle.route('/')
def session_test():
    s = bottle.request.environ.get('beaker.session')
    s['test'] = 'this string came from the session'
    s.save()
    bottle.redirect('/output')


@bottle.route('/output')
def session_output():
    s = bottle.request.environ.get('beaker.session')
    return s['test']


bottle.run(app=app, host='localhost', port=5000, debug=True, reloader=True)
Ejemplo n.º 24
0
                            input_encoding='utf-8',
                            output_encoding='utf-8')

    RP_ARGS = {
        "lookup": LOOKUP,
        "conf": CONF,
        "test_flows": TEST_FLOWS,
        "cache": {},
        "test_profile": TEST_PROFILE,
        "profiles": PROFILES,
        "test_class": test_class,
        "check_factory": check_factory
    }

    SRV = wsgiserver.CherryPyWSGIServer(
        ('0.0.0.0', CONF.PORT), SessionMiddleware(application, session_opts))

    if CONF.BASE.startswith("https"):
        import cherrypy
        from cherrypy.wsgiserver import ssl_pyopenssl
        # from OpenSSL import SSL

        SRV.ssl_adapter = ssl_pyopenssl.pyOpenSSLAdapter(
            CONF.SERVER_CERT, CONF.SERVER_KEY, CONF.CA_BUNDLE)
        # SRV.ssl_adapter.context = SSL.Context(SSL.SSLv23_METHOD)
        # SRV.ssl_adapter.context.set_options(SSL.OP_NO_SSLv3)
        try:
            cherrypy.server.ssl_certificate_chain = CONF.CERT_CHAIN
        except AttributeError:
            pass
        extra = " using SSL/TLS"
Ejemplo n.º 25
0
    fallback=True)
translation.install(True)
env.install_gettext_translations(translation)

# Middlewares

from beaker.middleware import SessionMiddleware

session_opts = {
    'session.type': 'file',
    'session.cookie_expires': False,
    'session.data_dir': './tmp',
    'session.auto': False
}

session = SessionMiddleware(app(), session_opts)
web = StripPathMiddleware(session)
web = GZipMiddleWare(web)

if PREFIX:
    web = PrefixMiddleware(web, prefix=PREFIX)

import pyload_app
import setup_app
import cnl_app
import api_app


# Server Adapter
def run_server(host, port, server):
    run(app=web, host=host, port=port, quiet=True, server=server)
Ejemplo n.º 26
0
def main():
    global aaa
    global app
    global content_path

    setproctitle("shoebill")

    args = parse_args()

    site_path = os.path.abspath(args.directory)
    content_path = os.path.join(site_path, "content")
    check_site_dir(site_path, content_path)

    print("Starting Shoebill...")
    setup_git_repo(site_path)

    if not args.no_auth:
        # Setup authentication
        if not aaa_available:
            print(
                """Error: the Beaker and/or Cork libraries are missing. \
            \nPlease install them or disable authentication using --no-auth"""
            )
            sys.exit(1)

        auth_dir = os.path.join(site_path, ".shoebill_auth")
        if not os.path.isdir(auth_dir):
            print("Creating authentication data")
            os.mkdir(auth_dir)

            token = gen_random_token(21)
            with open(os.path.join(auth_dir, "token"), "w") as f:
                f.write(token)

            aaa = Cork(auth_dir, initialize=True, preferred_hashing_algorithm="scrypt")
            aaa._store.roles["admin"] = 100
            aaa._store.roles["editor"] = 50
            aaa._store.save_roles()
            tstamp = str(datetime.utcnow())
            admin_password = gen_random_token(6)
            aaa._store.users["admin"] = {
                "role": "admin",
                "hash": aaa._hash("admin", admin_password),
                "email_addr": "",
                "desc": "admin",
                "creation_date": tstamp,
                "_accessed_time": tstamp,
                "last_login": tstamp,
            }
            aaa._store.save_users()
            print("\n", "*" * 32, "\n")
            print("Initialized user 'admin' with password '%s'" % admin_password)
            print("\n", "*" * 32, "\n")

        else:
            aaa = Cork(auth_dir, preferred_hashing_algorithm="scrypt")

    if aaa:
        # Sessions are enabled only if authentication is enabled
        with open(os.path.join(auth_dir, "token")) as f:
            session_encrypt_key = f.read()

        session_opts = {
            "session.cookie_expires": True,
            "session.encrypt_key": session_encrypt_key,
            "session.httponly": True,
            "session.timeout": 3600 * 24,  # 1 day
            "session.type": "cookie",
            "session.validate_key": True,
        }
        wrapped_app = SessionMiddleware(app, session_opts)
        bottle.run(
            wrapped_app,
            host=args.host,
            port=args.port,
            debug=args.debug,
            reloader=args.debug,
            server="auto",
        )

    else:
        bottle.run(
            app,
            host=args.host,
            port=args.port,
            debug=args.debug,
            reloader=args.debug,
            server="auto",
        )
Ejemplo n.º 27
0
    return True


install(SQLitePlugin(dbfile=const.DB_FILENAME))

session_opts = {
    'session.auto': True,
    'session.cookie_expires': True,
    'session.timeout': 1440,
    'session.type': 'file',
    'session.data_dir': './data',
    'session.httponly': True,
}

app = bottle.app()
app = SessionMiddleware(app, session_opts)

if __name__ == '__main__':
    logging.basicConfig(filename='logs.log',
                        level=logging.DEBUG,
                        format='%(levelname)s: %(asctime)s - %(message)s',
                        datefmt='%d-%m-%Y %H:%M:%S')

    if not is_valid_sqlite3(const.DB_FILENAME):
        print err.SQLITE_FILE_USER
        logging.critical(err.SQLITE_FILE)
    else:
        debug(True)
        run(app=app, host='10.10.0.25', port='8080', reloader=True)

    #TODO: add a menu
Ejemplo n.º 28
0
def make_app(global_conf, full_stack=True, static_files=True, **app_conf):
    """
    Create a Pylons WSGI application and return it

    ``global_conf``
        The inherited configuration for this application. Normally from
        the [DEFAULT] section of the Paste ini file.

    ``full_stack``
        Whether this application provides a full WSGI stack (by default,
        meaning it handles its own exceptions and errors). Disable
        full_stack when this application is "managed" by another WSGI
        middleware.

    ``static_files``
        Whether this application serves its own static files; disable
        when another web server is responsible for serving them.

    ``app_conf``
        The application's local configuration. Normally specified in
        the [app:<name>] section of the Paste ini file (where <name>
        defaults to main).

    """
    # Configure the Pylons environment
    config = load_environment(global_conf, app_conf)

    # The Pylons WSGI app
    app = PylonsApp()

    # Profiling Middleware
    if profile_load:
        if asbool(config['profile']):
            app = AccumulatingProfileMiddleware(
                app,
                log_filename='/var/log/linotp/profiling.log',
                cachegrind_filename='/var/log/linotp/cachegrind.out',
                discard_first_request=True,
                flush_at_shutdown=True,
                path='/__profile__')

    # Routing/Session/Cache Middleware
    app = RoutesMiddleware(app, config['routes.map'])
    app = SessionMiddleware(app, config)
    app = CacheMiddleware(app, config)

    g = config['pylons.app_globals']
    g.cache_manager = app.cache_manager

    # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)

    if asbool(full_stack):
        # Handle Python exceptions
        app = ErrorHandler(app, global_conf, **config['pylons.errorware'])

        # Display error documents for 401, 403, 404 status codes (and
        # 500 when debug is disabled)
        if asbool(config['debug']):
            app = StatusCodeRedirect(app)
        else:
            app = StatusCodeRedirect(app, [400, 401, 403, 404, 500])

    # Establish the Registry for this application
    app = RegistryManager(app)

    if asbool(static_files):
        # Serve static files
        static_app = StaticURLParser(config['pylons.paths']['static_files'])
        app = Cascade([static_app, app])

    # repoze.who
    if repoze_load:
        if 'who.generate_random_secret' in app_conf and not app_conf[
                'who.generate_random_secret']:
            app = make_who_with_config(app, global_conf,
                                       app_conf['who.config_file'],
                                       app_conf['who.log_file'],
                                       app_conf['who.log_level'])
        else:
            # Read the current configuration file and replace "secret" keys in every line
            who_config_lines = []
            secret = binascii.hexlify(os.urandom(16))
            if len(secret) != 32:
                raise RuntimeError(
                    'Could not generate random repoze.who secret, no os.urandom support?'
                )

            with open(app_conf['who.config_file']) as f:
                for line in f.readlines():
                    who_config_lines.append(
                        re.sub(r'^(secret)\s*=\s*.*$', r'\1 = %s' % secret,
                               line))
            with tempinput(''.join(who_config_lines)) as who_config_file:
                app = make_who_with_config(app, global_conf, who_config_file,
                                           app_conf['who.log_file'],
                                           app_conf['who.log_level'])

    # this is a compatibility hack for pylons > 1.0!!!
    conf = PyConf(config)

    conf['global_conf'] = global_conf
    conf['app_conf'] = app_conf
    conf['__file__'] = global_conf['__file__']
    conf['FILE'] = global_conf['__file__']
    conf['routes.map'] = config['routes.map']

    if not hasattr(conf, 'init_app'):
        setattr(conf, 'init_app', config.init_app)
    app.config = conf

    return app
Ejemplo n.º 29
0
def make_flask_stack(conf, **app_conf):
    """ This has to pass the flask app through all the same middleware that
    Pylons used """

    root = os.path.dirname(
        os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

    debug = asbool(conf.get('debug', conf.get('DEBUG', False)))
    testing = asbool(app_conf.get('testing', app_conf.get('TESTING', False)))
    app = flask_app = CKANFlask(__name__, static_url_path='')

    # Register storage for accessing group images, site logo, etc.
    storage_folder = []
    storage = uploader.get_storage_path()
    if storage:
        storage_folder = [os.path.join(storage, 'storage')]

    # Static files folders (core and extensions)
    public_folder = config.get(u'ckan.base_public_folder')
    app.static_folder = config.get('extra_public_paths', '').split(',') + [
        os.path.join(root, public_folder)
    ] + storage_folder

    app.jinja_options = jinja_extensions.get_jinja_env_options()

    app.debug = debug
    app.testing = testing
    app.template_folder = os.path.join(root, 'templates')
    app.app_ctx_globals_class = CKAN_AppCtxGlobals
    app.url_rule_class = CKAN_Rule

    # Update Flask config with the CKAN values. We use the common config
    # object as values might have been modified on `load_environment`
    if config:
        app.config.update(config)
    else:
        app.config.update(conf)
        app.config.update(app_conf)

    # Do all the Flask-specific stuff before adding other middlewares

    # Secret key needed for flask-debug-toolbar and sessions
    if not app.config.get('SECRET_KEY'):
        app.config['SECRET_KEY'] = config.get('beaker.session.secret')
    if not app.config.get('SECRET_KEY'):
        raise RuntimeError(u'You must provide a value for the secret key'
                           ' with the SECRET_KEY config option')

    if debug:
        from flask_debugtoolbar import DebugToolbarExtension
        app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
        DebugToolbarExtension(app)

        from werkzeug.debug import DebuggedApplication
        app.wsgi_app = DebuggedApplication(app.wsgi_app, True)

        log = logging.getLogger('werkzeug')
        log.setLevel(logging.DEBUG)

    # Use Beaker as the Flask session interface
    class BeakerSessionInterface(SessionInterface):
        def open_session(self, app, request):
            if 'beaker.session' in request.environ:
                return request.environ['beaker.session']

        def save_session(self, app, session, response):
            session.save()

    namespace = 'beaker.session.'
    session_opts = {
        k.replace('beaker.', ''): v
        for k, v in six.iteritems(config) if k.startswith(namespace)
    }
    if (not session_opts.get('session.data_dir')
            and session_opts.get('session.type', 'file') == 'file'):
        cache_dir = app_conf.get('cache_dir') or app_conf.get('cache.dir')
        session_opts['session.data_dir'] = '{data_dir}/sessions'.format(
            data_dir=cache_dir)

    app.wsgi_app = SessionMiddleware(app.wsgi_app, session_opts)
    app.session_interface = BeakerSessionInterface()

    # Add Jinja2 extensions and filters
    app.jinja_env.filters['empty_and_escape'] = \
        jinja_extensions.empty_and_escape

    # Common handlers for all requests
    app.before_request(ckan_before_request)
    app.after_request(ckan_after_request)

    # Template context processors
    app.context_processor(helper_functions)
    app.context_processor(c_object)

    @app.context_processor
    def ungettext_alias():
        u'''
        Provide `ungettext` as an alias of `ngettext` for backwards
        compatibility
        '''
        return dict(ungettext=ungettext)

    # Babel
    pairs = [(os.path.join(root, u'i18n'), 'ckan')
             ] + [(p.i18n_directory(), p.i18n_domain())
                  for p in PluginImplementations(ITranslation)]

    i18n_dirs, i18n_domains = zip(*pairs)

    app.config[u'BABEL_TRANSLATION_DIRECTORIES'] = ';'.join(i18n_dirs)
    app.config[u'BABEL_DOMAIN'] = 'ckan'
    app.config[u'BABEL_MULTIPLE_DOMAINS'] = ';'.join(i18n_domains)

    babel = CKANBabel(app)

    babel.localeselector(get_locale)

    # WebAssets
    _setup_webassets(app)

    # Auto-register all blueprints defined in the `views` folder
    _register_core_blueprints(app)
    _register_error_handler(app)

    # Set up each IBlueprint extension as a Flask Blueprint
    for plugin in PluginImplementations(IBlueprint):
        if hasattr(plugin, 'get_blueprint'):
            plugin_blueprints = plugin.get_blueprint()
            if not isinstance(plugin_blueprints, list):
                plugin_blueprints = [plugin_blueprints]
            for blueprint in plugin_blueprints:
                app.register_extension_blueprint(blueprint)

    lib_plugins.register_package_blueprints(app)
    lib_plugins.register_group_blueprints(app)

    # Set flask routes in named_routes
    # TODO: refactor whatever helper is using this to not do it
    if 'routes.named_routes' not in config:
        config['routes.named_routes'] = {}
    for rule in app.url_map.iter_rules():
        if '.' not in rule.endpoint:
            continue
        controller, action = rule.endpoint.split('.')
        needed = list(rule.arguments - set(rule.defaults or {}))
        route = {
            rule.endpoint: {
                'action': action,
                'controller': controller,
                'highlight_actions': action,
                'needed': needed
            }
        }
        config['routes.named_routes'].update(route)

    # Start other middleware
    for plugin in PluginImplementations(IMiddleware):
        app = plugin.make_middleware(app, config)

    # Fanstatic
    fanstatic_enable_rollup = asbool(
        app_conf.get('fanstatic_enable_rollup', False))
    if debug:
        fanstatic_config = {
            'versioning': True,
            'recompute_hashes': True,
            'minified': False,
            'bottom': True,
            'bundle': False,
            'rollup': fanstatic_enable_rollup,
        }
    else:
        fanstatic_config = {
            'versioning': True,
            'recompute_hashes': False,
            'minified': True,
            'bottom': True,
            'bundle': True,
            'rollup': fanstatic_enable_rollup,
        }
    root_path = config.get('ckan.root_path', None)
    if root_path:
        root_path = re.sub('/{{LANG}}', '', root_path)
        fanstatic_config['base_url'] = root_path
    app = Fanstatic(app, **fanstatic_config)

    for plugin in PluginImplementations(IMiddleware):
        try:
            app = plugin.make_error_log_middleware(app, config)
        except AttributeError:
            log.critical('Middleware class {0} is missing the method'
                         'make_error_log_middleware.'.format(
                             plugin.__class__.__name__))

    # Initialize repoze.who
    who_parser = WhoConfig(conf['here'])
    who_parser.parse(open(app_conf['who.config_file']))

    app = PluggableAuthenticationMiddleware(
        app,
        who_parser.identifiers,
        who_parser.authenticators,
        who_parser.challengers,
        who_parser.mdproviders,
        who_parser.request_classifier,
        who_parser.challenge_decider,
        logging.getLogger('repoze.who'),
        logging.WARN,  # ignored
        who_parser.remote_user_key)

    # Update the main CKAN config object with the Flask specific keys
    # that were set here or autogenerated
    flask_config_keys = set(flask_app.config.keys()) - set(config.keys())
    for key in flask_config_keys:
        config[key] = flask_app.config[key]

    if six.PY3:
        app = I18nMiddleware(app)

        if asbool(config.get('ckan.tracking_enabled', 'false')):
            app = TrackingMiddleware(app, config)

    # Add a reference to the actual Flask app so it's easier to access
    app._wsgi_app = flask_app

    return app
Ejemplo n.º 30
0
def make_app(global_conf, full_stack=True, static_files=True, **app_conf):
    """Create a Pylons WSGI application and return it

    ``global_conf``
        The inherited configuration for this application. Normally from
        the [DEFAULT] section of the Paste ini file.

    ``full_stack``
        Whether or not this application provides a full WSGI stack (by
        default, meaning it handles its own exceptions and errors).
        Disable full_stack when this application is "managed" by
        another WSGI middleware.

    ``app_conf``
        The application's local configuration. Normally specified in
        the [app:<name>] section of the Paste ini file (where <name>
        defaults to main).

    """
    # Configure the Pylons environment
    config = load_environment(global_conf, app_conf)

    # The Pylons WSGI app
    app = PylonsApp(config=config)

    # Routing/Session/Cache Middleware
    app = RoutesMiddleware(app, config['routes.map'])
    app = SessionMiddleware(app, config)

    # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)
    if asbool(config['pdebug']):
        from rhodecode.lib.profiler import ProfilingMiddleware
        app = ProfilingMiddleware(app)

    if asbool(full_stack):

        # Handle Python exceptions
        app = ErrorHandler(app, global_conf, **config['pylons.errorware'])

        # we want our low level middleware to get to the request ASAP. We don't
        # need any pylons stack middleware in them
        app = SimpleHg(app, config)
        app = SimpleGit(app, config)

        # Display error documents for 401, 403, 404 status codes (and
        # 500 when debug is disabled)
        if asbool(config['debug']):
            app = StatusCodeRedirect(app)
        else:
            app = StatusCodeRedirect(app, [400, 401, 403, 404, 500])

    #enable https redirets based on HTTP_X_URL_SCHEME set by proxy
    app = HttpsFixup(app, config)

    # Establish the Registry for this application
    app = RegistryManager(app)

    if asbool(static_files):
        # Serve static files
        static_app = StaticURLParser(config['pylons.paths']['static_files'])
        app = Cascade([static_app, app])
        app = make_gzip_middleware(app, global_conf, compress_level=1)

    app.config = config

    return app