Пример #1
0
    def __init__(self,
                 wrap_app,
                 config=None,
                 environ_key='beaker.session',
                 **kwargs):
        """Initialize the Session Middleware
        
        The Session middleware will make a lazy session instance available
        every request under the ``environ['beaker.session']`` key by
        default. The location in environ can be changed by setting
        ``environ_key``.
        
        ``config``
            dict  All settings should be prefixed by 'session.'. This method of
            passing variables is intended for Paste and other setups that
            accumulate multiple component settings in a single dictionary. If
            config contains *no cache. prefixed args*, then *all* of the config
            options will be used to intialize the Cache objects.
        
        ``environ_key``
            Location where the Session instance will keyed in the WSGI environ
        
        ``**kwargs``
            All keyword arguments are assumed to be cache settings and will
            override any settings found in ``config``
        """
        config = config or {}

        # Load up the default params
        self.options = dict(invalidate_corrupt=True,
                            type=None,
                            data_dir=None,
                            key='beaker.session.id',
                            timeout=None,
                            secret=None,
                            log_file=None)

        # Pull out any config args meant for beaker session. if there are any
        for dct in [config, kwargs]:
            for key, val in dct.iteritems():
                if key.startswith('beaker.session.'):
                    self.options[key[15:]] = val
                if key.startswith('session.'):
                    self.options[key[8:]] = val
                if key.startswith('session_'):
                    warnings.warn(
                        'Session options should start with session. '
                        'instead of session_.', DeprecationWarning, 2)
                    self.options[key[8:]] = val

        # Coerce and validate session params
        coerce_session_params(self.options)

        # Assume all keys are intended for cache if none are prefixed with 'cache.'
        if not self.options and config:
            self.options = config

        self.options.update(kwargs)
        self.wrap_app = wrap_app
        self.environ_key = environ_key
Пример #2
0
    def __init__(self, handler, config):
        super(SessionApplicationWrapper, self).__init__(handler, config)

        if SessionObject is None:  # pragma: no cover
            log.debug('Beaker not available, session disabled')
            self.enabled = False
            return

        # Load up the default params
        self.options = dict(invalidate_corrupt=True, type=None,
                            data_dir=None, key='beaker.session.id',
                            timeout=None, secret=None, log_file=None)

        # Pull out any config args meant for beaker session. if there are any
        for key, val in config.items():
            if key.startswith('beaker.session.'):
                warnings.warn('Session options should start with session. '
                              'instead of baker.session.', DeprecationWarning, 2)
                self.options[key[15:]] = val
            elif key.startswith('session.'):
                self.options[key[8:]] = val

        # Coerce and validate session params
        from beaker.util import coerce_session_params
        coerce_session_params(self.options)

        self.enabled = asbool(self.options.pop('enabled', True))

        log.debug('Sessions enabled: %s -> %s',
                  self.enabled, self.options)
Пример #3
0
 def __init__(self, **session_args):
     # Default parameters from beaker.middleware.SessionMiddleware
     self.options = dict(invalidate_corrupt=True, type=None,
                         data_dir=None, key='beaker.session.id',
                         timeout=None, secret=None, log_file=None)
     self.options.update(session_args)
     coerce_session_params(self.options)
Пример #4
0
    def __init__(self, handler, config):
        super(SessionApplicationWrapper, self).__init__(handler, config)

        if SessionObject is None:  # pragma: no cover
            log.debug('Beaker not available, session disabled')
            self.enabled = False
            return

        # Load up the default params
        self.options = dict(invalidate_corrupt=True,
                            type=None,
                            data_dir=None,
                            key='beaker.session.id',
                            timeout=None,
                            secret=None,
                            log_file=None)

        # Pull out any config args meant for beaker session. if there are any
        for key, val in config.items():
            if key.startswith('beaker.session.'):
                warnings.warn(
                    'Session options should start with session. '
                    'instead of baker.session.', DeprecationWarning, 2)
                self.options[key[15:]] = val
            elif key.startswith('session.'):
                self.options[key[8:]] = val

        # Coerce and validate session params
        from beaker.util import coerce_session_params
        coerce_session_params(self.options)

        self.enabled = asbool(self.options.pop('enabled', True))

        log.debug('Sessions enabled: %s -> %s', self.enabled, self.options)
Пример #5
0
    def __init__(self, wrap_app, config=None, environ_key='beaker.session',
                 **kwargs):
        """Initialize the Session Middleware

        The Session middleware will make a lazy session instance
        available every request under the ``environ['beaker.session']``
        key by default. The location in environ can be changed by
        setting ``environ_key``.

        ``config``
            dict  All settings should be prefixed by 'session.'. This
            method of passing variables is intended for Paste and other
            setups that accumulate multiple component settings in a
            single dictionary. If config contains *no session. prefixed
            args*, then *all* of the config options will be used to
            intialize the Session objects.

        ``environ_key``
            Location where the Session instance will keyed in the WSGI
            environ

        ``**kwargs``
            All keyword arguments are assumed to be session settings and
            will override any settings found in ``config``

        """
        config = config or {}

        # Load up the default params
        self.options = dict(invalidate_corrupt=True, type=None,
                            data_dir=None, key='beaker.session.id',
                            timeout=None, save_accessed_time=True, secret=None,
                            log_file=None)

        # Pull out any config args meant for beaker session. if there are any
        for dct in [config, kwargs]:
            for key, val in dct.items():
                if key.startswith('beaker.session.'):
                    self.options[key[15:]] = val
                if key.startswith('session.'):
                    self.options[key[8:]] = val
                if key.startswith('session_'):
                    warnings.warn('Session options should start with session. '
                                  'instead of session_.', DeprecationWarning, 2)
                    self.options[key[8:]] = val

        # Coerce and validate session params
        coerce_session_params(self.options)

        # Assume all keys are intended for session if none are prefixed with
        # 'session.'
        if not self.options and config:
            self.options = config

        self.options.update(kwargs)
        self.wrap_app = self.app = wrap_app
        self.environ_key = environ_key
Пример #6
0
    def __init__(self, config=None, environ_key='seminode.session',
                 **kwargs):
        """
        Initialize the Session Filter
        
        The Session Filter will make a lazy session instance
        available every request under the ``environ['seminode.session']``
        key by default. The location in environ can be changed by
        setting ``environ_key``.
        
        ``config``
            dict  All settings should be prefixed by 'session.'. This
            method of passing variables is intended for Paste and other
            setups that accumulate multiple component settings in a
            single dictionary. If config contains *no cache. prefixed
            args*, then *all* of the config options will be used to
            intialize the Cache objects.
        
        ``environ_key``
            Location where the Session instance will keyed in the WSGI
            environ
        
        ``**kwargs``
            All keyword arguments are assumed to be session settings and
            will override any settings found in ``config``

        """
        self.logger = logging.getLogger("seminode.web.wsgi.filter.HttpSessionContextFilter")
        
        
        config = config or {}
        
        # Load up the default params
        self.options = dict(invalidate_corrupt=True, type=None, auto=True,
                           data_dir='var/sessions', key='seminode.session.id',
                           timeout=None, secret=None, log_file=None)
        
        # Pull out any config args meant for beaker session. if there are any
        for dct in [config, kwargs]:
            for key, val in dct.iteritems():
                if key.startswith('seminode.session.'):
                    self.options[key[17:]] = val
                if key.startswith('session.'):
                    self.options[key[8:]] = val
        
        # Coerce and validate session params
        coerce_session_params(self.options)
        
        if not self.options and config:
            self.options = config
        
        self.options.update(kwargs)
        self.environ_key = environ_key
        self.print_log(self.options, "Options")
Пример #7
0
def beakerConfiguration(_context):
    """Read configuration from zope.conf and register components accordingly.

    This may result in one or two unnamed utilities:

    * ISessionConfig, a dictionary of session parameters from zope.conf
    * ICacheManager, a Beaker CacheManager instance configured from zope.conf
    """
    cfg = getConfiguration()

    if not hasattr(cfg, 'product_config'):
        return

    beakerConfig = cfg.product_config.get('beaker', {})

    if not beakerConfig:
        return

    cacheConfig = parse_cache_config_options(beakerConfig)

    sessionConfig = {}
    for key, value in beakerConfig.items():
        if key.startswith('session.'):
            sessionConfig[key[8:]] = value
        elif key.startswith('beaker.session.'):
            sessionConfig[key[15:]] = value
    coerce_session_params(sessionConfig)

    # If we have cache config, register an ICacheManager utility
    if cacheConfig:
        cacheManager = CacheManager(**cacheConfig)
        _context.action(
            discriminator=('utility', ICacheManager, u""),
            callable=handler,
            args=('registerUtility', cacheManager, ICacheManager, u""),
            kw=dict(info=cacheConfig),
        )

    # If we have session config, register these as an ISessionConfig
    # utility, which will then be looked up when the session factory is
    # invoked.
    if sessionConfig:

        # Set defaults for keys not set in the configuration
        sessionConfigWithDefaults = defaultSessionConfig.copy()
        sessionConfigWithDefaults.update(sessionConfig)

        _context.action(
            discriminator=('utility', ISessionConfig, u""),
            callable=handler,
            args=('registerUtility', sessionConfigWithDefaults,
                  ISessionConfig, u""),
            kw=dict(info=sessionConfig),
        )
def initialize_https_session_support(config, settings):
    """
    Parses config settings, builds a https session factory, registers it
    """
    https_options = {}
    https_prefixes = ('session_https.',
                      'beaker.session_https.',
                      )
    for k, v in settings.items():
        for prefix in https_prefixes:
            if k.startswith(prefix):
                option_name = k[len(prefix):]
                if option_name == 'cookie_on_exception':
                    v = asbool(v)
                https_options[option_name] = v

    # ensure compatibility with our options
    RedisConfigurator.ensure_compatibility(https_options)
    RedisConfigurator.ensure_security(config, https_options)
    RedisConfigurator.cleanup_options(https_options)

    # build a session
    https_options = coerce_session_params(https_options)
    https_session_factory = config.maybe_dotted(BeakerSessionFactoryConfig(**https_options))
    
    # okay!  register our factory
    pyramid_https_session_core.register_https_session_factory(config,
                                                              settings,
                                                              https_session_factory
                                                              )
    def apply(self, callback, context):
        conf = context['config'].get(self.name, {})
        keyword = conf.get('keyword', self.keyword)

        args = getargspec(context['callback'])[0]
        if keyword not in args:
            return callback

        route_config = conf.get('config', None)
        if route_config is None:
            config = self.config
        else:
            config = self.config.copy()
            config.update(coerce_session_params(route_config))

        def wrapper(*args, **kwargs):
            session = BottleBeakerSessionObject(request.environ, **config)
            kwargs[keyword] = session

            try:
                rv = callback(*args, **kwargs)
            finally:
                if session.accessed():
                    session.persist()
                    if session.__dict__['_headers']['set_cookie']:
                        cookie = session.__dict__['_headers']['cookie_out']
                        if cookie:
                            response.set_header('Set-Cookie', cookie.lstrip(), True)
            return rv

        return wrapper
Пример #10
0
def current_participant(request, dbsession, experiment, allow_create=True):
    """Get the current Participant or create a new one."""
    session = SessionObject(request.environ,
                            **coerce_session_params({'type': 'cookie',
                                                     'cookie_expires': 7776000,
                                                     'key': 'experiment.%s' % (experiment.external_id),
                                                     'encrypt_key':
                                                     get_config_setting(request, 'beaker.session.encrypt_key'),
                                                     'validate_key':
                                                     get_config_setting(request, 'beaker.session.validate_key'),
                                                     'auto': True}))
    if 'pid' in session:
        participant = dbsession.query(Participant).filter(and_(Participant.id == session['pid'],
                                                               Participant.experiment_id == experiment.id)).first()
    else:
        participant = None
    if participant is None:
        if allow_create:
            participant = Participant(experiment_id=experiment.id,
                                      completed=False)
            participant['current'] = experiment.start.id
            participant['answered'] = []
            dbsession.add(participant)
            dbsession.flush()
        else:
            return None
    session['pid'] = participant.id
    session.persist()
    request.response.headerlist.append(('Set-Cookie', session.__dict__['_headers']['cookie_out']))
    return participant
Пример #11
0
def completed(request):
    dbsession = DBSession
    with transaction.manager:
        experiment = dbsession.query(Experiment).filter(Experiment.external_id == request.matchdict['ueid']).first()
        if experiment is None:
            raise HTTPNotFound()
        if experiment.status in ['paused', 'completed']:
            raise HTTPFound(request.route_url('experiment.unavailable', ueid=experiment.external_id))
        participant = current_participant(request, dbsession, experiment, allow_create=False)
        if participant is None:
            if experiment.status == 'develop':
                raise HTTPFound(request.route_url('experiment.test', ueid=experiment.external_id))
            else:
                raise HTTPFound(request.route_url('experiment.run', ueid=experiment.external_id))
        participant.completed = True
    dbsession.add(experiment)
    dbsession.add(participant)
    if experiment.status == 'develop':
        session = SessionObject(request.environ,
                                **coerce_session_params({'type': 'cookie',
                                                         'cookie_expires': 7776000,
                                                         'key': 'experiment.%s' % (experiment.external_id),
                                                         'encrypt_key':
                                                         get_config_setting(request, 'beaker.session.encrypt_key'),
                                                         'validate_key':
                                                         get_config_setting(request, 'beaker.session.validate_key'),
                                                         'auto': True}))
        session['pid'] = -1
        session.persist()
        request.response.headerlist.append(('Set-Cookie', session.__dict__['_headers']['cookie_out']))
    return {'experiment': experiment,
            'participant': participant}
def session_factory_from_settings(settings):
    """ Return a Pyramid session factory using Beaker session settings
    supplied from a Paste configuration file"""
    prefixes = ('session.', 'beaker.session.')
    options = {}

    # Pull out any config args meant for beaker session. if there are any
    for k, v in settings.items():
        for prefix in prefixes:
            if k.startswith(prefix):
                option_name = k[len(prefix):]
                if option_name == 'cookie_on_exception':
                    v = asbool(v)
                options[option_name] = v

    # transpose an elasticache config url into actual node urls
    if 'type' in options and options['type'] == 'ext:elasticache-memcached':
        options['type'] = 'ext:memcached'
        if 'url' in options:
            uarr = options['url'].split(':')
            host = uarr[0]
            port = len(uarr) == 2 and int(uarr[1]) or 11211
            info = get_cluster_info(host, port)
            options['url'] = ';'.join(info['nodes'])

    options = coerce_session_params(options)
    return BeakerSessionFactoryConfig(**options)
Пример #13
0
    def setup_sessions(self, config):
        """Initialize the session."""
        # default options
        self.session_options = dict(invalidate_corrupt=True,
                                    type=None,
                                    data_dir=None,
                                    key='beaker.session.id',
                                    timeout=None,
                                    secret=None,
                                    log_file=None)

        # pull out any config args meant for beaker session
        for key, val in config.items():
            if key.startswith('session.'):
                self.session_options[key[8:]] = val

        # coerce and validate session params
        coerce_session_params(self.session_options)
Пример #14
0
    def __init__(self, options=None):
        # defaults of Beaker's SessionMiddleware
        self.options = {
                'invalidate_corrupt': True,
                'type': None,
                'data_dir': None,
                'key': 'beaker.session.id',
                'timeout': None,
                'secret': None,
                'log_file': None,
                }

        if options is not None:
            # Simplify the filtering present in Beaker's implementation
            # This is also required to mimic the 'Assume all keys are
            # intended for cache if none are prefixed w/ "cache."' behavior
            for k, v in options.iteritems():
                if k.startswith('session.'):
                    self.options[k[8:]] = v

        coerce_session_params(self.options)

        if not self.options and options:
            self.options = options
Пример #15
0
Файл: session.py Проект: 3divs/h
def session_factory_from_settings(settings):
    """ Return a Pyramid session factory using Beaker session settings
    supplied from a Paste configuration file"""
    prefixes = ('session.', 'beaker.session.')
    options = {}

    # Pull out any config args meant for beaker session. if there are any
    for k, v in settings.items():
        for prefix in prefixes:
            if k.startswith(prefix):
                option_name = k[len(prefix):]
                if option_name == 'cookie_on_exception':
                    v = asbool(v)
                options[option_name] = v

    options = coerce_session_params(options)
    return AngularSessionFactoryConfig(**options)
Пример #16
0
def session_factory_from_settings(settings):
    """ Return a Pyramid session factory using Beaker session settings
    supplied from a Paste configuration file"""
    prefixes = ('session.', 'beaker.session.')
    options = {}

    # Pull out any config args meant for beaker session. if there are any
    for k, v in settings.items():
        for prefix in prefixes:
            if k.startswith(prefix):
                option_name = k[len(prefix):]
                if option_name == 'cookie_on_exception':
                    v = asbool(v)
                options[option_name] = v

    options = coerce_session_params(options)
    return BeakerSessionFactoryConfig(**options)
def main(global_config, **settings):
    ...

    https_options= {}
    https_prefixes = ('session_https.', 'beaker.session_https.')
    for k, v in settings.items():
        for prefix in https_prefixes:
            if k.startswith(prefix):
                option_name = k[len(prefix):]
                if option_name == 'cookie_on_exception':
                    v = asbool(v)
                https_options[option_name] = v
    
    # setting this true should work...
    https_options['secure']= True
    
    https_options = coerce_session_params(https_options)
    https_session_factory = config.maybe_dotted( BeakerSessionFactoryConfig(**https_options) )
    def register_session_https_factory():
        config.registry.registerUtility(https_session_factory, ISessionHttpsFactory)
    intr = config.introspectable('session https factory', None,
                               config.object_description(https_session_factory),
                               'session https factory')
    intr['factory'] = https_session_factory
    config.action(ISessionHttpsFactory, register_session_https_factory, introspectables=(intr,))
    
    @reify
    def session_https(self):
        """ Obtain the :term:`session_https` object associated with this
        request.  If a :term:`session_https factory` has not been registered
        during application configuration, a
        :class:`pyramid.exceptions.ConfigurationError` will be raised"""
        factory = self.registry.queryUtility(ISessionHttpsFactory)
        if factory is None:
            raise AttributeError(
                'No session_https factory registered '
                )
        return factory(self)
    
    pyramid.request.Request.session_https= session_https
    
    ...
 def __init__(self, keyword='session', config=None):
     self.config = coerce_session_params(config) if config is not None else {}
     self.keyword = keyword