Exemplo n.º 1
0
    def _setup_initialize(self, conf):
        #Set the site specific settings in config (Most params don't update the 
        #base config dict)
        for k,v in conf.items():
            if k.startswith('site_'):
                config[k] = v

        log.enabled = conf['site_debug']

        #Set up cherrypy.session?  We do this even if we're not overriding
        #sessions, since it plays nice with the builtin sessions module.
        if not hasattr(cherrypy, 'session'):
            cherrypy.session = cherrypy._ThreadLocalProxy('session')

        #Set up cherrypy.user
        if not hasattr(cherrypy, 'user'):
            cherrypy.user = cherrypy._ThreadLocalProxy('user')

        #Setup slate storage medium
        self.storage_type = conf['site_storage']
        self.storage_class = storage.get_storage_class(self.storage_type)

        config.storage_class = self.storage_class
        log('Found: ' + str(config.storage_class))
        config.storage_class.setup(conf['site_storage_conf'])

        #Setup monitor thread...
        if getattr(config, 'storage_cleanup_thread', None) is not None:
            config.storage_cleanup_thread.stop()
            config.storage_cleanup_thread.unsubscribe()
            config.storage_cleanup_thread = None
        clean_freq = conf['site_storage_clean_freq']
        if clean_freq:
            def cleanup():
                config.storage_class.clean_up()
            #Start with a bang!
            cleanup()

            config.storage_cleanup_thread = cherrypy.process.plugins.Monitor(
                cherrypy.engine, cleanup, clean_freq * 60
                ,name = 'Slate Storage Cleanup'
                )
            config.storage_cleanup_thread.subscribe()
            config.storage_cleanup_thread.start()

        #Set up the authentication system interface
        config.auth = AuthInterface()

        #Add config groups/users
        for name,data in config['site_group_list'].items():
            try:
                config.auth.group_create(name, data)
            except AuthError, e:
                log("Failed to add group {0}: {1}".format(name, str(e)))
Exemplo n.º 2
0
def init(storage_type = 'ram', path = None, path_header = None, name = 'session_id', timeout = 60, domain = None, secure = False, clean_freq = 5, persistent = True, debug = False, **kwargs):
    request = cherrypy.serving.request
    if hasattr(request, '_session_init_flag'):
        return
    request._session_init_flag = True
    id = None
    if name in request.cookie:
        id = request.cookie[name].value
        if debug:
            cherrypy.log('ID obtained from request.cookie: %r' % id, 'TOOLS.SESSIONS')
    storage_class = storage_type.title() + 'Session'
    storage_class = globals()[storage_class]
    if not hasattr(cherrypy, 'session'):
        if hasattr(storage_class, 'setup'):
            storage_class.setup(**kwargs)
    kwargs['timeout'] = timeout
    kwargs['clean_freq'] = clean_freq
    cherrypy.serving.session = sess = storage_class(id, **kwargs)
    sess.debug = debug

    def update_cookie(id):
        cherrypy.serving.response.cookie[name] = id

    sess.id_observers.append(update_cookie)
    if not hasattr(cherrypy, 'session'):
        cherrypy.session = cherrypy._ThreadLocalProxy('session')
    if persistent:
        cookie_timeout = timeout
    else:
        cookie_timeout = None
    set_response_cookie(path=path, path_header=path_header, name=name, timeout=cookie_timeout, domain=domain, secure=secure)
Exemplo n.º 3
0
    def _setup(self):
        """Hook this tool into cherrypy.request.

        Used to start slate cleanup and hook in slates.init_session

        The standard CherryPy request object will automatically call this
        method when the tool is "turned on" in config.
        """
        hooks = cherrypy.serving.request.hooks

        conf = self._merged_args()

        # Check for new storage_type mostly for unit testing (as opposed
        # to the session variable's presence)
        new_storage_type = conf.get("storage_type", "ram")
        if self.storage_type != new_storage_type:
            if not hasattr(cherrypy, "session"):
                cherrypy.session = cherrypy._ThreadLocalProxy("session")

            # Find the storage class
            self.storage_type = new_storage_type
            self.storage_class = getattr(slates, self.storage_type.title() + "Slate")

            # Setup slates and slate storage
            conf["storage_class"] = self.storage_class
            slates.Slate.setup(**conf)

        p = conf.pop("priority", None)
        if p is None:
            p = getattr(self.callable, "priority", self._priority)

        hooks.attach(self._point, self.callable, priority=p, **conf)
Exemplo n.º 4
0
def init(storage_type='ram', path=None, path_header=None, name='session_id',
         timeout=60, domain=None, secure=False, clean_freq=5, **kwargs):
    """Initialize session object (using cookies).
    
    storage_type: one of 'ram', 'file', 'postgresql'. This will be used
        to look up the corresponding class in cherrypy.lib.sessions
        globals. For example, 'file' will use the FileSession class.
    path: the 'path' value to stick in the response cookie metadata.
    path_header: if 'path' is None (the default), then the response
        cookie 'path' will be pulled from request.headers[path_header].
    name: the name of the cookie.
    timeout: the expiration timeout (in minutes) for both the cookie and
        stored session data.
    domain: the cookie domain.
    secure: if False (the default) the cookie 'secure' value will not
        be set. If True, the cookie 'secure' value will be set (to 1).
    clean_freq (minutes): the poll rate for expired session cleanup.
    
    Any additional kwargs will be bound to the new Session instance,
    and may be specific to the storage type. See the subclass of Session
    you're using for more information.
    """
    
    request = cherrypy.request
    
    # Guard against running twice
    if hasattr(request, "_session_init_flag"):
        return
    request._session_init_flag = True
    
    # Check if request came with a session ID
    id = None
    if name in request.cookie:
        id = request.cookie[name].value
    
    # Find the storage class and call setup (first time only).
    storage_class = storage_type.title() + 'Session'
    storage_class = globals()[storage_class]
    if not hasattr(cherrypy, "session"):
        if hasattr(storage_class, "setup"):
            storage_class.setup(**kwargs)
    
    # Create and attach a new Session instance to cherrypy.serving.
    # It will possess a reference to (and lock, and lazily load)
    # the requested session data.
    kwargs['timeout'] = timeout
    kwargs['clean_freq'] = clean_freq
    cherrypy.serving.session = sess = storage_class(id, **kwargs)
    def update_cookie(id):
        """Update the cookie every time the session id changes."""
        cherrypy.response.cookie[name] = id
    sess.id_observers.append(update_cookie)
    
    # Create cherrypy.session which will proxy to cherrypy.serving.session
    if not hasattr(cherrypy, "session"):
        cherrypy.session = cherrypy._ThreadLocalProxy('session')
    
    set_response_cookie(path=path, path_header=path_header, name=name,
                        timeout=timeout, domain=domain, secure=secure)
Exemplo n.º 5
0
def init(storage_type='ram',
         path=None,
         path_header=None,
         name='session_id',
         timeout=60,
         domain=None,
         secure=False,
         clean_freq=5,
         persistent=True,
         debug=False,
         **kwargs):
    request = cherrypy.serving.request
    if hasattr(request, '_session_init_flag'):
        return
    request._session_init_flag = True
    id = None
    if name in request.cookie:
        id = request.cookie[name].value
        if debug:
            cherrypy.log('ID obtained from request.cookie: %r' % id,
                         'TOOLS.SESSIONS')
    storage_class = storage_type.title() + 'Session'
    storage_class = globals()[storage_class]
    if not hasattr(cherrypy, 'session'):
        if hasattr(storage_class, 'setup'):
            storage_class.setup(**kwargs)
    kwargs['timeout'] = timeout
    kwargs['clean_freq'] = clean_freq
    cherrypy.serving.session = sess = storage_class(id, **kwargs)
    sess.debug = debug

    def update_cookie(id):
        cherrypy.serving.response.cookie[name] = id

    sess.id_observers.append(update_cookie)
    if not hasattr(cherrypy, 'session'):
        cherrypy.session = cherrypy._ThreadLocalProxy('session')
    if persistent:
        cookie_timeout = timeout
    else:
        cookie_timeout = None
    set_response_cookie(path=path,
                        path_header=path_header,
                        name=name,
                        timeout=cookie_timeout,
                        domain=domain,
                        secure=secure)
Exemplo n.º 6
0
def init(storage_type='ram', path=None, path_header=None, name='session_id',
         timeout=60, domain=None, secure=False, clean_freq=5,
         persistent=True, debug=False, **kwargs):
    """Initialize session object (using cookies).
    
    storage_type
        One of 'ram', 'file', 'postgresql'. This will be used
        to look up the corresponding class in cherrypy.lib.sessions
        globals. For example, 'file' will use the FileSession class.
    
    path
        The 'path' value to stick in the response cookie metadata.
    
    path_header
        If 'path' is None (the default), then the response
        cookie 'path' will be pulled from request.headers[path_header].
    
    name
        The name of the cookie.
    
    timeout
        The expiration timeout (in minutes) for the stored session data.
        If 'persistent' is True (the default), this is also the timeout
        for the cookie.
    
    domain
        The cookie domain.
    
    secure
        If False (the default) the cookie 'secure' value will not
        be set. If True, the cookie 'secure' value will be set (to 1).
    
    clean_freq (minutes)
        The poll rate for expired session cleanup.
    
    persistent
        If True (the default), the 'timeout' argument will be used
        to expire the cookie. If False, the cookie will not have an expiry,
        and the cookie will be a "session cookie" which expires when the
        browser is closed.
    
    Any additional kwargs will be bound to the new Session instance,
    and may be specific to the storage type. See the subclass of Session
    you're using for more information.
    """
    
    request = cherrypy.serving.request
    
    # Guard against running twice
    if hasattr(request, "_session_init_flag"):
        return
    request._session_init_flag = True
    
    # Check if request came with a session ID
    id = None
    if name in request.cookie:
        id = request.cookie[name].value
        if debug:
            cherrypy.log('ID obtained from request.cookie: %r' % id,
                         'TOOLS.SESSIONS')
    
    # Find the storage class and call setup (first time only).
    storage_class = storage_type.title() + 'Session'
    storage_class = globals()[storage_class]
    if not hasattr(cherrypy, "session"):
        if hasattr(storage_class, "setup"):
            storage_class.setup(**kwargs)
    
    # Create and attach a new Session instance to cherrypy.serving.
    # It will possess a reference to (and lock, and lazily load)
    # the requested session data.
    kwargs['timeout'] = timeout
    kwargs['clean_freq'] = clean_freq
    cherrypy.serving.session = sess = storage_class(id, **kwargs)
    sess.debug = debug
    def update_cookie(id):
        """Update the cookie every time the session id changes."""
        cherrypy.serving.response.cookie[name] = id
    sess.id_observers.append(update_cookie)
    
    # Create cherrypy.session which will proxy to cherrypy.serving.session
    if not hasattr(cherrypy, "session"):
        cherrypy.session = cherrypy._ThreadLocalProxy('session')
    
    if persistent:
        cookie_timeout = timeout
    else:
        # See http://support.microsoft.com/kb/223799/EN-US/
        # and http://support.mozilla.com/en-US/kb/Cookies
        cookie_timeout = None
    set_response_cookie(path=path, path_header=path_header, name=name,
                        timeout=cookie_timeout, domain=domain, secure=secure)
    def limit (self, **dummy_kwargs):
        """ Do accounting for ip and return 403 if ip exceeded quota. """

        ipsession = self._get_ip_session ()

        cherrypy.serving.ipsession = ipsession
        if not hasattr (cherrypy, "ipsession"):
            cherrypy.ipsession = cherrypy._ThreadLocalProxy ('ipsession') # pylint: disable=W0212

        ipsession.sessions.add (cherrypy.session.id)

        headers = cherrypy.request.headers

        ua = headers.get ('User-Agent')
        signature = self._get_http_signature (headers)

        whitelisted = (ipsession.ips.whitelisted or
                       self.whitelisted_paths.match (cherrypy.request.path_info))

        with self.lock:
            ipsession['active'] = True
            ipsession.extend_expiration (self.expiration)
            ipsession.append_trace (self, ua, signature)
            ipsession['css_ok'] = self.check_challenge () # store value for stats page

            if not whitelisted:
                ipsession.calc_block (self, ua)

            ipsession['last_hit'] = datetime.datetime.now () # set this after calc_block
            ipsession.log_state ()

            # allow hit
            if whitelisted:
                ipsession.log ('whitelisted')
                cherrypy.response.headers['X-Whitelisted'] = 'ratelimiter'
                ipsession['hits'] += 1
                self.whitelist_hit_accumulator += 1
                return

            if ipsession['blocked'] == 0:
                ipsession['hits'] += 1
                self.hit_accumulator += 1
                return

            # soft or hard deny
            self.denied_hit_accumulator += 1
            cherrypy.lib.caching.expires (0, True)

            if ipsession['blocked'] == 1:
                ipsession['captchas'] += 1
                ipsession.extend_expiration (10 * self.expiration) # watch 'em longer
                ipsession.log ('Redirected to captcha')
                cherrypy.response.headers['X-Ratelimiter-Denied'] = "503"
                raise cherrypy.HTTPRedirect ('//www.gutenberg.org/w/captcha/question/')
            else:
                ipsession['dhits'] += 1
                ipsession.set_expiration (self.expiration)
                if not ipsession['headers']:
                    ipsession['headers'] = self._get_headers_array (headers)
                ipsession.log ('Blocked 403')
                cherrypy.response.headers['X-Ratelimiter-Denied'] = "403"
                raise cherrypy.HTTPError (403, 'Forbidden')
Exemplo n.º 8
0
def init(
        storage_type=None,
        path=None,
        path_header=None,
        name='session_id',
        timeout=60,
        domain=None,
        secure=False,
        clean_freq=5,
        persistent=True,
        httponly=False,
        debug=False,
        # Py27 compat
        # *, storage_class=RamSession,
        **kwargs):
    """Initialize session object (using cookies).

    storage_class
        The Session subclass to use. Defaults to RamSession.

    storage_type
        (deprecated)
        One of 'ram', 'file', memcached'. This will be
        used to look up the corresponding class in cherrypy.lib.sessions
        globals. For example, 'file' will use the FileSession class.

    path
        The 'path' value to stick in the response cookie metadata.

    path_header
        If 'path' is None (the default), then the response
        cookie 'path' will be pulled from request.headers[path_header].

    name
        The name of the cookie.

    timeout
        The expiration timeout (in minutes) for the stored session data.
        If 'persistent' is True (the default), this is also the timeout
        for the cookie.

    domain
        The cookie domain.

    secure
        If False (the default) the cookie 'secure' value will not
        be set. If True, the cookie 'secure' value will be set (to 1).

    clean_freq (minutes)
        The poll rate for expired session cleanup.

    persistent
        If True (the default), the 'timeout' argument will be used
        to expire the cookie. If False, the cookie will not have an expiry,
        and the cookie will be a "session cookie" which expires when the
        browser is closed.

    httponly
        If False (the default) the cookie 'httponly' value will not be set.
        If True, the cookie 'httponly' value will be set (to 1).

    Any additional kwargs will be bound to the new Session instance,
    and may be specific to the storage type. See the subclass of Session
    you're using for more information.
    """

    # Py27 compat
    storage_class = kwargs.pop('storage_class', RamSession)

    request = cherrypy.serving.request

    # Guard against running twice
    if hasattr(request, '_session_init_flag'):
        return
    request._session_init_flag = True

    # Check if request came with a session ID
    id = None
    if name in request.cookie:
        id = request.cookie[name].value
        if debug:
            cherrypy.log('ID obtained from request.cookie: %r' % id,
                         'TOOLS.SESSIONS')

    first_time = not hasattr(cherrypy, 'session')

    if storage_type:
        if first_time:
            msg = 'storage_type is deprecated. Supply storage_class instead'
            cherrypy.log(msg)
        storage_class = storage_type.title() + 'Session'
        storage_class = globals()[storage_class]

    # call setup first time only
    if first_time:
        if hasattr(storage_class, 'setup'):
            storage_class.setup(**kwargs)

    # Create and attach a new Session instance to cherrypy.serving.
    # It will possess a reference to (and lock, and lazily load)
    # the requested session data.
    kwargs['timeout'] = timeout
    kwargs['clean_freq'] = clean_freq
    cherrypy.serving.session = sess = storage_class(id, **kwargs)
    sess.debug = debug

    def update_cookie(id):
        """Update the cookie every time the session id changes."""
        cherrypy.serving.response.cookie[name] = id

    sess.id_observers.append(update_cookie)

    # Create cherrypy.session which will proxy to cherrypy.serving.session
    if not hasattr(cherrypy, 'session'):
        cherrypy.session = cherrypy._ThreadLocalProxy('session')

    if persistent:
        cookie_timeout = timeout
    else:
        # See http://support.microsoft.com/kb/223799/EN-US/
        # and http://support.mozilla.com/en-US/kb/Cookies
        cookie_timeout = None
    set_response_cookie(path=path,
                        path_header=path_header,
                        name=name,
                        timeout=cookie_timeout,
                        domain=domain,
                        secure=secure,
                        httponly=httponly)
Exemplo n.º 9
0
def init(storage_type = 'ram', path = None, path_header = None, name = 'session_id', timeout = 60, domain = None, secure = False, clean_freq = 5, persistent = True, debug = False, **kwargs):
    """Initialize session object (using cookies).
    
    storage_type
        One of 'ram', 'file', 'postgresql'. This will be used
        to look up the corresponding class in cherrypy.lib.sessions
        globals. For example, 'file' will use the FileSession class.
    
    path
        The 'path' value to stick in the response cookie metadata.
    
    path_header
        If 'path' is None (the default), then the response
        cookie 'path' will be pulled from request.headers[path_header].
    
    name
        The name of the cookie.
    
    timeout
        The expiration timeout (in minutes) for the stored session data.
        If 'persistent' is True (the default), this is also the timeout
        for the cookie.
    
    domain
        The cookie domain.
    
    secure
        If False (the default) the cookie 'secure' value will not
        be set. If True, the cookie 'secure' value will be set (to 1).
    
    clean_freq (minutes)
        The poll rate for expired session cleanup.
    
    persistent
        If True (the default), the 'timeout' argument will be used
        to expire the cookie. If False, the cookie will not have an expiry,
        and the cookie will be a "session cookie" which expires when the
        browser is closed.
    
    Any additional kwargs will be bound to the new Session instance,
    and may be specific to the storage type. See the subclass of Session
    you're using for more information.
    """
    request = cherrypy.serving.request
    if hasattr(request, '_session_init_flag'):
        return
    request._session_init_flag = True
    id = None
    if name in request.cookie:
        id = request.cookie[name].value
        if debug:
            cherrypy.log('ID obtained from request.cookie: %r' % id, 'TOOLS.SESSIONS')
    storage_class = storage_type.title() + 'Session'
    storage_class = globals()[storage_class]
    if not hasattr(cherrypy, 'session'):
        if hasattr(storage_class, 'setup'):
            storage_class.setup(**kwargs)
    kwargs['timeout'] = timeout
    kwargs['clean_freq'] = clean_freq
    cherrypy.serving.session = sess = storage_class(id, **kwargs)
    sess.debug = debug

    def update_cookie(id):
        """Update the cookie every time the session id changes."""
        cherrypy.serving.response.cookie[name] = id

    sess.id_observers.append(update_cookie)
    if not hasattr(cherrypy, 'session'):
        cherrypy.session = cherrypy._ThreadLocalProxy('session')
    if persistent:
        cookie_timeout = timeout
    else:
        cookie_timeout = None
    set_response_cookie(path=path, path_header=path_header, name=name, timeout=cookie_timeout, domain=domain, secure=secure)
Exemplo n.º 10
0
def init(storage_type='ram',
         path=None,
         path_header=None,
         name='session_id',
         timeout=60,
         domain=None,
         secure=False,
         clean_freq=5,
         **kwargs):
    """Initialize session object (using cookies).
    
    storage_type: one of 'ram', 'file', 'postgresql'. This will be used
        to look up the corresponding class in cherrypy.lib.sessions
        globals. For example, 'file' will use the FileSession class.
    path: the 'path' value to stick in the response cookie metadata.
    path_header: if 'path' is None (the default), then the response
        cookie 'path' will be pulled from request.headers[path_header].
    name: the name of the cookie.
    timeout: the expiration timeout (in minutes) for both the cookie and
        stored session data.
    domain: the cookie domain.
    secure: if False (the default) the cookie 'secure' value will not
        be set. If True, the cookie 'secure' value will be set (to 1).
    clean_freq (minutes): the poll rate for expired session cleanup.
    
    Any additional kwargs will be bound to the new Session instance,
    and may be specific to the storage type. See the subclass of Session
    you're using for more information.
    """

    request = cherrypy.request

    # Guard against running twice
    if hasattr(request, "_session_init_flag"):
        return
    request._session_init_flag = True

    # Check if request came with a session ID
    id = None
    if name in request.cookie:
        id = request.cookie[name].value

    # Find the storage class and call setup (first time only).
    storage_class = storage_type.title() + 'Session'
    storage_class = globals()[storage_class]
    if not hasattr(cherrypy, "session"):
        if hasattr(storage_class, "setup"):
            storage_class.setup(**kwargs)

    # Create and attach a new Session instance to cherrypy.serving.
    # It will possess a reference to (and lock, and lazily load)
    # the requested session data.
    kwargs['timeout'] = timeout
    kwargs['clean_freq'] = clean_freq
    cherrypy.serving.session = sess = storage_class(id, **kwargs)

    def update_cookie(id):
        """Update the cookie every time the session id changes."""
        cherrypy.response.cookie[name] = id

    sess.id_observers.append(update_cookie)

    # Create cherrypy.session which will proxy to cherrypy.serving.session
    if not hasattr(cherrypy, "session"):
        cherrypy.session = cherrypy._ThreadLocalProxy('session')

    set_response_cookie(path=path,
                        path_header=path_header,
                        name=name,
                        timeout=timeout,
                        domain=domain,
                        secure=secure)
Exemplo n.º 11
0
def init(storage_type='ram', path=None, path_header=None, name='session_id',
         timeout=60, domain=None, secure=False, clean_freq=5, **kwargs):
    """Initialize session object (using cookies).
    
    storage_type: one of 'ram', 'file', 'postgresql'. This will be used
        to look up the corresponding class in cherrypy.lib.sessions
        globals. For example, 'file' will use the FileSession class.
    path: the 'path' value to stick in the response cookie metadata.
    path_header: if 'path' is None (the default), then the response
        cookie 'path' will be pulled from request.headers[path_header].
    name: the name of the cookie.
    timeout: the expiration timeout for the cookie.
    domain: the cookie domain.
    secure: if False (the default) the cookie 'secure' value will not
        be set. If True, the cookie 'secure' value will be set (to 1).
    clean_freq (minutes): the poll rate for expired session cleanup.
    
    Any additional kwargs will be bound to the new Session instance,
    and may be specific to the storage type. See the subclass of Session
    you're using for more information.
    """
    
    request = cherrypy.request
    
    # Guard against running twice
    if hasattr(request, "_session_init_flag"):
        return
    request._session_init_flag = True
    
    # Check if request came with a session ID
    id = None
    if name in request.cookie:
        id = request.cookie[name].value
    
    # Create and attach a new Session instance to cherrypy._serving.
    # It will possess a reference to (and lock, and lazily load)
    # the requested session data.
    storage_class = storage_type.title() + 'Session'
    kwargs['timeout'] = timeout
    kwargs['clean_freq'] = clean_freq
    cherrypy._serving.session = sess = globals()[storage_class](id, **kwargs)
    
    if not hasattr(cherrypy, "session"):
        cherrypy.session = cherrypy._ThreadLocalProxy('session')
        if hasattr(sess, "setup"):
            sess.setup()
    
    # Set response cookie
    cookie = cherrypy.response.cookie
    cookie[name] = sess.id
    cookie[name]['path'] = path or request.headers.get(path_header) or '/'
    
    # We'd like to use the "max-age" param as indicated in
    # http://www.faqs.org/rfcs/rfc2109.html but IE doesn't
    # save it to disk and the session is lost if people close
    # the browser. So we have to use the old "expires" ... sigh ...
##    cookie[name]['max-age'] = timeout * 60
    if timeout:
        cookie[name]['expires'] = http.HTTPDate(time.time() + (timeout * 60))
    if domain is not None:
        cookie[name]['domain'] = domain
    if secure:
        cookie[name]['secure'] = 1