Ejemplo n.º 1
0
 def load_session(self):
     self.app = SessionMiddleware(self.app, {
         'session.type': 'mongodb',
         'session.cookie_expires': self.cookie_expires,
         'session.url': self.beaker_url,
         'session.secret': self.secret,
         'session.lock_dir': self.data_dir
     })
Ejemplo n.º 2
0
 def load_session(self):
     # Since we vendor mongodb_beaker because of broken dep on pypi.python.org
     # we need to setup the beaker class map manually.
     beaker.cache.clsmap['mongodb'] = mongodb_beaker.MongoDBNamespaceManager
     self.app = SessionMiddleware(self.app, {
         'session.type': 'mongodb',
         'session.cookie_expires': self.cookie_expires,
         'session.url': self.beaker_url,
         'session.secret': self.secret,
         'session.lock_dir': self.data_dir
     })
Ejemplo n.º 3
0
    def __init__(self, options={}):
        self.usage = None
        self.callable = None
        self.prog = None
        self.options = options
        self.do_load_config()

        self.setup_cork()

        super(AddressServer, self).__init__()
        self.app = Bottle()
        self.add_routes()
        self.add_middleware()
Ejemplo n.º 4
0
    def add_middleware(self):
        """Set up the session middleware."""

        ENCRYPT_KEY = os.environ.get('ENCRYPT_KEY')
        session_opts = {
            'session.cookie_expires': True,
            'session.encrypt_key': ENCRYPT_KEY,
            'session.httponly': True,
            'session.timeout': 3600 * 24,  # 1 day
            'session.type': 'cookie',
            'session.validate_key': True,
        }
        self.app = SessionMiddleware(self.app, session_opts)
Ejemplo n.º 5
0
    def init_app(self):
        self.logger.info('Initialize gevent signal-handlers')
        gevent.signal(SIGTERM, self.exit)
        gevent.signal(SIGINT, self.exit)
        self.logger.info('Initialize WSGI Application')
        self.app = BottleApplication()

        self.load_auth_backends()
        self.load_webservices()
        self.load_session()

        self.logger.info('WSGI fully loaded.')
        return self
Ejemplo n.º 6
0
    def __call__(self):
        self.logger.info('Initialize gevent signal-handlers')
        gevent.signal(SIGTERM, self.exit)
        gevent.signal(SIGINT, self.exit)

        self.logger.info('Start AMQP thread')
        self.amqp.start()

        self.logger.info('Initialize WSGI Application')
        self.app = BottleApplication()

        self.load_auth_backends()
        self.load_webservices()
        self.load_session()

        return self
Ejemplo n.º 7
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).

    """
    # The Pylons WSGI app
    app = pylons_app = CKANPylonsApp()

    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 = common_middleware.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.º 8
0
            log.warning('Using gevent for asynchronous processing')
            async = True

    config.async = async

    app = bottle.app()
    session_opts = {
        'session.auto': False,
        'session.type': 'file',
        'session.key': 'drink_cookie',
        'session.cookie_expires': False,
        'session.data_dir':  DB_PATH,
        #'session.validate_key': 'drink-key-you-must-change-this-in-cookies',
        #'session.encryption_key': ''.join(chr(randint(65, 122)) for x in xrange(100)
    }
    app = SessionMiddleware(app, session_opts)

    if not full:
        return app

    # handle debug mode
    debug = False
    if dbg_in_env:
        debug = True
        # trick to allow debug-wrapping
        app.catchall = False

        def dbg_repoze(app):
            from repoze.debug.pdbpm import PostMortemDebug
            app = PostMortemDebug(app)
            log.debug("Installed repoze.debug's debugging middleware")
Ejemplo n.º 9
0
    def __init__(self):
        self.cfg = j.portal.servers.config
        self.cfg_main = self.cfg["main"]
        self.cfg_oauth = self.cfg.get('oauth', None)
        self.logger = j.logger.get('j.portal.tools.server')

        self.contentdirs = list()
        self.libpath = j.portal.tools.html.htmlfactory.getHtmllibDir()
        self.started = False
        self.epoch = time.time()
        self.force_oauth_url = None
        self.force_oauth_instance = self.cfg_oauth.get('force_oauth_instance',
                                                       "")
        j.application.debug = self.cfg.get("debug", False)
        j.portal.tools.server.active = self

        self.watchedspaces = []
        self.pageKey2doc = {}
        self.routes = {}
        self.proxies = {}

        self.authentication_method = self.cfg.get("authentication_method")
        session_opts = {
            'session.cookie_expires':
            False,
            'session.data_dir':
            '%s' % j.sal.fs.joinPaths(j.dirs.VARDIR, "beakercache")
        }

        # TODO change that to work with ays instance config instead of connection string
        connection = self.cfg.get('mongoengine', {})
        self.port = connection.get('port', None)

        if not self.authentication_method:
            minimalsession = {
                'session.type': 'MinimalBeaker',
                'session.namespace_class': MinimalBeaker,
                'session.namespace_args': {
                    'client': None
                }
            }
            session_opts.update(minimalsession)
            self.auth = PortalAuthenticatorMinimal()
        else:
            if self.authentication_method == 'gitlab':
                self.auth = PortalAuthenticatorGitlab(
                    instance=self.gitlabinstance)
            else:
                j.portal.tools.models.system.connect2mongo(
                    connection['host'], port=int(connection['port']))

                mongoenginesession = {
                    'session.type': 'MongoEngineBeaker',
                    'session.namespace_class': MongoEngineBeaker,
                    'session.namespace_args': {}
                }
                session_opts.update(mongoenginesession)
                self.auth = PortalAuthenticatorMongoEngine()

        self.pageprocessor = PageProcessor()

        self.loadConfig()

        macros_dir = j.sal.fs.joinPaths(j.sal.fs.getcwd(), 'macros')
        macroPathsPreprocessor = [j.sal.fs.joinPaths(macros_dir, "preprocess")]
        macroPathsWiki = [j.sal.fs.joinPaths(macros_dir, "wiki")]
        macroPathsPage = [j.sal.fs.joinPaths(macros_dir, "page")]
        macroPathsMarkDown = [j.sal.fs.joinPaths(macros_dir, "markdown")]

        self.macroexecutorPreprocessor = MacroExecutorPreprocess(
            macroPathsPreprocessor)
        self.macroexecutorPage = MacroExecutorPage(macroPathsPage)
        self.macroexecutorMarkDown = MacroexecutorMarkDown(macroPathsMarkDown)
        self.macroexecutorWiki = MacroExecutorWiki(macroPathsWiki)
        self.errorhandler = ErrorHandler()
        templatedirs = [
            self.portaldir.joinpath('templates'),
            self.appdir.joinpath('templates')
        ]
        for contentdir in self.contentdirs:
            templatedirs.append(j.sal.fs.joinPaths(contentdir, 'templates'))
        self.templates = PortalTemplate(templatedirs)
        self.bootstrap()

        self._router = SessionMiddleware(AuditMiddleWare(self.router),
                                         session_opts)

        self._megarouter = DispatcherMiddleware(self._router)
        self._webserver = WSGIServer((self.listenip, self.port),
                                     self._megarouter)

        self.confluence2htmlconvertor = j.portal.tools.docgenerator.docgeneratorfactory.getConfluence2htmlConvertor(
        )
        self.activejobs = list()
        self.jobids2greenlets = dict()

        self.schedule1min = {}
        self.schedule15min = {}
        self.schedule60min = {}

        self.jslibroot = j.sal.fs.joinPaths(j.dirs.JSAPPSDIR, "portals",
                                            "jslib")

        #  Load local spaces
        self.rest = PortalRest(self)
        self.loadSpaces()
Ejemplo n.º 10
0
import dbfuncs
from userclass import TFuser
from caseclass import TFcase
from imageclass import TFimage, TFimagestack

site = Bottle()
session_opts = {
    'session.type': 'cookie',
    'session.validate_key': 'validkey',
    'session.timeout': 900,
    'session.cookie_expires': True,
    'session.data_dir': './data',
    'session.auto': True
}

app = SessionMiddleware(site, session_opts)

###### Static Routes


@site.route('/static/<filepath:path>')
def server_static(filepath):
    return static_file(filepath, root='./static')


@site.get('/')
def index():
    return static_file('index.html', root=".")


@site.get('/favicon.ico')
Ejemplo n.º 11
0
 def __call__(self, environ, start_response):
     return SessionMiddleware.__call__(self, environ, start_response)
Ejemplo n.º 12
0
def init(config, app):
    global local_api_url
    logger.info('Web asset root: "%s"', ui_root)
    auth_module = config.get('auth',
                             {'module': 'iris.ui.auth.noauth'})['module']
    auth = importlib.import_module(auth_module)
    auth_manager = getattr(auth, 'Authenticator')(config)

    debug = config['server'].get('disable_auth', False) is True
    local_api_url = config['server'].get('local_api_url',
                                         'http://localhost:16649')

    app.add_route('/static/bundles/{filename}',
                  StaticResource('/static/bundles'))
    app.add_route('/static/images/{filename}',
                  StaticResource('/static/images'))
    app.add_route('/static/fonts/{filename}', StaticResource('/static/fonts'))
    app.add_route('/', Index())
    app.add_route('/stats', Stats())
    app.add_route('/plans/', Plans())
    app.add_route('/plans/{plan}', Plan())
    app.add_route('/incidents/', Incidents())
    app.add_route('/incidents/{incident}', Incident())
    app.add_route('/messages/', Messages())
    app.add_route('/messages/{message}', Message())
    app.add_route('/templates/', Templates())
    app.add_route('/templates/{template}', Template())
    app.add_route('/applications/', Applications())
    app.add_route('/applications/{application}', Application())
    app.add_route('/login/', Login(auth_manager, debug))
    app.add_route('/logout/', Logout())
    app.add_route('/user/', User())
    app.add_route('/validate/jinja', JinjaValidate())

    # Configuring the beaker middleware mutilates the app object, so do it
    # at the end, after we've added all routes/sinks for the entire iris
    # app.
    session_opts = {
        'session.type':
        'cookie',
        'session.cookie_expires':
        True,
        'session.key':
        'iris-auth',
        'session.encrypt_key':
        config['user_session']['encrypt_key'],
        'session.validate_key':
        config['user_session']['sign_key'],
        'session.secure':
        not (config['server'].get('disable_auth', False)
             or config['server'].get('allow_http', False)),
        'session.httponly':
        True,
        'session.crypto_type':
        'cryptography',
        'session.samesite':
        'Lax'
    }
    app = SessionMiddleware(app, session_opts)

    return app
Ejemplo n.º 13
0
    def __init__(self, app, pm, engine):
        self.pm = pm
        SessionMiddleware.__init__(self, app)

        SimplePlugin.__init__(self, engine)
        self.subscribe()
Ejemplo n.º 14
0
 def __init__(self, app, login_url):
     self.app = SessionMiddleware(app, _session_opts)
     self.nacl = j.me.encryptor
     self.login_url = login_url
Ejemplo n.º 15
0
from mybot import config

# Add view paths to the Bottle template path
TEMPLATE_SUB_PATHS = next(os.walk(config.BASE_TEMPLATE_PATH))[1]
TEMPLATE_PATH.append(config.BASE_TEMPLATE_PATH)

for templatePath in TEMPLATE_SUB_PATHS:
    TEMPLATE_PATH.append(os.path.join(config.BASE_TEMPLATE_PATH, templatePath))


session_opts = {
    'session.type': 'file',
    'session.cookie_expires': 30,  # Время в сек через которое закончится текущая сессия
    'session.data_dir': './data',  # Директория для хранения сесии
    'session.auto': True
}

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

from .controllers import *

# if config.DEBUG:
#     print("ROOT_PATH: %s" % config.ROOT_PATH)
#     print("Template Paths:")
#
#     for it in bottle.TEMPLATE_PATH:
#         print("   %s" % it)

Ejemplo n.º 16
0
class WebServer():

    CONF_PATH = 'etc/webserver.conf'
    LOG_FILE = root_path + '/var/log/webserver.log'

    @property
    def application(self):
        return self.app

    @property
    def beaker_url(self):
        return self.db.beaker_uri

    @property
    def skip_login(self):
        return [bname for bname in self.auth_backends.keys()]

    @property
    def skip_logout(self):
        return [
            bname
            for bname in self.auth_backends.keys()
            if not self.auth_backends[bname].handle_logout
        ]

    def __init__(self, config, logger, amqp_pub):
        self.config = config
        self.logger = logger
        self.amqp_pub = amqp_pub

        server = self.config.get('server', {})
        self.debug = server.get('debug', DEFAULT_DEBUG)
        self.enable_crossdomain_send_events = server.get(
            'enable_crossdomain_send_events', DEFAULT_ECSE)
        self.root_directory = os.path.expanduser(
            server.get('root_directory', DEFAULT_ROOT_DIR))

        auth = self.config.get('auth', {})
        self.providers = cfg_to_array(auth.get('providers', ''))
        if len(self.providers) == 0:
            self.logger.critical(
                'Missing providers. Cannot launch webcore module.')
            raise RuntimeError('Missing providers')

        session = self.config.get('session', {})
        self.cookie_expires = int(session.get('cookie_expires',
                                              DEFAULT_COOKIES_EXPIRE))
        self.secret = session.get('secret', DEFAULT_SECRET)
        self.data_dir = session.get('data_dir', DEFAULT_DATA_DIR)

        self.webservices = self.config.get('webservices', {})

        # TODO: Replace with MongoStorage
        self.db = get_storage(account=Account(user='******', group='root'))
        self.stopping = False

        self.webmodules = {}
        self.auth_backends = {}

    def init_app(self):
        self.logger.info('Initialize gevent signal-handlers')
        gevent.signal(SIGTERM, self.exit)
        gevent.signal(SIGINT, self.exit)
        self.logger.info('Initialize WSGI Application')
        self.app = BottleApplication()

        self.load_auth_backends()
        self.load_webservices()
        self.load_session()

        self.logger.info('WSGI fully loaded.')
        return self

    def _load_webservice(self, modname):
        if modname in self.webmodules:
            return True

        if modname is None:
            return False

        self.logger.info('Loading webservice: {0}'.format(modname))

        try:
            mod = importlib.import_module(modname)

        except ImportError as err:
            self.logger.error(
                'Impossible to load webservice {0}: {1}'.format(modname, err)
            )

            return False

        else:
            if hasattr(mod, 'exports'):
                self.webmodules[modname] = mod
                mod.exports(self)

            else:
                self.logger.error(
                    'Invalid module {0}, no exports()'.format(modname)
                )

                return False

        return True

    def load_webservices(self):
        for module in sorted(self.webservices.keys()):
            enable = int(self.webservices[module])
            if enable == 1:
                self._load_webservice(module)
            else:
                self.logger.info(
                    u'Webservice {} skipped by configuration.'.format(module))

        self.logger.info(u'Service loading completed.')

    def _load_auth_backend(self, modname):
        if modname in self.auth_backends:
            return True

        self.logger.info('Load authentication backend: {0}'.format(modname))

        try:
            mod = importlib.import_module(modname)

        except ImportError as err:
            self.logger.error(
                'Impossible to load authentication backend {}: {}'.format(
                    modname, err
                )
            )

            return False

        else:
            backend = mod.get_backend(self)
            self.auth_backends[backend.name] = backend
            self.app.install(backend)

        return True

    def load_auth_backends(self):
        for provider in self.providers:
            self._load_auth_backend(provider)

        # Always add this backend which returns 401 when the login fails
        backend = EnsureAuthenticated(self)
        self.auth_backends[backend.name] = backend
        self.app.install(backend)

    def load_session(self):
        # Since we vendor mongodb_beaker because of broken dep on pypi.python.org
        # we need to setup the beaker class map manually.
        beaker.cache.clsmap['mongodb'] = mongodb_beaker.MongoDBNamespaceManager
        self.app = SessionMiddleware(self.app, {
            'session.type': 'mongodb',
            'session.cookie_expires': self.cookie_expires,
            'session.url': self.beaker_url,
            'session.secret': self.secret,
            'session.lock_dir': self.data_dir
        })

    def unload_session(self):
        pass

    def unload_auth_backends(self):
        pass

    def unload_webservices(self):
        pass

    def exit(self):
        if not self.stopping:
            self.stopping = True

            self.unload_session()
            self.unload_webservices()
            self.unload_auth_backends()
            self.amqp_pub.connection.disconnect()

            sys.exit(0)

    class Error(Exception):
        pass
Ejemplo n.º 17
0
 def __call__(self, environ, start_response):
     return SessionMiddleware.__call__(self, environ, start_response)
Ejemplo n.º 18
0
DEBUG = config.get("general",
                   "debug_mode") or "-d" in sys.argv or "--debug" in sys.argv
bottle.debug(DEBUG)

# 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 api_app
import cnl_app
import setup_app
# Last routes to register,
import pyload_app


# Server Adapter
def run_server(host, port, server):
Ejemplo n.º 19
0
class WebServer(Configurable):
    @property
    def debug(self):
        return setdefaultattr(self, '_debug', False)

    @debug.setter
    def debug(self, value):
        self._debug = value

    @property
    def enable_crossdomain_send_events(self):
        return setdefaultattr(self, '_crossdomain_evt', False)

    @enable_crossdomain_send_events.setter
    def enable_crossdomain_send_events(self, value):
        self._crossdomain_evt = value

    @property
    def root_directory(self):
        return setdefaultattr(
            self, '_rootdir',
            os.path.expanduser('~/var/www/')
        )

    @root_directory.setter
    def root_directory(self, value):
        value = os.path.expanduser(value)

        if os.path.exists(value):
            self._rootdir = value

    @property
    def providers(self):
        return setdefaultattr(self, '_providers', [])

    @providers.setter
    def providers(self, value):
        self._providers = value

    @property
    def cookie_expires(self):
        return setdefaultattr(self, '_cookie', 300)

    @cookie_expires.setter
    def cookie_expires(self, value):
        self._cookie = value

    @property
    def secret(self):
        return setdefaultattr(self, '_secret', 'canopsis')

    @secret.setter
    def secret(self, value):
        self._secret = value

    @property
    def data_dir(self):
        return setdefaultattr(
            self, '_datadir',
            os.path.expanduser('~/var/cache/canopsis/webcore/')
        )

    @data_dir.setter
    def data_dir(self, value):
        value = os.path.expanduser(value)

        if os.path.exists(value):
            self._datadir = value

    # dict properties do not need setters

    @property
    def webservices(self):
        if not hasattr(self, '_webservices'):
            self._webservices = {}

        return self._webservices

    @property
    def beaker_url(self):
        return '{0}.beaker'.format(self.db.uri)

    def __init__(self, *args, **kwargs):
        super(WebServer, self).__init__(*args, **kwargs)

        self.log_name = 'webserver'

        # TODO: Replace with MongoStorage
        self.db = get_storage(account=Account(user='******', group='root'))
        self.amqp = Amqp()
        self.stopping = False

        self.webmodules = {}
        self.auth_backends = {}

    def __call__(self):
        self.logger.info('Initialize gevent signal-handlers')
        gevent.signal(SIGTERM, self.exit)
        gevent.signal(SIGINT, self.exit)

        self.logger.info('Start AMQP thread')
        self.amqp.start()

        self.logger.info('Initialize WSGI Application')
        self.app = BottleApplication()

        self.load_auth_backends()
        self.load_webservices()
        self.load_session()

        return self

    def _load_webservice(self, name):
        modname = 'canopsis.webcore.services.{0}'.format(name)

        if name in self.webmodules:
            return True

        self.logger.info('Loading webservice: {0}'.format(name))

        try:
            mod = importlib.import_module(modname)

        except ImportError as err:
            self.logger.error(
                'Impossible to load webservice {0}: {1}'.format(name, err)
            )

            return False

        else:
            if hasattr(mod, 'exports'):
                self.webmodules[name] = mod
                mod.exports(self)

            else:
                self.logger.error(
                    'Invalid module {0}, no exports()'.format(name)
                )

                return False

        return True

    def load_webservices(self):
        for webservice in self.webservices:
            if self.webservices[webservice]:
                self._load_webservice(webservice)

    def _load_auth_backend(self, name):
        modname = 'canopsis.auth.{0}'.format(name)

        if name in self.auth_backends:
            return True

        self.logger.info('Load authentication backend: {0}'.format(name))

        try:
            mod = importlib.import_module(modname)

        except ImportError as err:
            self.logger.error(
                'Impossible to load authentication backend {}: {}'.format(
                    name, err
                )
            )

            return False

        else:
            backend = mod.get_backend(self)
            self.auth_backends[backend.name] = backend
            self.app.install(backend)

        return True

    def load_auth_backends(self):
        for provider in self.providers:
            self._load_auth_backend(provider)

        # Always add this backend which returns 401 when the login fails
        backend = EnsureAuthenticated(self)
        self.auth_backends[backend.name] = backend
        self.app.install(backend)

    def load_session(self):
        self.app = SessionMiddleware(self.app, {
            'session.type': 'mongodb',
            'session.cookie_expires': self.cookie_expires,
            'session.url': self.beaker_url,
            'session.secret': self.secret,
            'session.lock_dir': self.data_dir
        })

    def unload_session(self):
        pass

    def unload_auth_backends(self):
        pass

    def unload_webservices(self):
        pass

    def exit(self):
        if not self.stopping:
            self.stopping = True

            self.unload_session()
            self.unload_webservices()
            self.unload_auth_backends()

            self.amqp.stop()
            # TODO: self.amqp.wait() not implemented

            sys.exit(0)

    @property
    def application(self):
        return self.app

    @property
    def skip_login(self):
        return [bname for bname in self.auth_backends.keys()]

    @property
    def skip_logout(self):
        return [
            bname
            for bname in self.auth_backends.keys()
            if not self.auth_backends[bname].handle_logout
        ]

    def require(self, modname):
        if not self._load_webservice(modname):
            raise ImportError(
                'Impossible to import webservice: {0}'.format(modname)
            )

        return self.webmodules[modname]

    class Error(Exception):
        pass
Ejemplo n.º 20
0
# alias the authorization decorator with defaults
authorize = aaa.make_auth_decorator(fail_redirect="/login", role="user")

import datetime

app = bottle.app()
session_opts = {
    'session.cookie_expires': True,
    'session.encrypt_key': 'please use a random key and keep it secret!',
    'session.httponly': True,
    'session.timeout': 3600 * 24,  # 1 day
    'session.type': 'cookie',
    'session.validate_key': True,
}
app = SessionMiddleware(app, session_opts)

# #  Bottle methods  # #


def postd():
    return bottle.request.forms


def post_get(name, default=''):
    return bottle.request.POST.get(name, default).strip()


@bottle.post('/login')
def login():
    """Authenticate users"""
Ejemplo n.º 21
0
def get_app_webui():
    """
    Return global application object
    """
    global app_webui
    return app_webui


# --------------------------------------------------------------------------------------------------
# WebUI application is default bottle app
bottle_app = bottle.app()

# Bottle templates path
bottle.TEMPLATE_PATH.append(
    os.path.join(os.path.abspath(os.path.dirname(__file__)), 'views'))

# Extend default WSGI application with a session middleware
session_opts = {
    # Important: somedata stored in the session cannot be pickled. Using file is not allowed!
    'session.type': 'memory',
    'session.data_dir': os.path.join('/tmp', __name__, 'sessions'),
    'session.auto': True,
    'session.cookie_expires': 21600,  # 6 hours
    'session.key': __application__,
    'sesssion.webtest_varname': __application__,  # For unit tests ...
    'session.data_serializer':
    'json'  # Default is pickle ... not appropriate for our data!
}
webapp = SessionMiddleware(bottle_app, session_opts)
Ejemplo n.º 22
0
    def __init__(self, app, pm, engine):
        self.pm = pm
        SessionMiddleware.__init__(self, app)

        SimplePlugin.__init__(self, engine)
        self.subscribe()
Ejemplo n.º 23
0
def main():
    servicebroker = appcelerator.service_broker_factory({})
    app = SessionMiddleware(servicebroker, key='appc22_session_key', secret='secretsecretsecret')
    
    util.run_wsgi_app(app)
Ejemplo n.º 24
0
from bottle import Bottle, run, template, request, static_file
from beaker.middleware import SessionMiddleware
from os.path import abspath, dirname, join
app = Bottle()

#
# Beaker cookie handler configuration
#

session_options = {
    'session.type': 'file',
    'session.data_dir': './session/',
    'session.auto': True,
}

app_middleware = SessionMiddleware(app, session_options)


@app.hook('before_request')
def setup_request():
    """
    pre-assign request.session for cookie access before every 
    request
    """
    request.session = request.environ['beaker.session']


#
# Static files configuration for CSS, Javascript etc
#
Ejemplo n.º 25
0
def create_app(config='config.ProductionDevelopmentConfig', apptype='profi'):
    app = Flask(__name__, static_folder='./static')

    app.config.from_object(config)
    # babel = Babel(app)

    app.teardown_request(close_database)

    app.debug = app.config['DEBUG'] if 'DEBUG' in app.config else False
    app.testing = app.config['TESTING'] if 'TESTING' in app.config else False

    app.before_request(load_database(app.config['SQLALCHEMY_DATABASE_URI']))
    app.before_request(lambda: load_user(apptype))
    app.before_request(setup_authomatic(app))

    def add_map_headers_to_less_files(response):
        response.headers.add('Access-Control-Allow-Origin', '*')
        if request.path and re.search(r'\.css$', request.path):
            mapfile = re.sub(r'\.css$', r'.css.map', request.path)
            if os.path.isfile(
                    os.path.realpath(os.path.dirname(__file__)) + mapfile):
                response.headers.add('X-Sourcemap', mapfile)
        return response

    app.after_request(add_map_headers_to_less_files)

    if apptype == 'front':

        # relative paths
        def join_path(template, parent):
            return os.path.join(os.path.dirname(parent), template)

        app.jinja_env.join_path = join_path

        def load_portal():
            # class RelEnvironment(jinja2.Environment):
            #     """Override join_path() to enable relative template paths."""
            #     def join_path(self, template, parent):
            #         return os.path.join(os.path.dirname(parent), template)

            from profapp.models.portal import Portal
            portal = g.db.query(Portal).filter_by(host=request.host).first()
            # portal = g.db.query(Portal).filter_by(host=request.host).one()
            g.portal = portal if portal else None
            g.portal_id = portal.id if portal else None
            g.portal_layout_path = portal.layout.path if portal else ''
            g.lang = g.portal.lang if g.portal else g.user_dict[
                'lang'] if portal else 'en'

        app.before_request(load_portal)
        from profapp.controllers.blueprints_register import register_front as register_blueprints_front
        register_blueprints_front(app)

    elif apptype == 'static':
        from profapp.controllers.blueprints_register import register_static as register_blueprints_static
        register_blueprints_static(app)
    elif apptype == 'file':
        from profapp.controllers.blueprints_register import register_file as register_blueprints_file
        register_blueprints_file(app)
    else:
        from profapp.controllers.blueprints_register import register_profi as register_blueprints_profi
        register_blueprints_profi(app)

    bootstrap.init_app(app)
    mail.init_app(app)
    # moment.init_app(app)
    login_manager.init_app(app)
    login_manager.session_protection = 'basic'

    @login_manager.user_loader
    def load_user_manager(user_id):
        return g.db.query(User).get(user_id)

    # csrf.init_app(app)

    # read this: http://stackoverflow.com/questions/6036082/call-a-python-function-from-jinja2
    # app.jinja_env.globals.update(flask_endpoint_to_angular=flask_endpoint_to_angular)

    def raise_helper(msg):
        raise Exception(msg)

    app.jinja_env.globals.update(raw_url_for=raw_url_for)
    app.jinja_env.globals.update(pre=pre)
    app.jinja_env.globals.update(utils=utils)
    app.jinja_env.globals.update(translates=translates)
    app.jinja_env.globals.update(fileUrl=utils.fileUrl)
    app.jinja_env.globals.update(prImage=prImage)
    app.jinja_env.globals.update(prImageUrl=prImageUrl)
    # app.jinja_env.globals.update(url_page=url_page)
    app.jinja_env.globals.update(config_variables=config_variables)
    app.jinja_env.globals.update(_=translate_phrase)
    app.jinja_env.globals.update(moment=moment)
    app.jinja_env.globals.update(__=translate_html)
    app.jinja_env.globals['raise'] = raise_helper
    app.jinja_env.globals.update(
        tinymce_format_groups=HtmlHelper.tinymce_format_groups)
    app.jinja_env.globals.update(pr_help_tooltip=pr_help_tooltip)
    # url_regenerate

    app.jinja_env.filters['nl2br'] = nl2br
    # app.jinja_env.filters['localtime'] = localtime

    # see: http://flask.pocoo.org/docs/0.10/patterns/sqlalchemy/
    # Flask will automatically remove database sessions at the end of the
    # request or when the application shuts down:
    # from db_init import db_session

    # @app.teardown_appcontext
    # def shutdown_session(exception=None):
    #     try:
    #         db_session.commit()
    #     except Exception:
    #         session.rollback()
    #         raise
    #     finally:
    #         session.close()  # optional, depends on use case
    #     # db_session.remove()

    session_opts = {
        'session.type': 'ext:memcached',
        'session.url': 'memcached.profi:11211'
    }

    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()

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

    return app
Ejemplo n.º 26
0
    return output


@get('/signin')
def contactus():
    output = template('signin.tpl')
    return output


@post('/googlesignin')
def google():
    if oauth.validateGoogle():
        return HTTPResponse(body='', status=200, headers=None)
    else:
        return HTTPError(status=500, body=None, exception=None, traceback=None)


@post('/facebooksignin')
def facebook():
    if oauth.validateFacebook():
        return HTTPResponse(status=200)
    else:
        return HTTPError(status=500)


if __name__ == "__main__":
    app = SessionMiddleware(bottle.app(), session_opts)
    debug(True)
    bottle.run(app=app, host='localhost', port=8080, reloader=True)
else:
    application = SessionMiddleware(default_app(), session_opts)
Ejemplo n.º 27
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(config=config)

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

    # 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])
    app.config = config

    # gzip middleware
    app = make_gzip_middleware(app, config)

    # Add Access-Control headers
    if 'allowed_origins' in config:
        log.info("Adding ControlHeadersMiddleware")
        app = ControlHeadersMiddleware(app, config)
    return app
Ejemplo n.º 28
0
                                     post['update[%s][id]' % i]))
                if 'delete[]' in post:
                    for row in list(post.getall('delete[]')):
                        if row != '':
                            cur.execute(
                                "delete from " + table + " where id = %s"
                                "", (int(row), ))

                page = """{"result":"ok"}"""
                response = Response(body=page,
                                    content_type="application/json",
                                    charset="utf8",
                                    status="200 OK")
            else:
                page = pyad.login.login_again
                response = Response(body=page,
                                    content_type="text/html",
                                    charset="utf8",
                                    status="200 OK")
        con.commit()
        cur.close()
        con.close()

    return response(environment, start_response)


import pyad.sess
importlib.reload(pyad.sess)
session_opts = pyad.sess.session_opts
application = SessionMiddleware(application, session_opts)
Ejemplo n.º 29
0
if __name__ == '__main__':
    from beaker.middleware import SessionMiddleware
    from cherrypy import wsgiserver

    KW_ARGS = main_setup(logger)

    _conf = KW_ARGS["conf"]
    session_opts = {
        'session.type': 'memory',
        'session.cookie_expires': True,
        'session.auto': True,
        'session.timeout': 900
    }

    SRV = wsgiserver.CherryPyWSGIServer(
        ('0.0.0.0', _conf.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" % _conf.PORT)
    print("RP server starting listening on port:%s" % _conf.PORT)
    try:
        SRV.start()
    except KeyboardInterrupt:
        SRV.stop()
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 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(config=config)

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

    # 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, [417])
        else:
            app = StatusCodeRedirect(app, [400, 401, 403, 404, 417, 500])

    # authenticator = OCSAuthenticator(config)
    # app = AuthBasicHandler(app, "OCSManager", authenticator)
    fqdn = "%(hostname)s.%(dnsdomain)s" % config["samba"]
    auth_handler = NTLMAuthHandler(app)

    def ntlm_env_setter(environ, start_response):
        for var in ["SAMBA_HOST", "NTLMAUTHHANDLER_WORKDIR"]:
            try:
                environ[var] = app_conf[var]
            except KeyError:
                # FIXME: logging?
                pass
        return auth_handler(environ, start_response)

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

    if asbool(static_files):
        # Serve static files
        static_app = StaticURLParser(config['pylons.paths']['static_files'])
        app = Cascade([static_app, app])
    app.config = config
    return app
Ejemplo n.º 31
0
from flask import Flask, render_template
import json
from application import application
import sample
import folders
import login
import register
import registration
from beaker.middleware import SessionMiddleware

session_opts = {
    #'session.type': 'ext:memcached',
	'session.type': 'cookie',
	'session.validate_key': 'abc',
    'session.url': '127.0.0.1:5001',
    'session.data_dir': './cache',
	'session.auto': True,
	'session.save_accessed_time': True
}

@application.route('/')
def root():
    return render_template('sample.html')

if __name__ == '__main__':
	application.wsgi_app = SessionMiddleware(application.wsgi_app,session_opts)
	application.run(debug=True, threaded=True, port=5001)
Ejemplo n.º 32
0
        return "Restricted area <br> <a href='/logout'>Log out</a>"
    else:
        return "Aðgangur bannaður"


@route('/logout')
def logout():
    response.set_cookie('user', "", expires=0)
    return "Þú hefur verið skráður út. <br> <a href='/login'>Login</a>"


#Session lausn

session_options = {'session.type': 'file', 'session.data_dir': './data/'}

my_session = SessionMiddleware(app(), session_options)

products = [{
    'pid': 1,
    'name': 'Vara 1',
    'price': 100
}, {
    'pid': 2,
    'name': 'Vara 2',
    'price': 400
}, {
    'pid': 3,
    'name': 'Vara 3',
    'price': 200
}, {
    'pid': 4,
Ejemplo n.º 33
0
@post('/setVal')
def setVal():
    try:
        # 短暂休眠,模拟计算消耗
        time.sleep(0.001)
        data = request.json
        key = data["key"]
        val = data["val"]
        dbMgr.set_val(key, val)
        # 不可以返回数字,会说object is not iterable
        # return 1
        return "1"
    except Exception as e:
        print('getsetValVal, error:', e.value)
        return "-1"


# 函数主入口
if __name__ == '__main__':
    argv = sys.argv
    print(argv)
    port = int(argv[1])
    app_argv = SessionMiddleware(default_app(), session_opts)
    # 通知负载均衡,服务器准备就绪
    headers = {'content-type': 'application/json'}
    data = {'ip': "127.0.0.1", 'port': port}
    response = requests.post(_add_svr_path,
                             data=json.dumps(data),
                             headers=headers)
    run(app=app_argv, host='0.0.0.0', port=port, debug=True, reloader=True)
Ejemplo n.º 34
0
reload(sys)
sys.setdefaultencoding('utf-8')


T.insert(0, TEMPLATE_PATH)

session_opts = {
    'session.type': 'file',
    'session.data_dir': '/tmp/openmining.data',
    'session.lock_dir': '/tmp/openmining.lock',
    'session.cookie_expires': 50000,
    'session.auto': True
}

app = SessionMiddleware(Bottle(), session_opts)
app.wrap_app.mount('/api', api_app)
app.wrap_app.mount('/stream', stream_app)
app.wrap_app.mount('/export', export_app)

app.wrap_app.install(auth)


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


@app.wrap_app.route('/')
@login()
@view('index.html')
Ejemplo n.º 35
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()

    # 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])

    # 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.º 36
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 TG 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 sessions
    app = SessionMiddleware(app, config, data_serializer=BeakerPickleSerializerWithLatin1())
    # 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=True,
        use_cache=not asbool(global_conf['debug']),
        script_name=app_conf.get('ew.script_name', '/_ew_resources/'),
        url_base=app_conf.get('ew.url_base', '/_ew_resources/'),
        extra_headers=ast.literal_eval(app_conf.get('ew.extra_headers', '[]')),
        cache_max_age=asint(app_conf.get('ew.cache_header_seconds', 60*60*24*365)),

        # settings to pass through to jinja Environment for EW core widgets
        # these are for the easywidgets' own [easy_widgets.engines] entry point
        # (the Allura [easy_widgets.engines] entry point is named "jinja" (not jinja2) but it doesn't need
        #  any settings since it is a class that uses the same jinja env as the rest of allura)
        **{
            'jinja2.auto_reload': asbool(config['auto_reload_templates']),
            'jinja2.bytecode_cache': AlluraJinjaRenderer._setup_bytecode_cache(),
            'jinja2.cache_size': asint(config.get('jinja_cache_size', -1)),
        }
    )
    # 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') not in ('task', 'basetest_project_root'):
        if asbool(config['debug']):
            # 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['tg.errorware'])
        else:
            app = ErrorMiddleware(app, config, **config['tg.errorware'])

        app = SetRequestHostFromConfig(app, config)

        # 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.º 37
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__)
    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

    app.jinja_options = jinja_extensions.get_jinja_env_options()
    # 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)

    # 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 = dict([(k.replace('beaker.', ''), v)
                        for k, v in config.iteritems()
                        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)

    @app.route('/hello', methods=['GET'])
    def hello_world():
        return 'Hello World, this is served by Flask'

    @app.route('/hello', methods=['POST'])
    def hello_world_post():
        return 'Hello World, this was posted to Flask'

    # 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'):
            app.register_extension_blueprint(plugin.get_blueprint())

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

    # Set flask routes in 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
    if debug:
        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,
        }
    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]

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

    return app
Ejemplo n.º 38
0
        'map_prof': PROFILEMAP,
        'client_factory': Factory(Client)
    })

    WA = WebApplication(sessionhandler=SessionHandler,
                        webio=WebIh,
                        webtester=WebTester,
                        check=check,
                        webenv=app_args,
                        pick_grp=pick_grp,
                        path=_path)

    _conf = app_args['conf']

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

    if args.tls:
        from cherrypy.wsgiserver.ssl_builtin import BuiltinSSLAdapter

        SRV.ssl_adapter = BuiltinSSLAdapter(_conf.SERVER_CERT,
                                            _conf.SERVER_KEY, _conf.CERT_CHAIN)
        extra = " using SSL/TLS"
    else:
        extra = ""

    print(_path)
    txt = "AS test server starting listening on port:%s%s" % (args.port, extra)
    logger.info(txt)
    print(txt)
    try:
Ejemplo n.º 39
0
 def session_middleware(self, app):
     return SessionMiddleware(app, session.config)
Ejemplo n.º 40
0
from bottle import app as bottleapp
from bottle import run, route, request, template, static_file, abort
from beaker.middleware import SessionMiddleware
from json import dumps
from random import randint

beaker_opts = {
    'session.type': 'file',
    'session.data_dir': '.',
    'session.auto': True
}

app = SessionMiddleware(bottleapp(), beaker_opts)

@route('/assets/<filename:path>')
def assets(filename):
    return static_file(filename, root='./assets/')

@route('/')
def index():
    s = request.environ['beaker.session']

    s['count'] = 0
    s['num'] = randint(1, 100)
    s['num'] = 87
    s.save()

    return template('index.html', locals())

@route('/get/<num:int>')
def get(num):
Ejemplo n.º 41
0
#! /usr/bin/env python2

from bottle import route, run, template, request, app, redirect, static_file
from beaker.middleware import SessionMiddleware
import sys

session_opts = {
    'session.type': 'file',
    'session.cookie_expires': 300000,
    'session.data_dir': '/tmp/session',
    'session.auto': True,
    'session.key': "sessionid"
}

app = application = myapp = SessionMiddleware(app(), session_opts)


@route('/')
def root_page():
    session = request.environ.get('beaker.session')
    if ('log_in' in session and session['log_in'] == True):
        return template("welcome.html", name=session['login'])
    else:
        session['log_in'] = False
        redirect("/login")


@route('/login')
def authentication():
    username = request.params.get('username')
    password = request.params.get('password')
Ejemplo n.º 42
0
 def __init__(self, app):
     SessionMiddleware.__init__(self, app, self.get_beaker_opts())
Ejemplo n.º 43
0
class AddressServer(Application):

    """
    This class is the gunicorn wrapper to serve up bottle.

    Strongly borrowed from:
    http://damianzaremba.co.uk/2012/08/running-a-wsgi-
    app-via-gunicorn-from-python/

    """

    def __init__(self, options={}):
        self.usage = None
        self.callable = None
        self.prog = None
        self.options = options
        self.do_load_config()

        self.setup_cork()

        super(AddressServer, self).__init__()
        self.app = Bottle()
        self.add_routes()
        self.add_middleware()

    def setup_cork(self):
        """Set up cork using environment variables."""

        EMAIL = os.environ.get('EMAIL_SENDER')
        EMAIL_PASS = os.environ.get('EMAIL_PASSWORD')
        self.MONGO_DB = os.environ.get('MONGOHQ_DB')
        self.MONGO_URL = os.environ.get('MONGOHQ_URL')
        mb = MongoDBBackend(self.MONGO_DB, self.MONGO_URL)
        self.loginPlugin = Cork(backend=mb, email_sender=EMAIL,
                                smtp_url='starttls://' + EMAIL + ':' +
                                EMAIL_PASS + '@smtp.gmail.com:587')

    def add_middleware(self):
        """Set up the session middleware."""

        ENCRYPT_KEY = os.environ.get('ENCRYPT_KEY')
        session_opts = {
            'session.cookie_expires': True,
            'session.encrypt_key': ENCRYPT_KEY,
            'session.httponly': True,
            'session.timeout': 3600 * 24,  # 1 day
            'session.type': 'cookie',
            'session.validate_key': True,
        }
        self.app = SessionMiddleware(self.app, session_opts)

    def add_routes(self):
        """Add all the application routes."""

        self.app.route(LOGIN_PATH, 'GET', callback=get_login)
        self.app.route(LOGIN_PATH, 'POST', callback=post_login,
                       apply=self.add_login_plugin)
        self.app.route('/logout', 'GET', callback=logout,
                       apply=self.add_login_plugin)
        self.app.route('/register', 'GET', callback=get_register,
                       apply=self.add_login_plugin)
        self.app.route('/register', 'POST', callback=post_register,
                       apply=self.add_login_plugin)
        self.app.route(VALIDATE_REGISTRATION_PATH + '/<registration_code>',
                       'GET', callback=validate_registration,
                       apply=self.add_login_plugin)
        self.app.route(CHANGE_PASSWORD_PATH + '/<reset_code>', 'GET',
                       callback=get_change_password)
        self.app.route(CHANGE_PASSWORD_PATH, 'POST',
                       callback=post_change_password,
                       apply=self.add_login_plugin)
        self.app.route('/reset_password', 'GET', callback=get_reset_password)
        self.app.route('/reset_password', 'POST', callback=post_reset_password,
                       apply=self.add_login_plugin)
        self.app.route('/', 'GET', callback=index, apply=self.check_login)
        self.app.route('/addresses', 'GET', callback=get_addresses,
                       apply=self.check_login)
        self.app.route('/addresses', 'POST', callback=post_addresses,
                       apply=self.check_login)
        self.app.route('/addresses', 'PUT', callback=put_addresses,
                       apply=self.check_login)
        self.app.route('/addresses/<deleteId>', 'DELETE',
                       callback=delete_addresses, apply=self.check_login)
        self.app.route('/csv', 'GET', callback=csv_export,
                       apply=self.check_login)
        self.app.route('/christmas_card', 'GET',
                       callback=christmas_card_csv_export,
                       apply=self.check_login)
#        self.app.route('/import_csv', 'GET', callback=csv_import,
#                       apply=self.check_login)

        self.app.route('/js/<filename>', 'GET', callback=js_static)
        self.app.route('/css/<filename>', 'GET', callback=css_static)

    def init(self, *args):
        """Add any options passed in to the config.

        :param *args: the arguments of the application
        :returns: config object
        :rtype: dict

        """

        cfg = {}
        for k, v in self.options.items():
            if k.lower() in self.cfg.settings and v is not None:
                cfg[k.lower()] = v
        return cfg

    def load(self):
        """Load and return the bottle app."""

        return self.app

    @hook('before_request')
    def check_login(self, fn):
        """Hook for checking the login before doing logic.

        :param fn: the function to call if the user is logged in
        :returns: the wrapped function
        :rtype: def

        """

        def check_uid(**kwargs):
            self.loginPlugin.require(fail_redirect=LOGIN_PATH)
            kwargs["helper"] = AddressModel(self.MONGO_URL, self.MONGO_DB)
            kwargs["userName"] = self.loginPlugin.current_user.username
            return fn(**kwargs)
        return check_uid

    @hook('before_request')
    def add_login_plugin(self, fn):
        """Hook for adding the plugin information.

        :param fn: the function to pass the plugin
        :returns: the wrapped function
        :rtype: def

        """

        def add_plugin(**kwargs):
            kwargs["loginPlugin"] = self.loginPlugin
            return fn(**kwargs)
        return add_plugin