def unset_cookie(self, key): """ Unset a cookie with the given name (remove it from the response). If there are multiple cookies (e.g., two cookies with the same name and different paths or domains), all such cookies will be deleted. """ existing = self.response.headers.get_all('Set-Cookie') if not existing: raise KeyError( "No cookies at all have been set") del self.response.headers['Set-Cookie'] found = False for header in existing: cookies = BaseCookie() cookies.load(header) if key in cookies: found = True del cookies[key] header = cookies.output(header='').lstrip() if header: self.response.headers.add('Set-Cookie', header) if not found: raise KeyError( "No cookie has been set with the name %r" % key)
def unset_cookie(self, key): """ Unset a cookie with the given name (remove from the response). If there are multiple cookies (e.g., two cookies with the same name and different paths or domains), all such cookies will be deleted. Args: key: string that is the cookie's name (mandatory) Side effects: delete from self.response.headers all cookies with that name Raises: KeyError if the response had no such cookies (or, none at all) """ existing = self.response.headers.getall('Set-Cookie') if not existing: raise KeyError("No cookies at all had been set") # remove all set-cookie headers, then put back those (if any) that # should not be removed del self.response.headers['Set-Cookie'] found = False for header in existing: cookies = BaseCookie() cookies.load(header) if key in cookies: found = True del cookies[key] header = cookies.output(header='').lstrip() if header: self.response.headers.add_header('Set-Cookie', header) if not found: raise KeyError("No cookie had been set with name %r" % key)
def prepareResponse(self, response): for key, value in response.headers.items(): if key.lower() == "set-cookie": cookie = BaseCookie(value) # use all attributes but 'secure', because then the browser won't send the cookie anymore value = cookie.output(attrs=['expires','path','comment','domain','max-age','secure','version','httponly'], header="") self.setHeader(key, value) self.setResponseCode(response.code)
def prepareResponse(self, response): for key, value in response.headers.items(): if key.lower() == "set-cookie": cookie = BaseCookie(value) # use all attributes but 'secure', because then the browser won't send the cookie anymore value = cookie.output(attrs=[ 'expires', 'path', 'comment', 'domain', 'max-age', 'secure', 'version', 'httponly' ], header="") self.setHeader(key, value) self.setResponseCode(response.code)
def do_login(u, login, pwd): conn = httplib.HTTPConnection(u.hostname, u.port) conn.request('GET', u.path) r = conn.getresponse() if r.status != 200: raise Exception, r.status, r.reason h = pymayhem.FormRipper() h.feed(r.read()) f = findlogin(h.forms) if f is None: raise ValueError, 'login form not found' f['sausr'] = login f['sapwd'] = pwd params = f.get_form_data() headers = {'Content-type': 'application/x-www-form-urlencoded', 'Referer': u.geturl(), 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:14.0) Gecko/20100101 Firefox/14.0.1', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-us,en;q=0.5' } lu = urlparse(f.action) conn = httplib.HTTPConnection(lu.hostname, lu.port) conn.request('POST', lu.path, params, headers) r = conn.getresponse() if r.status != 302: raise ValueError, 'bad response', r cookie = None location = None for (k, v) in r.getheaders(): if k == 'set-cookie': cookie = v elif k == 'location': location = urlparse(v) c = Cookie(cookie) c = c.output(c.keys(), '', ', ').strip() q = location.query return (c, q)
def set_cookie(self, name, value, domain=None, expires=None, path='/', expires_days=None): """Sets the given cookie name/value with the given options. :param name: Cookie name. :param value: Cookie value. :param domain: Cookie domain. :param expires: A expiration date as a `datetime` object. :param path: Cookie path. :param expires_days: Number of days to calculate expiration. :return: `None`. """ if expires_days is not None and not expires: expires = datetime.datetime.utcnow() + datetime.timedelta( days=expires_days) cookie = BaseCookie() cookie[name] = str(base64.b64encode(value)) if expires: timestamp = calendar.timegm(expires.utctimetuple()) expires = email.utils.formatdate(timestamp, localtime=False, usegmt=True) cookie[name]['expires'] = expires if path: cookie[name]['path'] = path if domain: cookie[name]['domain'] = domain cookie_str = cookie.output() if cookie_str.startswith('Set-Cookie:'): cookie_str = cookie_str[11:].strip() self._response.headers.add_header('Set-Cookie', cookie_str)
def unset_cookie(self, key): existing = self.headers.get_all('Set-Cookie') if not existing: raise KeyError('No cookies have been set') del self.headers['Set-Cookie'] found = False for header in existing: cookies = BaseCookie() cookies.load(header) if key in cookies: found = True del cookies[key] header = cookies.output(header='').lstrip() if header: if header.endswith(';'): header = header[:-1] self.headers.add_header('Set-Cookie', header) if not found: raise KeyError('No cookie has been set with the name %r' % key)
def get(self): user = users.get_current_user() if user: self.response.out.write('''<!DOCTYPE html> <html> <head> <title>Authorized</title> <script language="Javascript" type="text/javascript"> //<![CDATA[ if (window.opener && !window.opener.closed) { window.opener.location.href = window.opener.location.href; } if (window.parent) { window.parent.location.href = window.parent.location.href; } window.close(); //]]> </script> </head> <body> </body> </html>''') return openid_url = self.request.get('openid_url', None) if openid_url is None or len(openid_url.strip()) == 0: openid_url = ID_PROVIDERS.get(self.request.get('provider'), None) if openid_url is not None: c = BaseCookie() c['idprovider'] = openid_url c['idprovider']['Max-Age'] = '2592000' self.response.headers.add_header('Set-Cookie', c.output(header="")) self.redirect(users.create_login_url(self.request.url, federated_identity = openid_url)) return else: self.response.out.write('''<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>What's Your OpenID URL</title> <!--[if lt IE 9]> <script src="/static/js/IE9.js" type="text/javascript"></script><![endif]--> <style type="text/css"> html, body, h1, h2, form, fieldset, legend, ol, li { margin: 0; padding: 0; } body { background: #ffffff; color: #111111; padding: 20px; font-family: Calibri,sans-serif; } .panel {text-align: center; padding: 3px;border-radius: 15px;background: #eeeeee; margin:150px 100px 0 100px;} .formheader {text-align: left; margin-left:65px;font-size:125%; color: #555555;padding:0} .formheader a{font-size: small;color:#888888;} #openid_url{background:url(/static/image/openid.png) no-repeat #FFF 2px; font-size: 16px; font-family: Calibri,sans-serif; padding-left:26px; width: 350px; height: 24px} button {font-size: 16px; margin:10px} </style> </head> <body> <form id="provider" method="post" name="provider"> <div class="panel"> <div class="formheader">Sign in with OpenID <a href="http://openid.net/get-an-openid/what-is-openid/" target="_blank">What is OpenID</a></div> <input id="openid_url" name="openid_url" type="text" placeholder="Please Enter Your OpenID" autocapitalize="off" autocorrect="off" required autofocus/> <button type="submit">Sign in</button> </div> </form> </body> </html> ''')
def get(self): user = users.get_current_user() if user: self.response.out.write('''<!DOCTYPE html> <html> <head> <title>Authorized</title> <script language="Javascript" type="text/javascript"> //<![CDATA[ if (window.opener && !window.opener.closed) { window.opener.location.href = window.opener.location.href; } if (window.parent) { window.parent.location.href = window.parent.location.href; } window.close(); //]]> </script> </head> <body> </body> </html>''') return openid_url = self.request.get('openid_url', None) if openid_url is None or len(openid_url.strip()) == 0: openid_url = ID_PROVIDERS.get(self.request.get('provider'), None) if openid_url is not None: c = BaseCookie() c['idprovider'] = openid_url c['idprovider']['Max-Age'] = '2592000' self.response.headers.add_header('Set-Cookie', c.output(header="")) self.redirect( users.create_login_url(self.request.url, federated_identity=openid_url)) return else: self.response.out.write('''<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>What's Your OpenID URL</title> <!--[if lt IE 9]> <script src="/static/js/IE9.js" type="text/javascript"></script><![endif]--> <style type="text/css"> html, body, h1, h2, form, fieldset, legend, ol, li { margin: 0; padding: 0; } body { background: #ffffff; color: #111111; padding: 20px; font-family: Calibri,sans-serif; } .panel {text-align: center; padding: 3px;border-radius: 15px;background: #eeeeee; margin:150px 100px 0 100px;} .formheader {text-align: left; margin-left:65px;font-size:125%; color: #555555;padding:0} .formheader a{font-size: small;color:#888888;} #openid_url{background:url(/static/image/openid.png) no-repeat #FFF 2px; font-size: 16px; font-family: Calibri,sans-serif; padding-left:26px; width: 350px; height: 24px} button {font-size: 16px; margin:10px} </style> </head> <body> <form id="provider" method="post" name="provider"> <div class="panel"> <div class="formheader">Sign in with OpenID <a href="http://openid.net/get-an-openid/what-is-openid/" target="_blank">What is OpenID</a></div> <input id="openid_url" name="openid_url" type="text" placeholder="Please Enter Your OpenID" autocapitalize="off" autocorrect="off" required autofocus/> <button type="submit">Sign in</button> </div> </form> </body> </html> ''')