Ejemplo n.º 1
0
    def get_secure_cookie(self, name):
        """
        Return the signed cookie with the key ``name``, if it exists and has a
        valid signature. Otherwise, return None.
        """
        if not name in self.cookies:
            return None

        try:
            value, expires, ts, signature = self.cookies[name].value.rsplit('|', 3)
            expires = int(expires)
            ts = int(ts)
        except (AttributeError, ValueError):
            return None

        v = base64.b64encode(str(value))
        sig = generate_signature(self.connection.server.cookie_secret, expires, ts, v)

        if signature != sig or ts < time() - expires or ts > time() + expires:
            return None

        # Process value
        vtype = value[:1]
        if vtype == "j":
            value = json.loads(value[1:])
        elif vtype == "u":
            value = value[1:].decode("utf-8")
        else:
            value = value[1:]

        return value
Ejemplo n.º 2
0
    def get_secure_cookie(self, name):
        """
        Return the signed cookie with the key ``name`` if it exists and has a
        valid signature. Otherwise, return None.
        """
        if not name in self.cookies:
            return None

        try:
            value, expires, ts, signature = self.cookies[name].value.rsplit(
                '|', 3)
            expires = int(expires)
            ts = int(ts)
        except (AttributeError, ValueError):
            return None

        v = base64.b64encode(str(value))
        sig = generate_signature(self.connection.server.cookie_secret, expires,
                                 ts, v)

        if signature != sig or ts < time() - expires or ts > time() + expires:
            return None

        # Process value
        vtype = value[:1]
        if vtype == b"j":
            value = json.loads(value[1:])
        elif vtype == b"u":
            value = value[1:].decode("utf-8")
        else:
            value = value[1:]

        return value
Ejemplo n.º 3
0
    def set_secure_cookie(self, name, value, expires=30*86400, **kwargs):
        """
        Set a timestamp on a cookie and sign it, ensuring that it can't be
        altered by the client. To use this, the :class:`~pants.http.HTTPServer`
        *must* have a ``cookie_secret`` set.

        Cookies set with this function may be read with
        :func:`~pants.http.HTTPServer.get_secure_cookie`.

        =========  ===========  ============
        Argument   Default      Description
        =========  ===========  ============
        name                    The name of the cookie to set.
        value                   The value of the cookie.
        expires    ``2592000``  *Optional.* How long, in seconds, the cookie should last before expiring. The default value is equivalent to 30 days.
        =========  ===========  ============

        Additional arguments, such as ``path`` and ``httponly`` may be set by
        providing them as keyword arguments.
        """
        ts = str(int(time()))
        v = base64.b64encode(str(value))
        signature = generate_signature(
                        self.connection.server.cookie_secret, expires, ts, v)

        value = "%s|%d|%s|%s" % (value, expires, ts, signature)

        self.cookies_out[name] = value
        m = self.cookies_out[name]

        if kwargs:
            for k,v in kwargs.iteritems():
                m[k] = v
        m['expires'] = expires
Ejemplo n.º 4
0
    def set_secure_cookie(self, name, value, expires=30 * 86400, **kwargs):
        """
        Set a timestamp on a cookie and sign it, ensuring that it can't be
        altered by the client. To use this, the :class:`HTTPServer`
        *must* have a :attr:`~HTTPServer.cookie_secret` set.

        Cookies set with this function may be read with
        :meth:`get_secure_cookie`.

        If the provided value is a dictionary, list, or tuple the value will
        be serialized into JSON and encoded as UTF-8. Unicode strings will
        also be encoded as UTF-8. Byte strings will be passed as is. All other
        types will result in a :class:`TypeError`.

        =========  ===========  ============
        Argument   Default      Description
        =========  ===========  ============
        name                    The name of the cookie to set.
        value                   The value of the cookie.
        expires    ``2592000``  *Optional.* How long, in seconds, the cookie should last before expiring. The default value is equivalent to 30 days.
        =========  ===========  ============

        Additional arguments, such as ``path`` and ``secure`` may be set by
        providing them as keyword arguments. The ``HttpOnly`` attribute will
        be set by default on secure cookies..
        """
        if isinstance(value, (dict, list, tuple)):
            value = b"j" + json.dumps(value)
        elif isinstance(value, unicode):
            value = b"u" + value.encode("utf-8")
        elif not isinstance(value, str):
            raise TypeError("Invalid value for secure cookie: %r" % (value, ))
        else:
            value = b"s" + value

        ts = str(int(time()))
        v = base64.b64encode(value)
        signature = generate_signature(self.connection.server.cookie_secret,
                                       expires, ts, v)

        value = "%s|%d|%s|%s" % (value, expires, ts, signature)

        self.cookies_out[name] = value
        m = self.cookies_out[name]
        m['httponly'] = True

        if kwargs:
            for k, v in kwargs.iteritems():
                if k.lower() == 'httponly' and not v:
                    del m['httponly']
                else:
                    m[k] = v

        m['expires'] = expires
Ejemplo n.º 5
0
    def set_secure_cookie(self, name, value, expires=30*86400, **kwargs):
        """
        Set a timestamp on a cookie and sign it, ensuring that it can't be
        altered by the client. To use this, the :class:`HTTPServer`
        *must* have a :attr:`~HTTPServer.cookie_secret` set.

        Cookies set with this function may be read with
        :meth:`get_secure_cookie`.

        If the provided value is a dictionary, list, or tuple the value will
        be serialized into JSON and encoded as UTF-8. Unicode strings will
        also be encoded as UTF-8. Byte strings will be passed as is. All other
        types will result in a :class:`TypeError`.

        =========  ===========  ============
        Argument   Default      Description
        =========  ===========  ============
        name                    The name of the cookie to set.
        value                   The value of the cookie.
        expires    ``2592000``  *Optional.* How long, in seconds, the cookie should last before expiring. The default value is equivalent to 30 days.
        =========  ===========  ============

        Additional arguments, such as ``path`` and ``secure`` may be set by
        providing them as keyword arguments. The ``HttpOnly`` attribute will
        be set by default on secure cookies..
        """
        if isinstance(value, (dict, list, tuple)):
            value = b"j" + json.dumps(value)
        elif isinstance(value, unicode):
            value = b"u" + value.encode("utf-8")
        elif not isinstance(value, str):
            raise TypeError("Invalid value for secure cookie: %r" % (value,))
        else:
            value = b"s" + value

        ts = str(int(time()))
        v = base64.b64encode(value)
        signature = generate_signature(
                        self.connection.server.cookie_secret, expires, ts, v)

        value = "%s|%d|%s|%s" % (value, expires, ts, signature)

        self.cookies_out[name] = value
        m = self.cookies_out[name]
        m['httponly'] = True

        if kwargs:
            for k, v in kwargs.iteritems():
                if k.lower() == 'httponly' and not v:
                    del m['httponly']
                else:
                    m[k] = v

        m['expires'] = expires
Ejemplo n.º 6
0
    def set_secure_cookie(self, name, value, expires=30*86400, **kwargs):
        """
        Set a timestamp on a cookie and sign it, ensuring that it can't be
        altered by the client. To use this, the :class:`~pants.http.HTTPServer`
        *must* have a ``cookie_secret`` set.

        Cookies set with this function may be read with
        :func:`~pants.http.HTTPServer.get_secure_cookie`.

        If the provided value is a dictionary, list, or tuple the value will
        be converted to a string with JSON. Other values will be converted to
        strings using ``str(value)``.

        =========  ===========  ============
        Argument   Default      Description
        =========  ===========  ============
        name                    The name of the cookie to set.
        value                   The value of the cookie.
        expires    ``2592000``  *Optional.* How long, in seconds, the cookie should last before expiring. The default value is equivalent to 30 days.
        =========  ===========  ============

        Additional arguments, such as ``path`` and ``secure`` may be set by
        providing them as keyword arguments. The ``HttpOnly`` attribute will
        be set by default on secure cookies..
        """
        if isinstance(value, (dict, list, tuple, int, long, float, bool)):
            value = "j" + json.dumps(value)
        elif isinstance(value, unicode):
            value = "u" + value.encode("utf-8")
        else:
            value = "s" + str(value)

        ts = str(int(time()))
        v = base64.b64encode(value)
        signature = generate_signature(
                        self.connection.server.cookie_secret, expires, ts, v)

        value = "%s|%d|%s|%s" % (value, expires, ts, signature)

        self.cookies_out[name] = value
        m = self.cookies_out[name]
        m['httponly'] = True

        if kwargs:
            for k, v in kwargs.iteritems():
                if k.lower() == 'httponly' and not v:
                    del m['httponly']
                else:
                    m[k] = v

        m['expires'] = expires
Ejemplo n.º 7
0
    def get_secure_cookie(self, name):
        """
        Return the signed cookie with the key ``name``, if it exists and has a
        valid signature. Otherwise, return None.
        """
        try:
            value, expires, ts, signature = self.cookies[name].value.split('|')
            expires = int(expires)
            ts = int(ts)
        except (AttributeError, ValueError):
            return None

        v = base64.b64encode(str(value))
        sig = generate_signature(self.connection.server.cookie_secret, expires, ts, v)

        if signature != sig or ts < time() - expires or ts > time() + expires:
            return None

        return value