def query_server(self, filename): conn = self.module.ICAPConnection(**self.conn_kwargs) conn.request("REQMOD", filename, read_content=False, **self.req_kwargs) resp = conn.getresponse() conn.close() # look for the headers defined inside # the RFC Draft for ICAP Extensions threat = resp.get_icap_header("X-Violations-Found") # multiple threats? try to parse the header values if threat is not None: try: values = threat.split("\n") # only read the human readable descriptions threats = [s.strip() for idx, s in enumerate(values[1:]) if idx % 4 == 1] threat = "%s threat(s) found: %s" % (threats[0].strip(), ", ".join(threats)) except: threat = "Multiple threats found: %s" % threat if threat is None: # only a description threat = resp.get_icap_header("X-Virus-ID") if threat is not None: threat = "Threat found: %s" % threat if threat is None: threat = resp.get_icap_header("X-Infection-Found") if threat is not None: # only return the human readable threat name cookie = Cookie(threat) kv = cookie.get("Threat") if kv is not None: threat = kv.value if threat is not None: threat = "Threat found: %s" % threat return threat
def recordSession(self): """Record session ID. Invoked by commit() to record the session ID in the response (if a session exists). This implementation sets a cookie for that purpose. For people who don't like sweets, a future version could check a setting and instead of using cookies, could parse the HTML and update all the relevant URLs to include the session ID (which implies a big performance hit). Or we could require site developers to always pass their URLs through a function which adds the session ID (which implies pain). Personally, I'd rather just use cookies. You can experiment with different techniques by subclassing Session and overriding this method. Just make sure Application knows which "session" class to use. It should be also considered to automatically add the server port to the cookie name in order to distinguish application instances running on different ports on the same server, or to use the port cookie-attribute introduced with RFC 2965 for that purpose. """ trans = self._transaction app = trans.application() if not app.setting('UseCookieSessions'): return session = trans._session if not session: if debug: print '>> recordSession: Did not set SID.' return request = trans.request() sessionName = app.sessionName(trans) identifier = session.identifier() if session.isExpired() or session.timeout() == 0: self.delCookie(sessionName, app.sessionCookiePath(trans), request.isSecure() and app.setting('SecureSessionCookie')) if debug: print '>> recordSession: Removing SID', identifier return # Temporary fix for bug 65471 #if request.hasCookie(sessionName): if False: if request.cookie(sessionName) == identifier: if debug: print '>> recordSession: Using SID', identifier return cookie = Cookie(app.sessionName(trans), identifier) cookie.setPath(app.sessionCookiePath(trans)) if trans.request().isSecure(): cookie.setSecure(app.setting('SecureSessionCookie')) self.addCookie(cookie) if debug: print '>> recordSession: Setting SID', identifier
def delCookie(self, name): """Delete a cookie at the browser. To do so, one has to create and send to the browser a cookie with parameters that will cause the browser to delete it. """ if self._cookies.has_key(name): self._cookies[name].delete() else: cookie = Cookie(name, None) cookie.delete() self.addCookie(cookie)
def test_known_cookie_ip_check_enabled(self): self.env.config.set('trac', 'check_auth_ip', 'yes') self.env.db_transaction(""" INSERT INTO auth_cookie (cookie, name, ipnr) VALUES ('123', 'john', '127.0.0.1')""") incookie = Cookie() incookie['trac_auth'] = '123' outcookie = Cookie() req = Mock(cgi_location='/trac', href=Href('/trac.cgi'), incookie=incookie, outcookie=outcookie, remote_addr='192.168.0.100', remote_user=None, base_path='/trac.cgi') self.assertIsNone(self.module.authenticate(req)) self.assertIn('trac_auth', req.outcookie)
def test_known_cookie_access(self): cursor = self.db.cursor() cursor.execute("INSERT INTO auth_cookie (cookie, name, ipnr) " "VALUES ('123', 'john', '127.0.0.1')") incookie = Cookie() incookie['trac_auth'] = '123' outcookie = Cookie() req = Mock(incookie=incookie, outcookie=outcookie, href=Href('/trac.cgi'), remote_addr='127.0.0.1', remote_user=None) self.assertEqual('john', self.module.authenticate(req)) self.failIf('auth_cookie' in req.outcookie)
def test_anonymous_session(self): """ Verify that session variables are stored in the database. """ incookie = Cookie() incookie['trac_session'] = '123456' outcookie = Cookie() req = Mock(authname='anonymous', base_path='/', incookie=incookie, outcookie=outcookie) session = Session(self.env, req) self.assertEquals('123456', session.sid) self.failIf(outcookie.has_key('trac_session'))
def setCookie(self, name, value, path='/', expires='ONCLOSE', secure=False): """Set a cookie. You can also set the path (which defaults to /). You can also set when it expires. It can expire: 'NOW': this is the same as trying to delete it, but it doesn't really seem to work in IE 'ONCLOSE': the default behavior for cookies (expires when the browser closes) 'NEVER': some time in the far, far future. integer: a timestamp value tuple or struct_time: a tuple, as created by the time module datetime: a datetime.datetime object for the time (if without time zone, assumed to be *local*, not GMT time) timedelta: a duration counted from the present, e.g., datetime.timedelta(days=14) (2 weeks in the future) '+...': a time in the future, '...' should be something like 1w (1 week), 3h46m (3:45), etc. You can use y (year), b (month), w (week), d (day), h (hour), m (minute), s (second). This is done by the MiscUtils.DateInterval. """ cookie = Cookie(name, value) t = expires if isinstance(t, basestring): if t == 'ONCLOSE': t = None elif t == 'NOW': cookie.delete() return elif t == 'NEVER': t = gmtime() t = (t[0] + 10,) + t[1:] elif t.startswith('+'): t = time() + timeDecode(t[1:]) if t: if isinstance(t, (int, long, float)): t = gmtime(t) if isinstance(t, (tuple, struct_time)): t = strftime("%a, %d-%b-%Y %H:%M:%S GMT", t) if isinstance(t, timedelta): t = datetime.now() + t if isinstance(t, datetime): d = t.utcoffset() if d is None: d = localTimeDelta() t -= d t = t.strftime("%a, %d-%b-%Y %H:%M:%S GMT") cookie.setExpires(t) if path: cookie.setPath(path) if secure: cookie.setSecure(secure) self.addCookie(cookie)
def test_logout(self): self.env.db_transaction(""" INSERT INTO auth_cookie (cookie, name, ipnr) VALUES ('123', 'john', '127.0.0.1')""") incookie = Cookie() incookie['trac_auth'] = '123' outcookie = Cookie() req = Mock(cgi_location='/trac', href=Href('/trac.cgi'), incookie=incookie, outcookie=outcookie, remote_addr='127.0.0.1', remote_user=None, authname='john', method='POST', base_path='/trac.cgi') self.module._do_logout(req) self.assertIn('trac_auth', outcookie) self.assertFalse(self.env.db_query( "SELECT name, ipnr FROM auth_cookie WHERE name='john'"))
def setUp(self): _BaseTestCase.setUp(self) self.mgr = AccountManager(self.env) self.store = SessionStore(self.env) self.store.set_password('user', 'passwd') args = dict(username='******', name='', email='') incookie = Cookie() incookie['trac_session'] = '123456' self.req = Mock(authname='', args=args, authenticated=True, base_path='/', callbacks=dict(), href=Mock(prefs=lambda x: None), incookie=incookie, outcookie=Cookie(), redirect=lambda x: None) self.req.path_info = '/'
def _create_session(self, user, authenticated=1, name='', email=''): args = dict(username=user, name=name, email=email) incookie = Cookie() incookie['trac_session'] = '123456' req = Mock(authname=bool(authenticated) and user or 'anonymous', args=args, base_path='/', chrome=dict(warnings=list()), href=Mock(prefs=lambda x: None), incookie=incookie, outcookie=Cookie(), redirect=lambda x: None) req.session = Session(self.env, req) req.session.save() return req.session
def test_known_cookie_ip_check_disabled(self): self.env.config.set('trac', 'check_auth_ip', 'no') cursor = self.db.cursor() cursor.execute("INSERT INTO auth_cookie (cookie, name, ipnr) " "VALUES ('123', 'john', '127.0.0.1')") incookie = Cookie() incookie['trac_auth'] = '123' outcookie = Cookie() req = Mock(incookie=incookie, outcookie=outcookie, href=Href('/trac.cgi'), remote_addr='192.168.0.100', remote_user=None) self.assertEqual('john', self.module.authenticate(req)) self.failIf('auth_cookie' in req.outcookie)
def test_known_cookie_different_ipnr_access(self): cursor = self.db.cursor() cursor.execute("INSERT INTO auth_cookie (cookie, name, ipnr) " "VALUES ('123', 'john', '127.0.0.1')") incookie = Cookie() incookie['trac_auth'] = '123' outcookie = Cookie() req = Mock(cgi_location='/trac', href=Href('/trac.cgi'), incookie=incookie, outcookie=outcookie, remote_addr='192.168.0.100', remote_user=None) self.assertEqual(None, self.module.authenticate(req)) self.failIf('trac_auth' not in req.outcookie)
def test_new_session(self): """ Verify that a session cookie gets sent back to the client for a new session. """ cookie = Cookie() req = Mock(incookie=Cookie(), outcookie=cookie, authname='anonymous', base_path='/') session = Session(self.env, req) self.assertEqual(session.sid, cookie['trac_session'].value) self.assertEqual( 0, self.env.db_query("SELECT COUNT(*) FROM session")[0][0])
def test_add_anonymous_session_var(self): """ Verify that new variables are inserted into the 'session' table in the database for an anonymous session. """ incookie = Cookie() incookie['trac_session'] = '123456' req = Mock(authname='anonymous', base_path='/', incookie=incookie, outcookie=Cookie()) session = Session(self.env, req) session['foo'] = 'bar' session.save() self.assertEqual('bar', self.env.db_query( "SELECT value FROM session_attribute WHERE sid='123456'")[0][0])
def test_known_cookie_access(self): self.env.db_transaction(""" INSERT INTO auth_cookie (cookie, name, ipnr) VALUES ('123', 'john', '127.0.0.1')""") incookie = Cookie() incookie['trac_auth'] = '123' outcookie = Cookie() req = Mock(incookie=incookie, outcookie=outcookie, href=Href('/trac.cgi'), base_path='/trac.cgi', remote_addr='127.0.0.1', remote_user=None) self.assertEqual('john', self.module.authenticate(req)) self.assertNotIn('auth_cookie', req.outcookie)
def test_authenticated_session(self): """ Verifies that a session cookie does not get used if the user is logged in, and that Trac expires the cookie. """ incookie = Cookie() incookie['trac_session'] = '123456' outcookie = Cookie() req = Mock(authname='john', base_path='/', incookie=incookie, outcookie=outcookie) session = Session(self.env, req) self.assertEqual('john', session.sid) session['foo'] = 'bar' session.save() self.assertEquals(0, outcookie['trac_session']['expires'])
def test_login(self): outcookie = Cookie() # remote_user must be upper case to test that by default, case is # preserved. req = Mock(cgi_location='/trac', href=Href('/trac.cgi'), incookie=Cookie(), outcookie=outcookie, remote_addr='127.0.0.1', remote_user='******', authname='john', base_path='/trac.cgi') self.module._do_login(req) self.assertIn('trac_auth', outcookie, '"trac_auth" Cookie not set') auth_cookie = outcookie['trac_auth'].value self.assertEqual([('john', '127.0.0.1')], self.env.db_query( "SELECT name, ipnr FROM auth_cookie WHERE cookie=%s", (auth_cookie,)))
def __init__(self, req): """SafeRequest constructor. Args: req: Mongrel2 Request object """ self.req = req self.url_params = None self.post_params = None self.cookies = Cookie(str(self.header("cookie"))) self._body = self.req.body self._data = {} self._escaped_data = {} self._content_type = self.header("content-type") if self.header("QUERY"): self.url_params = urlparse.parse_qs(self.header("QUERY")) if self.header("METHOD") == "POST": self.post_params = urlparse.parse_qs(self.req.body) if self._body and self._content_type and self._content_type.find( "application/json") != -1: self._data = json.loads(self._body) self._escaped_data = json.loads(self._escape(self._body))
def on_start(self): """ Set up the initial user. We only have access to the HTTP environment, so we use the session ID in the cookie and look up a user with it. If a valid user is found, we add them to the user set in redis, and broadcast their join event to everyone else. """ try: cookie = Cookie(self.environ["HTTP_COOKIE"]) session_key = cookie[settings.SESSION_COOKIE_NAME].value session = Session.objects.get(session_key=session_key) user_id = session.get_decoded().get(SESSION_KEY) user = User.objects.get(id=user_id) except (KeyError, ObjectDoesNotExist): self.user = None else: self.user = { "id": user.id, "name": user.username, "x": randint(780, 980), "y": randint(100, 300), } self.broadcast_event_not_me("join", self.user) redis.hset(USERS_KEY, self.user["id"], dumps(self.user)) # Send the current set of users to the new socket. self.emit("users", [loads(u) for u in redis.hvals(USERS_KEY)]) for game in registry.values(): if game.players: self.emit("game_users", game.name, game.players.keys())
def test_add_anonymous_session_var(self): """ Verify that new variables are inserted into the 'session' table in the database for an anonymous session. """ incookie = Cookie() incookie['trac_session'] = '123456' req = Mock(authname='anonymous', cgi_location='/', incookie=incookie, outcookie=Cookie()) session = Session(self.env, req) session['foo'] = 'bar' session.save() cursor = self.db.cursor() cursor.execute("SELECT var_value FROM session WHERE sid='123456' AND " "authenticated=0 AND var_name='foo'") self.assertEqual('bar', cursor.fetchone()[0])
def _prelogin(self): url = 'http://ptlogin2.qq.com/login' params = { 'u':self.id, 'p':self.encodepwd, 'verifycode':self.verify, 'u1':'http://web2.qq.com/loginproxy.html?strong=true', 'remember_uin':1, 'aid':1003903, 'h':1, 'ptredirect':0, 'ptlang':2052, 'from_ui':1, 'pttype':1, 'dumy':'', 'fp':'loginerroralert', } self.cookies['verifysession'] = self.verify Headers['Cookie']=self.cookies.output() resp,content = Get(url,params=params,headers=Headers) self.cookies = Cookie(resp.get('set-cookie','')) match = CB.match(content) if int(match.group('one')) == 0: return True else: return False
def test_process_unknown_collection(self): BuildConfig(self.env, 'test', path='somepath', active=True, recipe='<build></build>').insert() build = Build(self.env, 'test', '123', 1, slave='hal', rev_time=42) build.insert() outheaders = {} outbody = StringIO() req = Mock(method='POST', base_path='', path_info='/builds/%d/files/' % build.id, href=Href('/trac'), remote_addr='127.0.0.1', args={}, perm=PermissionCache(self.env, 'hal'), send_response=lambda x: outheaders.setdefault('Status', x), send_header=lambda x, y: outheaders.setdefault(x, y), write=outbody.write, incookie=Cookie('trac_auth=')) module = BuildMaster(self.env) assert module.match_request(req) self.assertRaises(RequestDone, module.process_request, req) self.assertEqual(404, outheaders['Status']) self.assertEqual("No such collection 'files'", outbody.getvalue())
def test_create_build_protocol_no_version(self): inheaders = {'Content-Type': 'application/x-bitten+xml'} inbody = StringIO("""<slave name="hal"> <platform>Power Macintosh</platform> <os family="posix" version="8.1.0">Darwin</os> </slave>""") outheaders = {} outbody = StringIO() req = Mock(method='POST', base_path='', path_info='/builds', href=Href('/trac'), remote_addr='127.0.0.1', args={}, perm=PermissionCache(self.env, 'hal'), get_header=lambda x: inheaders.get(x), read=inbody.read, send_response=lambda x: outheaders.setdefault('Status', x), send_header=lambda x, y: outheaders.setdefault(x, y), write=outbody.write, incookie=Cookie('trac_auth=')) module = BuildMaster(self.env) assert module.match_request(req) self.assertRaises(RequestDone, module.process_request, req) self.assertEqual(400, outheaders['Status']) self.assertEqual('Master-Slave version mismatch: master=%d, slave=1' \ % (PROTOCOL_VERSION,), outbody.getvalue())
def test_create_build_invalid_xml(self): inheaders = {'Content-Type': 'application/x-bitten+xml'} inbody = StringIO('<slave></salve>') outheaders = {} outbody = StringIO() req = Mock(method='POST', base_path='', path_info='/builds', href=Href('/trac'), remote_addr='127.0.0.1', args={}, perm=PermissionCache(self.env, 'hal'), get_header=lambda x: inheaders.get(x), read=inbody.read, send_response=lambda x: outheaders.setdefault('Status', x), send_header=lambda x, y: outheaders.setdefault(x, y), write=outbody.write, incookie=Cookie('trac_auth=')) module = BuildMaster(self.env) assert module.match_request(req) self.assertRaises(RequestDone, module.process_request, req) self.assertEquals(400, outheaders['Status']) self.assertEqual('XML parser error', outbody.getvalue())
def __init__(self): self.outcookie = Cookie() self.incookie = Cookie() self.args = { 'username': '******', 'password': '******', 'action': '' } self.authname = 'anonymous' self.remote_addr = '127.0.0.1' self.session = DummySession() self.base_path = '' self.remote_user = '' self.href = trac.web.Href('/tmp') #@UndefinedVariable self.chrome = {} self.method = ''
def handleHeader(self, key, value): if (not key.lower() in GoogleConnection.disallowedHeaders): self.client.setHeader(key, value) elif (key.lower() == 'set-cookie'): logging.debug("Adding cookie to collection: " + value) self.identity.setCookie( Cookie(value, self.headers['Host'], self.uri))
def test_anonymous_access(self): req = Mock(incookie=Cookie(), href=Href('/trac.cgi'), remote_addr='127.0.0.1', remote_user=None, base_path='/trac.cgi') self.assertIsNone(self.module.authenticate(req))
def test_login_no_username(self): req = Mock(incookie=Cookie(), href=Href('/trac.cgi'), remote_addr='127.0.0.1', remote_user=None, base_path='/trac.cgi') self.assertRaises(TracError, self.module._do_login, req)
def test_logout(self): cursor = self.db.cursor() cursor.execute("INSERT INTO auth_cookie (cookie, name, ipnr) " "VALUES ('123', 'john', '127.0.0.1')") incookie = Cookie() incookie['trac_auth'] = '123' outcookie = Cookie() req = Mock(cgi_location='/trac', incookie=incookie, outcookie=outcookie, remote_addr='127.0.0.1', remote_user=None, authname='john') self.module._do_logout(req) self.failIf('trac_auth' not in outcookie) cursor.execute("SELECT name,ipnr FROM auth_cookie WHERE name='john'") self.failIf(cursor.fetchone())
def setUp(self): conf.use_test_db(False) dbStub.addResult([['cookiename']]) self.cm = trac.core.ComponentManager() self.cookie = Cookie() self.cookie.value = 'cookie' self.req = DummyReq() self.secure_cookies = True
def test_new_session_promotion(self): """ Verifies that even without a preexisting anonymous session, an authenticated session will be created when the user logs in. (same test as above without the initial INSERT) """ with self.env.db_transaction as db: incookie = Cookie() incookie['trac_session'] = '123456' outcookie = Cookie() req = Mock(authname='john', base_path='/', incookie=incookie, outcookie=outcookie) session = Session(self.env, req) self.assertEqual('john', session.sid) session.save() self.assertEqual([('john', 1)], self.env.db_query( "SELECT sid, authenticated FROM session"))
def test_session_promotion(self): """ Verifies that an existing anonymous session gets promoted to an authenticated session when the user logs in. """ with self.env.db_transaction as db: db("INSERT INTO session VALUES ('123456', 0, 0)") incookie = Cookie() incookie['trac_session'] = '123456' outcookie = Cookie() req = Mock(authname='john', base_path='/', incookie=incookie, outcookie=outcookie) session = Session(self.env, req) self.assertEqual('john', session.sid) session.save() self.assertEqual([('john', 1)], self.env.db_query( "SELECT sid, authenticated FROM session"))
def test_delete_anonymous_session_var(self): """ Verify that modifying a variable updates the 'session' table accordingly for an anonymous session. """ cursor = self.db.cursor() cursor.execute("INSERT INTO session VALUES ('123456', 0, 'foo', 'bar')") incookie = Cookie() incookie['trac_session'] = '123456' req = Mock(authname='anonymous', cgi_location='/', incookie=incookie, outcookie=Cookie()) session = Session(self.env, req) self.assertEqual('bar', session['foo']) del session['foo'] session.save() cursor.execute("SELECT COUNT(*) FROM session WHERE sid='123456' AND " "authenticated=0 AND var_name='foo'") self.assertEqual(0, cursor.fetchone()[0])
def test_session_change_id_with_invalid_sid(self): cookie = Cookie() req = Mock(incookie=Cookie(), outcookie=cookie, authname='anonymous', base_path='/') session = Session(self.env, req) session.change_sid('0123456789') self.assertEqual('0123456789', session.sid) session.change_sid('abcxyz') self.assertEqual('abcxyz', session.sid) session.change_sid('abc123xyz') self.assertEqual('abc123xyz', session.sid) self.assertRaises(TracError, session.change_sid, 'abc 123 xyz') self.assertRaises(TracError, session.change_sid, 'abc-123-xyz') self.assertRaises(TracError, session.change_sid, 'abc<i>123</i>xyz') self.assertRaises(TracError, session.change_sid, u'abc123xÿz') self.assertRaises(TracError, session.change_sid, u'abc¹₂³xyz') # Unicode digits
class SolutionFifteen: def __init__(self, ingredients): self.cookie = Cookie() self.ingredients = {} for value in ingredients: i = Ingredient(value) self.ingredients[i.name] = i def add_ingredient(self, name, amount): ingredient = self.ingredients.get(name) self.cookie.add(ingredient, amount) def bake(self): cookie = Cookie() # add one of each ingredient for ingredient in self.ingredients.values(): cookie.add(ingredient) rounds = 100 - len(self.ingredients) # add the rest of the 100 spoons for round in range(0, rounds): competitors = [] # make a new cookie with one more of each ingredient for ingredient in self.ingredients.values(): tmp = Cookie(cookie) # start with previous state tmp.add(ingredient) competitors.append(tmp) # look through the competitors and grab the one with # the best score for next iteration best = None highest = 0 for c in competitors: if highest < c.score: best = c highest = c.score cookie = best return cookie
def bake(self): cookie = Cookie() # add one of each ingredient for ingredient in self.ingredients.values(): cookie.add(ingredient) rounds = 100 - len(self.ingredients) # add the rest of the 100 spoons for round in range(0, rounds): competitors = [] # make a new cookie with one more of each ingredient for ingredient in self.ingredients.values(): tmp = Cookie(cookie) # start with previous state tmp.add(ingredient) competitors.append(tmp) # look through the competitors and grab the one with # the best score for next iteration best = None highest = 0 for c in competitors: if highest < c.score: best = c highest = c.score cookie = best return cookie
def delCookie(self, name, path='/', secure=False): """Delete a cookie at the browser. To do so, one has to create and send to the browser a cookie with parameters that will cause the browser to delete it. """ if name in self._cookies: self._cookies[name].delete() else: cookie = Cookie(name, None) if path: cookie.setPath(path) if secure: cookie.setSecure(secure) cookie.delete() self.addCookie(cookie)
def setCookie(self, name, value, path='/', expires='ONCLOSE', secure=False): """Set a cookie. You can also set the path (which defaults to /). You can also set when it expires. It can expire: 'NOW': this is the same as trying to delete it, but it doesn't really seem to work in IE 'ONCLOSE': the default behavior for cookies (expires when the browser closes) 'NEVER': some time in the far, far future. integer: a timestamp value tuple: a tuple, as created by the time module DateTime: an mxDateTime object for the time (assumed to be *local*, not GMT time) DateTimeDelta: a interval from the present, e.g., DateTime.DateTimeDelta(month=1) (1 month in the future) '+...': a time in the future, '...' should be something like 1w (1 week), 3h46m (3:45), etc. You can use y (year), b (month), w (week), d (day), h (hour), m (minute), s (second). This is done by the MiscUtils.DateInterval. """ cookie = Cookie(name, value) if expires == 'ONCLOSE' or not expires: pass # this is already default behavior elif expires == 'NOW': cookie.delete() return elif expires == 'NEVER': t = time.gmtime(time.time()) if expires == 'NEVER': t = (t[0] + 10,) + t[1:] t = time.strftime("%a, %d-%b-%Y %H:%M:%S GMT", t) cookie.setExpires(t) else: t = expires if type(t) is StringType and t and t[0] == '+': interval = timeDecode(t[1:]) t = time.time() + interval if type(t) in (IntType, LongType, FloatType): t = time.gmtime(t) if type(t) in (TupleType, TimeTupleType): t = time.strftime("%a, %d-%b-%Y %H:%M:%S GMT", t) if DateTime and \ (type(t) is DateTime.DateTimeDeltaType or isinstance(t, DateTime.RelativeDateTime)): t = DateTime.now() + t if DateTime and type(t) is DateTime.DateTimeType: t = (t - t.gmtoffset()).strftime("%a, %d-%b-%Y %H:%M:%S GMT") cookie.setExpires(t) if path: cookie.setPath(path) if secure: cookie.setSecure(secure) self.addCookie(cookie)
def rewrite_links(request, response, proxied_base, orig_base, proxied_url): exact_proxied_base = proxied_base if not proxied_base.endswith('/'): proxied_base += '/' exact_orig_base = orig_base if not orig_base.endswith('/'): orig_base += '/' assert (proxied_url.startswith(proxied_base) or proxied_url.split('?', 1)[0] == proxied_base[:-1]), ( "Unexpected proxied_url %r, doesn't start with proxied_base %r" % (proxied_url, proxied_base)) assert (request.url.startswith(orig_base) or request.url.split('?', 1)[0] == orig_base[:-1]), ( "Unexpected request.url %r, doesn't start with orig_base %r" % (request.url, orig_base)) def link_repl_func(link): """Rewrites a link to point to this proxy""" if link == exact_proxied_base: return exact_orig_base if not link.startswith(proxied_base): # External link, so we don't rewrite it return link new = orig_base + link[len(proxied_base):] return new if response.content_type != 'text/html' or len(response.body) == 0: pass else: if not response.charset: ## FIXME: maybe we should guess the encoding? body = response.body else: body = response.unicode_body body_doc = document_fromstring(body, base_url=proxied_url) body_doc.make_links_absolute() body_doc.rewrite_links(link_repl_func) response.body = tostring(body_doc) if response.location: ## FIXME: if you give a proxy like ## http://openplans.org, and it redirects to ## http://www.openplans.org, it won't be rewritten and ## that can be confusing -- it *shouldn't* be ## rewritten, but some better log message is required loc = urlparse.urljoin(proxied_url, response.location) loc = link_repl_func(loc) response.location = loc if 'set-cookie' in response.headers: cookies = response.headers.getall('set-cookie') del response.headers['set-cookie'] for cook in cookies: old_domain = urlparse.urlsplit(proxied_url)[1].lower() new_domain = request.host.split(':', 1)[0].lower() def rewrite_domain(match): """Rewrites domains to point to this proxy""" domain = match.group(2) if domain == old_domain: ## FIXME: doesn't catch wildcards and the sort return match.group(1) + new_domain + match.group(3) else: return match.group(0) cook = _cookie_domain_re.sub(rewrite_domain, cook) _cook = Cookie(cook) assert len(_cook.keys()) == 1 for key in _cook.keys(): _morsel = _cook[key] if _morsel.get('path'): _morsel['path'] = limit_cookie( _morsel['path'], urlparse.urlparse(exact_proxied_base).path, urlparse.urlparse(exact_orig_base).path) cook = _morsel.OutputString() response.headers.add('set-cookie', cook) return response
def __init__(self, ingredients): self.cookie = Cookie() self.ingredients = {} for value in ingredients: i = Ingredient(value) self.ingredients[i.name] = i