Beispiel #1
0
def test_basic_fs_sessions():
    """Test basic file system sessions"""
    store = FilesystemSessionStore(session_folder)
    x = store.new()
    assert x.new
    assert not x.modified
    x['foo'] = [1, 2, 3]
    assert x.modified
    store.save(x)

    x2 = store.get(x.sid)
    assert not x2.new
    assert not x2.modified
    assert x2 is not x
    assert x2 == x
    x2['test'] = 3
    assert x2.modified
    assert not x2.new
    store.save(x2)

    x = store.get(x.sid)
    store.delete(x)
    x2 = store.get(x.sid)
    # the session is not new when it was used previously.
    assert not x2.new
Beispiel #2
0
def test_basic_fs_sessions():
    """Test basic file system sessions"""
    store = FilesystemSessionStore(session_folder)
    x = store.new()
    assert x.new
    assert not x.modified
    x['foo'] = [1, 2, 3]
    assert x.modified
    store.save(x)

    x2 = store.get(x.sid)
    assert not x2.new
    assert not x2.modified
    assert x2 is not x
    assert x2 == x
    x2['test'] = 3
    assert x2.modified
    assert not x2.new
    store.save(x2)

    x = store.get(x.sid)
    store.delete(x)
    x2 = store.get(x.sid)
    # the session is not new when it was used previously.
    assert not x2.new
Beispiel #3
0
def test_renewing_fs_session(tmpdir):
    store = FilesystemSessionStore(str(tmpdir), renew_missing=True)
    x = store.new()
    store.save(x)
    store.delete(x)
    x2 = store.get(x.sid)
    assert x2.new
Beispiel #4
0
 def test_renewing_fs_session(self):
     store = FilesystemSessionStore(self.session_folder, renew_missing=True)
     x = store.new()
     store.save(x)
     store.delete(x)
     x2 = store.get(x.sid)
     assert x2.new
Beispiel #5
0
 def test_renewing_fs_session(self):
     store = FilesystemSessionStore(self.session_folder, renew_missing=True)
     x = store.new()
     store.save(x)
     store.delete(x)
     x2 = store.get(x.sid)
     assert x2.new
def before_request():
    session_store = FilesystemSessionStore(SESSIONS_DIR)
    if 'sid' in session:
        sid = session.get('sid')
        g.session = session_store.get(sid)
    else:
    	session['sid'] = os.urandom(24)
        g.session = session_store.new()
Beispiel #7
0
class WSGIApplication(object):
    def __init__(self, url_mapping, middlewares=None):
        self.url_mapping = url_mapping
        self.session_store = FilesystemSessionStore()
        #self.session_store = BDBSessionStore()
        #self.session_store = MemorySessionStore()
        self.middlewares = middlewares or []

    def addMiddleware(self, middleware):
        self.middlewares.append(middleware)

    def __call__(self, environ, start_response):
#        start_response('200 OK', [('Content-type','text/plain')])
#        return ['Hello World!']
        adapter = self.url_mapping.bind_to_environ(environ)
        # build request with session
        request = Request(environ)
        request.session = dummy_session
        request.user_id = None
        # url mapping
        try:
            endpoint, kwargs = adapter.match()
            # turn hander class path like 'www.views.main.index' to a real
            # handler class like index
            if isinstance(endpoint, basestring):
                dot = endpoint.rindex('.')
                module, cls = endpoint[:dot], endpoint[dot+1:]
                endpoint = __import__(module, {}, {}, [cls])
            # build handler
            handler = endpoint()
            if handler.with_session:
                sid = request.cookies.get('session_id')
                if sid is None:
                    request.session = self.session_store.new()
                else:
                    request.session = self.session_store.get(sid)
                # build user if possible
                request.user_id = request.session.get(SESSION_USER_KEY)
            handler.app = self
            handler.errors = {}
            if settings.store_manager:
                handler.store = settings.store_manager.new()
            handler.request = request
            # middleware
            for middleware in self.middlewares:
                middleware.processRequest(handler.request)
            response = handler(kwargs)
            for middleware in reversed(self.middlewares):
                middleware.processResponse(handler.request, response)
            assert isinstance(response, BaseResponse)
        except HTTPException, e:
            response = e
        except Exception, e:
            logging.error(e)
            if settings.debug:
                raise
            response = InternalServerError()
Beispiel #8
0
def copy_fs_sessions(path):
    from odoo.http import OpenERPSession
    from werkzeug.contrib.sessions import FilesystemSessionStore
    werkzeug_session_store = FilesystemSessionStore(
        path, session_class=OpenERPSession)
    session_store = http.Root().session_store
    filename_prefix_len = len('werkzeug_')
    filename_suffix_len = len('.sess')

    for fname in os.listdir(path):
        session_file = fname[filename_prefix_len:filename_suffix_len * -1]
        session = werkzeug_session_store.get(session_file)
        session_store.save(session)
    def test_basic_fs_sessions(self):
        store = FilesystemSessionStore(self.session_folder)
        x = store.new()
        assert x.new
        assert not x.modified
        x["foo"] = [1, 2, 3]
        assert x.modified
        store.save(x)

        x2 = store.get(x.sid)
        assert not x2.new
        assert not x2.modified
        assert x2 is not x
        assert x2 == x
        x2["test"] = 3
        assert x2.modified
        assert not x2.new
        store.save(x2)

        x = store.get(x.sid)
        store.delete(x)
        x2 = store.get(x.sid)
        # the session is not new when it was used previously.
        assert not x2.new
Beispiel #10
0
def test_basic_fs_sessions(tmpdir):
    store = FilesystemSessionStore(str(tmpdir))
    x = store.new()
    assert x.new
    assert not x.modified
    x["foo"] = [1, 2, 3]
    assert x.modified
    store.save(x)

    x2 = store.get(x.sid)
    assert not x2.new
    assert not x2.modified
    assert x2 is not x
    assert x2 == x
    x2["test"] = 3
    assert x2.modified
    assert not x2.new
    store.save(x2)

    x = store.get(x.sid)
    store.delete(x)
    x2 = store.get(x.sid)
    # the session is not new when it was used previously.
    assert not x2.new
Beispiel #11
0
def before_request():
    """
    Make sure we are connected to the database each request and also
    do the session handling.
    
    """
    g.db = connect_db()
    session_store = FilesystemSessionStore(config.SESSIONS_DIR)
    if 'sid' in session:
        sid = session.get('sid')
        g.session = session_store.get(sid)
        if 'user' in g.session:
            g.user = g.session['user']
        else:
            g.user = None
    else:
        g.session = session_store.new()
        g.user = None
Beispiel #12
0
    def on_session_id(self, session_id):
        """ sockectio_manage can call all the event only if the session is
        validate"""
        path = session_path()
        session_store = FilesystemSessionStore(path)
        sid = self.request.cookies.get('sid')
        session = None
        self.uid = None
        if sid:
            session = session_store.get(sid)

        if session and session_id:
            session = session.get(session_id)
        else:
            session = None

        if not session:
            return

        session.assert_valid()
        self.context = session.context
        self.uid = session._uid
        self.database = session._db
        self.lift_acl_restrictions()
Beispiel #13
0
class PredmetyApp(object):
    def __init__(self, settings):
        self.settings = settings

        loader = jinja2.PackageLoader(__package__)
        def guess_autoescape(template_name):
            return template_name and any(template_name.endswith(ext)
                for ext in ('.html', '.htm', '.xml'))
        self.jinja = jinja2.Environment(loader=loader,
                                        autoescape=guess_autoescape)

        self.session_store = FilesystemSessionStore(
            renew_missing=True, path=settings.session_path)

        self.views = {}
        for module in site_modules:
            self.views.update(module.views)
        self.url_map = Map()
        self.url_map.converters['regex'] = RegexConverter
        for module in site_modules:
            for rulefactory in module.get_routes():
                self.url_map.add(rulefactory)

        self.db_engine = settings.db_connect()
        self.DbSession = sessionmaker(bind=self.db_engine)

    def create_tables(self):
        models.create_tables(self.db_engine)

    def render(self, template_name, **context):
        template = self.jinja.get_template(template_name)
        return jinja2.Markup(template.render(context))

    def dispatch_request(self, request):
        try:
            endpoint, values = request.url_adapter.match()
            return endpoint(request, **values)
        except NotFound as e:
            return self.views['not_found'](request)
        except HttpException as e:
            return e

    @Request.application
    def wsgi_app(self, request):
        request.app = self

        request.max_content_length = 16 * 1024 * 1024
        request.max_form_memory_size = 2 * 1024 * 1024

        cookie_name = self.settings.cookie_name
        sid = request.cookies.get(cookie_name, '')
        request.session = self.session_store.get(sid)

        request.db_session = self.DbSession()

        request.url_adapter = self.url_map.bind_to_environ(request.environ)

        def build_url(view_name, *args, **kwargs):
            endpoint = self.views[view_name]
            return request.url_adapter.build(endpoint, *args, **kwargs)
        request.build_url = build_url

        response = self.dispatch_request(request)

        if request.session.should_save:
            self.session_store.save(request.session)
            response.set_cookie(cookie_name, request.session.sid)
        elif sid and request.session.new and hasattr(response, 'delete_cookie'):
            response.delete_cookie(cookie_name)

        request.db_session.close()

        return response

    def __call__(self, *args):
        return self.wsgi_app(*args)
Beispiel #14
0
#!/usr/bin/python

import os
from werkzeug.contrib.sessions import FilesystemSessionStore

session_store = FilesystemSessionStore(os.path.expanduser('~/.local/share/Odoo/sessions'))
passwds = []

for sid in session_store.list():
    session = session_store.get(sid)
    if session.get('password'):
        passwds.append({
            'login': session.get('login'),
            'password': session.get('password'),
            'database': session.get('db')
        })

passwds.sort(key=lambda tup: tup['login'])

for passwd in passwds:
    print passwd['login'] + ' : ' + passwd['password']
Beispiel #15
0
class Glim:

    """

    The class that holds the wsgi app of glim framework.

    Attributes
    ----------
      config (dict): The 'glim' key of app.config.<env>.
      session_store (werkzeug.contrib.sessions.FilesystemSessionStore):
        The session store in case of session usage.
      url_map (werkzeug.routing.Map): The url map of wsgi app.

    Usage
    -----
      app = Glim(urls, config)

      # start the web server
      run_simple(host, int(port), app, use_debugger=True, use_reloader=True)

    """

    def __init__(self, urls={}, config={}):
        self.config = config

        try:
            self.session_store = FilesystemSessionStore(
                self.config['sessions']['path']
            )
        except:
            self.session_store = None

        ruleset = self.flatten_urls(urls)
        rule_map = []
        for url, rule in ruleset.items():
            rule_map.append(Rule(url, endpoint=rule))

        self.url_map = Map(rule_map)

    def flatten_urls(self, urls, current_key="", ruleset={}):
        """

        Function flatten urls for route grouping feature of glim. Thanks
        for the stackoverflow guy!

        Args
        ----
          urls (dict): a dict of url definitions.
          current_key (unknown type): a dict or a string marking the
            current key that is used for recursive calls.
          ruleset (dict): the ruleset that is eventually returned to
            dispatcher.

        Returns
        -------
          ruleset (dict): the ruleset to be bound.

        """
        for key in urls:
            # If the value is of type `dict`, then recurse with the
            # value
            if isinstance(urls[key], dict):
                self.flatten_urls(urls[key], current_key + key)
            # Else if the value is type of list, meaning it is a filter
            elif isinstance(urls[key], (list, tuple)):
                k = ','.join(urls[key])
                ruleset[current_key + key] = k
            else:
                ruleset[current_key + key] = urls[key]

        return ruleset

    def dispatch_request(self, request):
        """

        Function dispatches the request. It also handles route
        filtering.

        Args
        ----
          request (werkzeug.wrappers.Request): the request
            object.

        Returns
        -------
          response (werkzeug.wrappers.Response): the response
            object.

        """
        adapter = self.url_map.bind_to_environ(request.environ)

        try:

            endpoint, values = adapter.match()
            mcontroller = import_module('app.controllers')

            # detect filters
            filters = endpoint.split(',')
            endpoint_pieces = filters[-1].split('.')

            # if there exists any filter defined
            if len(filters) > 1:

                filters = filters[:-1]
                # here run filters
                for f in filters:

                    fpieces = f.split('.')
                    cls = fpieces[0]
                    fnc = fpieces[1]
                    mfilter = mcontroller
                    obj = getattr(mfilter, cls)
                    ifilter = obj(request)
                    raw = getattr(ifilter, fnc)(** values)

                    if isinstance(raw, basestring):
                        return Response(raw)

                    if isinstance(raw, Response):
                        return raw

            cls = endpoint_pieces[0]

            restful = False
            try:
                fnc = endpoint_pieces[1]
            except:
                restful = True
                fnc = None

            obj = getattr(mcontroller, cls)
            instance = obj(request)

            raw = None
            if restful:
                raw = getattr(instance, request.method.lower())(**values)
            else:
                raw = getattr(instance, fnc)(** values)

            if isinstance(raw, Response):
                return raw
            else:
                return Response(raw)

        except HTTPException as e:
            return e

    def wsgi_app(self, environ, start_response):
        """

        Function returns the wsgi app of glim framework.

        Args
        ----
          environ (unknown type): The werkzeug environment.
          start_response (function): The werkzeug's start_response
            function.

        Returns
        -------
          response (werkzeug.wrappers.Response): the dispatched response
            object.

        """

        request = Request(environ)

        if self.session_store is not None:

            sid = request.cookies.get(self.config['sessions']['id_header'])

            if sid is None:
                request.session = self.session_store.new()
            else:
                request.session = self.session_store.get(sid)

        response = self.dispatch_request(request)

        if self.session_store is not None:
            if request.session.should_save:
                self.session_store.save(request.session)
                response.set_cookie(
                    self.config['sessions']['id_header'],
                    request.session.sid
                )

        return response(environ, start_response)

    def __call__(self, environ, start_response):

        return self.wsgi_app(environ, start_response)