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)
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
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
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
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)
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
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
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)
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)
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()
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)
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)
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)
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)
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)
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
def __init__(self, *args, **kwargs): self.request_object = kwargs.pop('request_object') Session.__init__(self, *args, **kwargs)
def get_session(**kwargs): """A shortcut for creating :class:`Session` instance""" options = {} options.update(**kwargs) return Session({}, **options)
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
def _get_session(self, session_id=None): return Session({}, session_id, use_cookies=False, **self.options)
def _get_session(self): return Session({}, use_cookies=False, **self.session_options)