예제 #1
0
    def __init__(self,
                 request,
                 id=None,
                 invalidate_corrupt=False,
                 use_cookies=True,
                 type=None,
                 data_dir=None,
                 key='seminode.session.id',
                 timeout=None,
                 cookie_expires=True,
                 cookie_domain=None,
                 secret=None,
                 secure=False,
                 namespace_class=None,
                 **namespace_args):

        Session.__init__(
            self,
            request,
            id=id,
            invalidate_corrupt=invalidate_corrupt,
            use_cookies=use_cookies,
            type=type,
            data_dir=data_dir,
            key=key,
            timeout=timeout,
            cookie_expires=cookie_expires,
            cookie_domain=cookie_domain,
            secret=secret,
            secure=secure,
            namespace_class=namespace_class,
            **namespace_args)
예제 #2
0
def test_set_cookie_expires():
    """Exhibit Set-Cookie: values."""
    session = Session({}, cookie_expires=True)
    assert cookie_expiration(session) is True
    session._set_cookie_expires(False)
    assert cookie_expiration(session) is False
    session._set_cookie_expires(True)
    assert cookie_expiration(session) is True
예제 #3
0
def test_cookie_exprires_2():
    """Exhibit Set-Cookie: values."""
    expires = cookie_expiration(Session({}, cookie_expires=True))

    assert expires is True, expires
    no_expires = cookie_expiration(Session({}, cookie_expires=False))

    assert no_expires is False, no_expires
예제 #4
0
 def create_session(self, username, password, otp=None):
     user = self.authenticate(username, password, otp)
     prefix = otp[:-32] if otp else None
     user_session = UserSession({}, **session_config)
     user_session['user_id'] = user.id
     user_session['username'] = user.name
     user_session['prefix'] = prefix if prefix else None
     user_session.save()
     return user_session
예제 #5
0
 def create_session(self, username, password, otp=None):
     user = self.authenticate(username, password, otp)
     prefix = otp[:-32] if otp else None
     user_session = UserSession({}, **session_config)
     user_session['user_id'] = user.id
     user_session['username'] = user.name
     user_session['prefix'] = prefix if prefix else None
     user_session.save()
     return user_session
예제 #6
0
    def save(self):
        # Save permissions in session if needed.
        if c.perms.dirty:
            # Save permissions.
            log.debug("Permissions have changed: saving them into session.")
            self['perms'] = c.perms.to_dict()

        # Call parent save method.
        log.debug("Saving session.")
        Session.save(self)
예제 #7
0
def test_cookie_exprires_2():
    """Exhibit Set-Cookie: values."""
    expires = Session({}, cookie_expires=True).cookie.output()

    assert re.match('Set-Cookie: beaker.session.id=[0-9a-f]{32}; Path=/',
                    expires), expires
    no_expires = Session({}, cookie_expires=False).cookie.output()

    assert re.match(
        'Set-Cookie: beaker.session.id=[0-9a-f]{32}; expires=(Mon|Tue), 1[89]-Jan-2038 [0-9:]{8} GMT; Path=/',
        no_expires), no_expires
예제 #8
0
def test_cookie_expires_different_locale():
    from locale import setlocale, LC_TIME
    expires_date = datetime.datetime(2019, 5, 22)
    setlocale(LC_TIME, 'it_IT.UTF-8')
    # if you get locale.Error: unsupported locale setting. you have to enable that locale in your OS.
    assert expires_date.strftime("%a, %d-%b-%Y %H:%M:%S GMT").startswith('mer,')
    session = Session({}, cookie_expires=True, validate_key='validate_key')
    assert session._set_cookie_expires(expires_date)
    expires = cookie_expiration(session)
    assert expires == 'Wed, 22-May-2019 00:00:00 GMT', expires
    setlocale(LC_TIME, '')  # restore default locale for further tests
예제 #9
0
    def __init__(self, request, environ=None, id=None, invalidate_corrupt=False,
             use_cookies=True, type=None, data_dir=None,
             key='beaker.session.id', timeout=None, cookie_expires=True,
             cookie_domain=None, secret=None, secure=False,
             namespace_class=None, **namespace_args):
        
        self.environ = environ

        # Call parent constructor.
        Session.__init__(self, request, id, invalidate_corrupt,
             use_cookies, type, data_dir,
             key, timeout, cookie_expires,
             cookie_domain, secret, secure,
             namespace_class, **namespace_args)
예제 #10
0
 def _create_id(self):
     # Call parent _create_id method.
     Session._create_id(self)
     if self.environ and self.environ.has_key('wsgiorg.routing_args') and (len(self.environ['wsgiorg.routing_args']) > 1):
         if 'workspace_id' in self.environ['wsgiorg.routing_args'][1]:
             if self.environ['wsgiorg.routing_args'][1]['controller'] in ['admin_teambox', 'admin_file_download']:
                 self.id = 'wsadminid' + self.environ['wsgiorg.routing_args'][1]['workspace_id'] + '__' + self.id
                 log.debug('kwmo admin session id created ' + self.id)
             else:
                 self.id = 'wsid' + self.environ['wsgiorg.routing_args'][1]['workspace_id'] + '__' + self.id
                 log.debug('kwmo session id created ' + self.id)
         else:
             log.info('_failed to create kwmo session id, creating session with cookie id ' + self.id)
     else:
         log.warn('__failed to create kwmo session id, creating session with cookie id ' + self.id)
예제 #11
0
    def test_logout(self):
        url = '/logout/'

        request_with_all = TestRequest.blank(
            url,
            method='GET',
            referrer='http://localhost/content/list/',
            headers=self.mk_session()[1])
        request_without_ref = TestRequest.blank(url,
                                                method='GET',
                                                headers=self.mk_session()[1])
        request_with_invalid_ref = TestRequest.blank(
            url,
            method='GET',
            referrer='http://example.com/page/',
            headers=self.mk_session()[1])

        for request in (request_with_all, request_without_ref,
                        request_with_invalid_ref):
            resp = self.app.request(request)

            self.assertEqual(resp.status_int, 302)
            if request == request_with_all:
                self.assertEqual(resp.location, request.referrer)
            else:
                self.assertEqual(resp.location, 'http://localhost/')

            # check that the session is no longer authenticated
            session = Session(request,
                              id=request.cookies['beaker.session.id'],
                              use_cookies=False)
            self.assertNotIn('auth.userid', session)

            self.app.reset()
예제 #12
0
def application(environ, start_response):
    global IDP_CLIENT
    session = Session(environ['beaker.session'])
    path = environ.get('PATH_INFO', '').lstrip('/')

    if path.startswith("info"):
        # Assume query of the form
        # info/<uid>/<bundle>[?attr=<attribute>[&attr=<attribute>]] or
        # info/<uid>[?attr=<attribute>[&attr=<attribute>]]
        owner = path[5:]
        #owner = owner.replace("--", "@")
        resp = IDP_CLIENT.get_info(owner)
    elif path.startswith("authz_cb"):  # Authorization redirect URI
        try:
            owner = IDP_CLIENT.get_tokens(environ["QUERY_STRING"])
            resp = IDP_CLIENT.get_info(owner)
        except Exception as err:
            raise
    else:
        resp = None

    if resp:
        pass
    else:
        resp = NotImplemented(path)

    return resp(environ, start_response)
예제 #13
0
    def mk_session(self, logged_in=True, user_data={}):
        session_id = uuid.uuid4().hex
        session = Session(
            testing.DummyRequest(), id=session_id, use_cookies=False)

        if logged_in:
            user_data = user_data or {
                'uuid': uuid.uuid4().hex,
                'username': '******',
                'app_data': {'display_name': 'foobar'}
            }
            session[USER_DATA_SESSION_KEY] = user_data
            session['auth.userid'] = user_data['uuid']

        session.save()
        # return the session and cookie header
        return session, {'Cookie': 'beaker.session.id=%s' % session_id}
 def restore_session(self, environ):
     '''Given a wsgi environment it reconstruct a session object
     :param environ: wsgi environment
     :return: session object
     '''
     session = SessionObject(environ, **self.options)
     environ[self.environ_key] = session
     environ['beaker.get_session'] = self._get_session
     return Session({}, use_cookies=True, **self.options)
예제 #15
0
    def load(self):
        if not self.is_new:            
            if self.environ and self.environ.has_key('wsgiorg.routing_args') and (len(self.environ['wsgiorg.routing_args']) > 1):
                if 'workspace_id' in self.environ['wsgiorg.routing_args'][1]:
                    if self.environ['wsgiorg.routing_args'][1]['controller'] in ['admin_teambox', 'admin_file_download']:
                        self.id = 'wsadminid' + self.environ['wsgiorg.routing_args'][1]['workspace_id'] + '__' + self.id
                        log.debug('kwmo admin session loaded ' + self.id)
                    else:
                        self.id = 'wsid' + self.environ['wsgiorg.routing_args'][1]['workspace_id'] + '__' + self.id
                        #log.debug('kwmo session loaded ' + self.id)

                else:
                    log.info('_failed to load kwmo session, loading session with cookie id ' + self.id)
            else:
                log.warn('__failed to load kwmo session, loading session with cookie id ' + self.id)
                
        #call parent load        
        Session.load(self)
예제 #16
0
def test_load_deleted_from_storage_session__not_loaded():
    req = {'cookie': {'beaker.session.id': 123}}
    session = Session(req, timeout=1)

    session.delete()
    session.save()

    Session(req, timeout=1)
예제 #17
0
    def test_login(self):
        ticket = 'iamaticket'
        redirect_url = 'http://localhost/content/list/'
        user_data = {
            'uuid': 'imauuid',
            'username': '******',
            'app_data': {
                'display_name': 'foobar'
            }
        }

        responses.add(responses.GET,
                      re.compile(r'.*/sso/validate.*'),
                      body=json.dumps(user_data),
                      status=200,
                      content_type='application/json')

        request_with_url = TestRequest.blank('/login/?%s' %
                                             urlencode({
                                                 'ticket': ticket,
                                                 'url': redirect_url
                                             }))
        request_without_url = TestRequest.blank('/login/?%s' %
                                                urlencode({'ticket': ticket}))

        for request in (request_with_url, request_without_url):
            resp = self.app.request(request)

            self.assertEqual(resp.status_int, 302)
            if request == request_with_url:
                self.assertEqual(resp.location, redirect_url)
            else:
                self.assertEqual(resp.location, 'http://localhost/')

            # check that session contains user data
            self.assertIn('beaker.session.id', self.app.cookies)
            session = Session(request,
                              id=self.app.cookies['beaker.session.id'],
                              use_cookies=False)
            self.assertEqual(session['auth.userid'], user_data['uuid'])
            self.assertEqual(session[USER_DATA_SESSION_KEY], user_data)

            self.app.reset()

        responses.reset()
        responses.add(responses.GET,
                      re.compile(r'.*/sso/validate.*'),
                      body=json.dumps('no\n'),
                      status=200,
                      content_type='application/json')

        resp = self.app.request(request_with_url)
        self.assertEqual(resp.status_int, 302)
        self.assertEqual(resp.location, redirect_url)
        self.assertNotIn('beaker.session.id', self.app.cookies)
예제 #18
0
def test_set_cookie_expires():
    """Exhibit Set-Cookie: values."""
    session = Session({}, cookie_expires=True)
    assert cookie_expiration(session) is True
    session._set_cookie_expires(False)
    assert cookie_expiration(session) is False
    session._set_cookie_expires(True)
    assert cookie_expiration(session) is True
예제 #19
0
    def load_session(self, cookies):
        from http.cookies import SimpleCookie
        from beaker.session import Session
        from pyload.webui.interface import session

        cookies = SimpleCookie(cookies)
        sid = cookies.get(session.options['key'])
        if not sid:
            return None

        s = Session({}, use_cookies=False, id=sid.value, **session.options)
        if s.is_new:
            return None

        return s
예제 #20
0
 def __init__(self, *args, **kwargs):
     self.request_object = kwargs.pop('request_object')
     Session.__init__(self, *args, **kwargs)
예제 #21
0
def get_session(**kwargs):
    """A shortcut for creating :class:`Session` instance"""
    options = {}
    options.update(**kwargs)
    return Session({}, **options)
예제 #22
0
 def get_session(self, sessionId):
     user_session = UserSession({}, id=sessionId, **session_config)
     if user_session.is_new:
         user_session.delete()
         raise ValueError("Session not found!")
     return user_session
예제 #23
0
 def get_session(self, sessionId):
     user_session = UserSession({}, id=sessionId, **session_config)
     if user_session.is_new:
         user_session.delete()
         raise ValueError("Session not found!")
     return user_session
예제 #24
0
 def __init__(self, *args, **kwargs):
     self.request_object = kwargs.pop('request_object')
     Session.__init__(self, *args, **kwargs)
예제 #25
0
 def _get_session(self, session_id=None):
     return Session({}, session_id, use_cookies=False, **self.options)
예제 #26
0
 def _get_session(self):
     return Session({}, use_cookies=False, **self.session_options)