Python Cookie.CookieError() Examples

The following are 9 code examples of Cookie.CookieError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module Cookie , or try the search function .
Example #1
Source File: login.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def get_user_info(http_cookie, cookie_name=_COOKIE_NAME):
  """Gets the requestor's user info from an HTTP Cookie header.

  Args:
    http_cookie: The value of the 'Cookie' HTTP request header.
    cookie_name: The name of the cookie that stores the user info.

  Returns:
    A tuple (email, admin, user_id) where:
      email: The user's email address, if any.
      admin: True if the user is an admin; False otherwise.
      user_id: The user ID, if any.
  """
  try:
    cookie = Cookie.SimpleCookie(http_cookie)
  except Cookie.CookieError:
    return '', False, ''

  cookie_dict = dict((k, v.value) for k, v in cookie.iteritems())
  return _get_user_info_from_dict(cookie_dict, cookie_name) 
Example #2
Source File: login.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def get_user_info(http_cookie, cookie_name=_COOKIE_NAME):
  """Gets the requestor's user info from an HTTP Cookie header.

  Args:
    http_cookie: The value of the 'Cookie' HTTP request header.
    cookie_name: The name of the cookie that stores the user info.

  Returns:
    A tuple (email, admin, user_id) where:
      email: The user's email address, if any.
      admin: True if the user is an admin; False otherwise.
      user_id: The user ID, if any.
  """
  try:
    cookie = Cookie.SimpleCookie(http_cookie)
  except Cookie.CookieError:
    return '', False, ''

  cookie_dict = dict((k, v.value) for k, v in cookie.iteritems())
  return _get_user_info_from_dict(cookie_dict, cookie_name) 
Example #3
Source File: dev_appserver_login.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def GetUserInfo(http_cookie, cookie_name=COOKIE_NAME):
  """Get the requestor's user info from the HTTP cookie in the CGI environment.

  Args:
    http_cookie: Value of the HTTP_COOKIE environment variable.
    cookie_name: Name of the cookie that stores the user info.

  Returns:
    Tuple (email, admin, user_id) where:
      email: The user's email address, if any.
      admin: True if the user is an admin; False otherwise.
      user_id: The user ID, if any.
  """
  try:
    cookie = Cookie.SimpleCookie(http_cookie)
  except Cookie.CookieError:
    return '', False, ''

  cookie_value = ''
  if cookie_name in cookie:
    cookie_value = cookie[cookie_name].value

  email, admin, user_id = (cookie_value.split(':') + ['', '', ''])[:3]
  return email, (admin == 'True'), user_id 
Example #4
Source File: session.py    From malwareHunter with GNU General Public License v2.0 5 votes vote down vote up
def _set_cookie_http_only(self):
        try:
            if self.httponly:
                self.cookie[self.key]['httponly'] = True
        except Cookie.CookieError, e:
            if 'Invalid Attribute httponly' not in str(e):
                raise
            util.warn('Python 2.6+ is required to use httponly') 
Example #5
Source File: session.py    From malwareHunter with GNU General Public License v2.0 5 votes vote down vote up
def _set_cookie_http_only(self):
        try:
            if self.httponly:
                self.cookie[self.key]['httponly'] = True
        except Cookie.CookieError, e:
            if 'Invalid Attribute httponly' not in str(e):
                raise
            util.warn('Python 2.6+ is required to use httponly') 
Example #6
Source File: webapi.py    From nightmare with GNU General Public License v2.0 4 votes vote down vote up
def parse_cookies(http_cookie):
    r"""Parse a HTTP_COOKIE header and return dict of cookie names and decoded values.
        
    >>> sorted(parse_cookies('').items())
    []
    >>> sorted(parse_cookies('a=1').items())
    [('a', '1')]
    >>> sorted(parse_cookies('a=1%202').items())
    [('a', '1 2')]
    >>> sorted(parse_cookies('a=Z%C3%A9Z').items())
    [('a', 'Z\xc3\xa9Z')]
    >>> sorted(parse_cookies('a=1; b=2; c=3').items())
    [('a', '1'), ('b', '2'), ('c', '3')]
    >>> sorted(parse_cookies('a=1; b=w("x")|y=z; c=3').items())
    [('a', '1'), ('b', 'w('), ('c', '3')]
    >>> sorted(parse_cookies('a=1; b=w(%22x%22)|y=z; c=3').items())
    [('a', '1'), ('b', 'w("x")|y=z'), ('c', '3')]

    >>> sorted(parse_cookies('keebler=E=mc2').items())
    [('keebler', 'E=mc2')]
    >>> sorted(parse_cookies(r'keebler="E=mc2; L=\"Loves\"; fudge=\012;"').items())
    [('keebler', 'E=mc2; L="Loves"; fudge=\n;')]
    """
    #print "parse_cookies"
    if '"' in http_cookie:
        # HTTP_COOKIE has quotes in it, use slow but correct cookie parsing
        cookie = Cookie.SimpleCookie()
        try:
            cookie.load(http_cookie)
        except Cookie.CookieError:
            # If HTTP_COOKIE header is malformed, try at least to load the cookies we can by
            # first splitting on ';' and loading each attr=value pair separately
            cookie = Cookie.SimpleCookie()
            for attr_value in http_cookie.split(';'):
                try:
                    cookie.load(attr_value)
                except Cookie.CookieError:
                    pass
        cookies = dict((k, urllib.unquote(v.value)) for k, v in cookie.iteritems())
    else:
        # HTTP_COOKIE doesn't have quotes, use fast cookie parsing
        cookies = {}
        for key_value in http_cookie.split(';'):
            key_value = key_value.split('=', 1)
            if len(key_value) == 2:
                key, value = key_value
                cookies[key.strip()] = urllib.unquote(value.strip())
    return cookies 
Example #7
Source File: session.py    From malwareHunter with GNU General Public License v2.0 4 votes vote down vote up
def __init__(self, request, key='beaker.session.id', timeout=None,
                 cookie_expires=True, cookie_domain=None, cookie_path='/',
                 encrypt_key=None, validate_key=None, secure=False,
                 httponly=False, **kwargs):

        if not crypto.has_aes and encrypt_key:
            raise InvalidCryptoBackendError("No AES library is installed, can't generate "
                                  "encrypted cookie-only Session.")

        self.request = request
        self.key = key
        self.timeout = timeout
        self.cookie_expires = cookie_expires
        self.encrypt_key = encrypt_key
        self.validate_key = validate_key
        self.request['set_cookie'] = False
        self.secure = secure
        self.httponly = httponly
        self._domain = cookie_domain
        self._path = cookie_path

        try:
            cookieheader = request['cookie']
        except KeyError:
            cookieheader = ''

        if validate_key is None:
            raise BeakerException("No validate_key specified for Cookie only "
                                  "Session.")

        try:
            self.cookie = SignedCookie(validate_key, input=cookieheader)
        except Cookie.CookieError:
            self.cookie = SignedCookie(validate_key, input=None)

        self['_id'] = _session_id()
        self.is_new = True

        # If we have a cookie, load it
        if self.key in self.cookie and self.cookie[self.key].value is not None:
            self.is_new = False
            try:
                cookie_data = self.cookie[self.key].value
                self.update(self._decrypt_data(cookie_data))
                self._path = self.get('_path', '/')
            except:
                pass
            if self.timeout is not None and time.time() - \
               self['_accessed_time'] > self.timeout:
                self.clear()
            self.accessed_dict = self.copy()
            self._create_cookie() 
Example #8
Source File: session.py    From malwareHunter with GNU General Public License v2.0 4 votes vote down vote up
def __init__(self, request, key='beaker.session.id', timeout=None,
                 cookie_expires=True, cookie_domain=None, cookie_path='/',
                 encrypt_key=None, validate_key=None, secure=False,
                 httponly=False, **kwargs):

        if not crypto.has_aes and encrypt_key:
            raise InvalidCryptoBackendError("No AES library is installed, can't generate "
                                  "encrypted cookie-only Session.")

        self.request = request
        self.key = key
        self.timeout = timeout
        self.cookie_expires = cookie_expires
        self.encrypt_key = encrypt_key
        self.validate_key = validate_key
        self.request['set_cookie'] = False
        self.secure = secure
        self.httponly = httponly
        self._domain = cookie_domain
        self._path = cookie_path

        try:
            cookieheader = request['cookie']
        except KeyError:
            cookieheader = ''

        if validate_key is None:
            raise BeakerException("No validate_key specified for Cookie only "
                                  "Session.")

        try:
            self.cookie = SignedCookie(validate_key, input=cookieheader)
        except Cookie.CookieError:
            self.cookie = SignedCookie(validate_key, input=None)

        self['_id'] = _session_id()
        self.is_new = True

        # If we have a cookie, load it
        if self.key in self.cookie and self.cookie[self.key].value is not None:
            self.is_new = False
            try:
                cookie_data = self.cookie[self.key].value
                self.update(self._decrypt_data(cookie_data))
                self._path = self.get('_path', '/')
            except:
                pass
            if self.timeout is not None and time.time() - \
               self['_accessed_time'] > self.timeout:
                self.clear()
            self.accessed_dict = self.copy()
            self._create_cookie() 
Example #9
Source File: webapi.py    From cosa-nostra with GNU General Public License v3.0 4 votes vote down vote up
def parse_cookies(http_cookie):
    r"""Parse a HTTP_COOKIE header and return dict of cookie names and decoded values.
        
    >>> sorted(parse_cookies('').items())
    []
    >>> sorted(parse_cookies('a=1').items())
    [('a', '1')]
    >>> sorted(parse_cookies('a=1%202').items())
    [('a', '1 2')]
    >>> sorted(parse_cookies('a=Z%C3%A9Z').items())
    [('a', 'Z\xc3\xa9Z')]
    >>> sorted(parse_cookies('a=1; b=2; c=3').items())
    [('a', '1'), ('b', '2'), ('c', '3')]
    >>> sorted(parse_cookies('a=1; b=w("x")|y=z; c=3').items())
    [('a', '1'), ('b', 'w('), ('c', '3')]
    >>> sorted(parse_cookies('a=1; b=w(%22x%22)|y=z; c=3').items())
    [('a', '1'), ('b', 'w("x")|y=z'), ('c', '3')]

    >>> sorted(parse_cookies('keebler=E=mc2').items())
    [('keebler', 'E=mc2')]
    >>> sorted(parse_cookies(r'keebler="E=mc2; L=\"Loves\"; fudge=\012;"').items())
    [('keebler', 'E=mc2; L="Loves"; fudge=\n;')]
    """
    #print "parse_cookies"
    if '"' in http_cookie:
        # HTTP_COOKIE has quotes in it, use slow but correct cookie parsing
        cookie = Cookie.SimpleCookie()
        try:
            cookie.load(http_cookie)
        except Cookie.CookieError:
            # If HTTP_COOKIE header is malformed, try at least to load the cookies we can by
            # first splitting on ';' and loading each attr=value pair separately
            cookie = Cookie.SimpleCookie()
            for attr_value in http_cookie.split(';'):
                try:
                    cookie.load(attr_value)
                except Cookie.CookieError:
                    pass
        cookies = dict((k, urllib.unquote(v.value)) for k, v in cookie.iteritems())
    else:
        # HTTP_COOKIE doesn't have quotes, use fast cookie parsing
        cookies = {}
        for key_value in http_cookie.split(';'):
            key_value = key_value.split('=', 1)
            if len(key_value) == 2:
                key, value = key_value
                cookies[key.strip()] = urllib.unquote(value.strip())
    return cookies