Beispiel #1
0
 def cookies(self):
     try:
         cookie = hcookies.BaseCookie()
         cookie.load(self.headers.get("cookie"))
         return cookie
     except Exception as e:
         return hcookies.BaseCookie()
Beispiel #2
0
 def cookies(self):
     try:
         cookie = hcookies.BaseCookie()
         for _, v in self.headers.pairs('set-cookie'):
             cookie.load(v)
         return cookie
     except Exception as e:
         return hcookies.BaseCookie()
Beispiel #3
0
    def InfoPage(self, uri):
        """ Renders an information page with the POST endpoint and cookie flag.

    Args:
      uri: a string containing the request URI
    Returns:
      A string with the contents of the info page to be displayed
    """
        page = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html><head>
<title>Bulk Loader</title>
</head><body>"""

        page += ('The bulk load endpoint is: <a href="%s">%s</a><br />\n' %
                 (uri, uri))

        cookies = os.environ.get('HTTP_COOKIE', None)
        if cookies:
            cookie = Cookie.BaseCookie(cookies)
            for param in ['ACSID', 'dev_appserver_login']:
                value = cookie.get(param)
                if value:
                    page += (
                        "Pass this flag to the client: --cookie='%s=%s'\n" %
                        (param, value.value))
                    break

        else:
            page += 'No cookie found!\n'

        page += '</body></html>'
        return page
Beispiel #4
0
def cookie_output(name, value):
    cookie = Cookie.BaseCookie()
    expiry = datetime.datetime.now() + datetime.timedelta(days=30)
    cookie[name] = value
    cookie[name]["path"] = "/"
    cookie[name]["expires"] = expiry.strftime("%a, %d-%b-%Y %H:%M:%S PST")
    return cookie[name].OutputString()
Beispiel #5
0
 def set_cookie(self,
                name,
                value,
                domain=None,
                expires=None,
                path="/",
                expires_days=None):
     """Sets the given cookie name/value with the given options."""
     name = _utf8(name)
     value = _utf8(value)
     if re.search(r"[\x00-\x20]", name +
                  value):  # Don't let us accidentally inject bad stuff
         raise ValueError("Invalid cookie %r:%r" % (name, value))
     new_cookie = Cookie.BaseCookie()
     new_cookie[name] = value
     if domain:
         new_cookie[name]["domain"] = domain
     if expires_days is not None and not expires:
         expires = datetime.datetime.utcnow() + datetime.timedelta(
             days=expires_days)
     if expires:
         timestamp = calendar.timegm(expires.utctimetuple())
         new_cookie[name]["expires"] = email.utils.formatdate(
             timestamp, localtime=False, usegmt=True)
     if path:
         new_cookie[name]["path"] = path
     for morsel in new_cookie.values():
         self.response.headers.add_header('Set-Cookie',
                                          morsel.OutputString(None))
Beispiel #6
0
def get_cookie_value(key):
    cookies = None
    try:
        cookies = Cookie.BaseCookie(os.environ.get('HTTP_COOKIE', ''))
    except Cookie.CookieError, error:
        logging.debug("Ignoring Cookie Error, skipping get cookie: '%s'" %
                      error)
Beispiel #7
0
def set_cookie_value(key,
                     value='',
                     max_age=None,
                     path='/',
                     domain=None,
                     secure=None,
                     httponly=False,
                     version=None,
                     comment=None):
    cookies = Cookie.BaseCookie()
    cookies[key] = value
    for var_name, var_value in [
        ('max-age', max_age),
        ('path', path),
        ('domain', domain),
        ('secure', secure),
            #('HttpOnly', httponly), Python 2.6 is required for httponly cookies
        ('version', version),
        ('comment', comment),
    ]:
        if var_value is not None and var_value is not False:
            cookies[key][var_name] = str(var_value)
        if max_age is not None:
            cookies[key]['expires'] = max_age

    cookies_header = cookies[key].output(header='').lstrip()

    if httponly:
        # We have to manually add this part of the header until GAE uses Python 2.6.
        cookies_header += "; HttpOnly"

    return cookies_header
Beispiel #8
0
    def __init__(self,
                 proto='HTTP/1.0',
                 host=None,
                 method=None,
                 uri=None,
                 args=None,
                 remote_ip=None,
                 headers=None,
                 body=None,
                 body_file=None):
        self.proto = proto
        self.host = host
        self.method = method
        self.uri = uri
        self.remote_ip = remote_ip
        self.headers = headers
        self.body = body
        self.body_file = body_file

        self.path, _, self.query = uri.partition('?')
        self.query_args = urlparse.parse_qs(self.query, keep_blank_values=True)
        self.args = args

        self.cookies = {}
        for cookie in self.headers.get_list("cookie", []):
            try:
                for name, morsel in Cookie.BaseCookie(cookie).iteritems():
                    self.cookies[name] = morsel.value
            except Cookie.CookieError:
                pass
Beispiel #9
0
    def request_details(self, request, response=None):

        view_name = getattr(request, '_stats_view_name', None)
        local_name = getattr(request, '_stats_local_name', None)

        if hasattr(request, 'device'):
            devid = request.device.devid
        else:
            devid = None

        if hasattr(request, 'session'):
            session_key = request.session.session_key
        else:
            try:
                session_key = Cookie.BaseCookie(request.META.get('HTTP_COOKIE', ''))['sessionid'].value
            except:
                session_key = ''

        requested = getattr(request, 'requested', time.time())

        return {
            'session_key': session_key,
            'user_agent': request.META.get('HTTP_USER_AGENT'),
            'device_id': devid,
            'ip_address': request.META['REMOTE_ADDR'],
            'referer': request.META.get('HTTP_REFERER'),
            'full_path': request.get_full_path(),
            'requested': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(requested)) + ('%.6f' % (requested % 1))[1:],
            'response_time': (time.time() - requested) if hasattr(request, 'requested') else None,
            'local_name': local_name,
            'view_name': view_name,
            'status_code': response.status_code if response else 500,
            'redirect_to': response.get('Location', None) if response else None,
        }
Beispiel #10
0
def get_profile_from_cookies():
    """ Get Facebook profile data of current logged in Facebook user

    Returns:
        A dict of Facebook profile data of the current logged in Facebook user.
        For example, this would return the following for Mark Zuckerberg:

        {
           "id": "4",
           "name": "Mark Zuckerberg",
           "first_name": "Mark",
           "last_name": "Zuckerberg",
           "link": "https://www.facebook.com/zuck",
           "username": "******",
           "gender": "male",
           "locale": "en_US"
        }

    """

    if App.facebook_app_secret is None:
        return None

    cookies = None
    try:
        cookies = Cookie.BaseCookie(os.environ.get('HTTP_COOKIE', ''))
    except Cookie.CookieError, error:
        logging.debug("Ignoring Cookie Error, skipping Facebook login: '******'" % error)
def get_phantom_user_id_from_cookies():
    cookies = None
    try:
        cookies = Cookie.BaseCookie(os.environ.get('HTTP_COOKIE', ''))
    except Cookie.CookieError, error:
        logging.critical("Ignoring Cookie Error: '%s'" % error)
        return None
Beispiel #12
0
def parse_cookies(cookie_string, verbose, url=None, response_cookie=False):
    """
    Parses the cookie string from an HTTP header into a query
    * Request 'Cookie'
        query = (name, value)
    * Response 'Set-Cookie'
        query = (name, value, domain, path, expires, max-age, httponly, secure, comment, version)
    """
    queries = list()
    attrs = ()
    try:
        if type(cookie_string) == unicode:
            cookie_string = cookie_string.encode('utf-8')
        cookie = Cookie.BaseCookie(cookie_string)  # requires str type
        for key in cookie.keys():
            name = encode_to_unicode(key)
            value = encode_to_unicode(cookie[key].coded_value)
            if response_cookie:
                attrs = parse_cookie_attributes(cookie, key, url)
            query = (name, value) + attrs
            queries.append(query)
    except Cookie.CookieError, e:
        if verbose: print "[ERROR] - Malformed cookie string"
        if verbose: print "--------- " + cookie_string
        if verbose: print e
        pass
Beispiel #13
0
def namespace_manager_default_namespace_for_request():
  """Determine which namespace is to be used for a request.

  The value of _NAMESPACE_PICKER has the following effects:

  If _USE_SERVER_NAME, we read server name
  foo.guestbook-isv.appspot.com and set the namespace.

  If _USE_GOOGLE_APPS_DOMAIN, we allow the namespace manager to infer
  the namespace from the request.

  If _USE_COOKIE, then the ISV might have a gateway page that sets a
  cookie called 'namespace', and we set the namespace to the cookie's value
  """
  name = None

  if _NAMESPACE_PICKER == _USE_SERVER_NAME:
    name = os.environ['SERVER_NAME']
  elif _NAMESPACE_PICKER == _USE_GOOGLE_APPS_DOMAIN:
    name = namespace_manager.google_apps_namespace()
  elif _NAMESPACE_PICKER == _USE_COOKIE:
    cookies = os.environ.get('HTTP_COOKIE', None)
    if cookies:
      name = Cookie.BaseCookie(cookies).get('namespace')

  return name
Beispiel #14
0
  def set_cookie(self, name, value, domain=None, expires=None, path="/",
           expires_days=None, **kwargs):
    """Sets the given cookie name/value with the given options.

    Additional keyword arguments are set on the Cookie.Morsel
    directly.
    See http://docs.python.org/library/cookie.html#morsel-objects
    for available attributes.
    """
    name = LilCookies._utf8(name)
    value = LilCookies._utf8(value)
    if re.search(r"[\x00-\x20]", name + value):
      # Don't let us accidentally inject bad stuff
      raise ValueError("Invalid cookie %r: %r" % (name, value))
    if not hasattr(self, "_new_cookies"):
      self._new_cookies = []
    new_cookie = Cookie.BaseCookie()
    self._new_cookies.append(new_cookie)
    new_cookie[name] = value
    if domain:
      new_cookie[name]["domain"] = domain
    if expires_days is not None and not expires:
      expires = datetime.datetime.utcnow() + datetime.timedelta(days=expires_days)
    if expires:
      timestamp = calendar.timegm(expires.utctimetuple())
      new_cookie[name]["expires"] = email.utils.formatdate(
        timestamp, localtime=False, usegmt=True)
    if path:
      new_cookie[name]["path"] = path
    for k, v in kwargs.iteritems():
      new_cookie[name][k] = v
    
    # The 2 lines below were not in Tornado.  Instead, they output all their cookies to the headers at once before a response flush.
    for vals in new_cookie.values():
      self.response.headers._headers.append(('Set-Cookie', vals.OutputString(None)))
Beispiel #15
0
	def get_rid_cookie(self):
		cookies = self.headers.get('Cookie')
		rid = ""
		if cookies:
			stub = Cookie.BaseCookie(cookies).get('rid')
			if stub:
				rid = stub.value
		return rid
Beispiel #16
0
def has_cookie(request):
    cookies = request.getHttp().get('HTTP_COOKIE', None)
    if cookies:
        morsel = Cookie.BaseCookie(cookies).get('openid_remembered')
        if morsel and morsel.value == 'yes':
            return True

    return False
Beispiel #17
0
	def get_jsesh_cookie(self):
		cookies = self.headers.get('Cookie')
		jsesh = ""
		if cookies:
			stub = Cookie.BaseCookie(cookies).get('JSESSIONID')
			if stub:
				jsesh = stub.value
		return jsesh
Beispiel #18
0
 def load_cookies(self, raw_cookies):
     # parse cookies
     base_cookies = Cookie.BaseCookie()
     base_cookies.load(raw_cookies)
     # rebuild proper simple dictionary
     self.cookies = dict()
     for key, morsel in base_cookies.items():
         self.cookies[key] = morsel.value
Beispiel #19
0
 def getresponse(self):
     rsp = super(SecureHTTPConnection, self).getresponse()
     for hdr in rsp.msg.headers:
         if hdr.startswith('Set-Cookie:'):
             c = Cookie.BaseCookie(hdr[11:])
             for k in c:
                 self.cookies[k] = c[k].value
     return rsp
Beispiel #20
0
    def HasCookie(self, trust_root):
        cookies = os.environ.get('HTTP_COOKIE', None)
        if cookies:
            morsel = Cookie.BaseCookie(cookies).get('openid_remembered_%s' %
                                                    digest(trust_root))
            if morsel and morsel.value == 'yes':
                return True

        return False
Beispiel #21
0
def extractToken(response):
	info = response.info()
#	print "info:", info
	cookie = info['Set-Cookie']
	cookie = Cookie.BaseCookie(cookie)
#	print "cookie:", cookie
	token = cookie['token']
#	print "token:", token.value
	return token.value
Beispiel #22
0
 def _get_cookie(self, name):
     """ Get a cookie from the request """
     value = None
     cookie_string = ";".join(self.headers.getheaders('Cookie'))
     cookies = Cookie.BaseCookie(cookie_string)
     if cookies:
         if session_cookie_name in cookies:
             value = cookies[session_cookie_name].value
     return value
Beispiel #23
0
 def set_cookies(self, c):
     self.headers.delete("set-cookie")
     if isinstance(c, hcookies.BaseCookie):
         cookies = c
     else:
         cookies = hcookies.BaseCookie()
         for k, v in c.items():
             cookies[k] = v
     for _, m in c.items():
         self.headers.add("Set-Cookie", m.OutputString())
 def get_cookie(self, name):
     cookies = self.headers.get('Cookie')
     if cookies:
         authcookie = Cookie.BaseCookie(cookies).get(name)
         if authcookie:
             return authcookie.value
         else:
             return None
     else:
         return None
Beispiel #25
0
 def cookies(self):
     if self._cookies is None:
         parser = Cookie.BaseCookie()
         cookie_headers = self.headers.get("cookie", "")
         parser.load(cookie_headers)
         cookies = Cookies()
         for key, value in parser.iteritems():
             cookies[key] = CookieValue(value)
         self._cookies = cookies
     return self._cookies
Beispiel #26
0
 def cookies(self):
     """A dictionary of Cookie.Morsel objects."""
     if not hasattr(self, "_cookies"):
         self._cookies = Cookie.BaseCookie()
         if "Cookie" in self.request.headers:
             try:
                 self._cookies.load(self.request.headers["Cookie"])
             except:
                 self.clear_all_cookies()
     return self._cookies
Beispiel #27
0
 def _set_game_object(self):
     """Setting the game object to self._game using the cookies"""
     cookie = Cookie.BaseCookie(self._request.get_all_header()["cookie"])
     if "pid" in cookie:
         pid = cookie["pid"].value
         if pid in self.common.pid_client:
             self._game = self.common.pid_client[pid]
             self.logger.debug("Set game as %s", self._game)
     else:
         self.logger.debug("Game object not found")
def get_profile_from_cookies():

    if App.facebook_app_secret is None:
        return None

    cookies = None
    try:
        cookies = Cookie.BaseCookie(os.environ.get('HTTP_COOKIE', ''))
    except Cookie.CookieError, error:
        logging.debug("Ignoring Cookie Error, skipping Facebook login: '******'" %
                      error)
Beispiel #29
0
    def unset_cookie(self, name):
        """Remove a cookie from those that are being sent with the response"""
        cookies = self.headers.get("Set-Cookie")
        parser = Cookie.BaseCookie()
        for cookie in cookies:
            parser.load(cookie)

        if name in parser.keys():
            del self.headers["Set-Cookie"]
            for m in parser.values():
                if m.key != name:
                    self.headers.append(("Set-Cookie", m.OutputString()))
Beispiel #30
0
 def getresponse(self):
     try:
         rsp = super(SecureHTTPConnection, self).getresponse()
         for hdr in rsp.msg.headers:
             if hdr.startswith('Set-Cookie:'):
                 c = Cookie.BaseCookie(hdr[11:])
                 for k in c:
                     self.cookies[k] = c[k].value
     except httplib.BadStatusLine:
         self.broken = True
         raise
     return rsp