Back to index

moin  1.9.0~rc2
Public Member Functions | Public Attributes | Static Public Attributes | Properties
MoinMoin.support.werkzeug.contrib.securecookie.SecureCookie Class Reference
Inheritance diagram for MoinMoin.support.werkzeug.contrib.securecookie.SecureCookie:
Inheritance graph
[legend]
Collaboration diagram for MoinMoin.support.werkzeug.contrib.securecookie.SecureCookie:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def __init__
def __repr__
def should_save
def quote
def unquote
def serialize
def unserialize
def load_cookie
def save_cookie

Public Attributes

 secret_key
 new

Static Public Attributes

 hash_method = _default_hash
 serialization_method = pickle
 quote_base64 = True

Properties

 should_save = property(should_save, doc=should_save.__doc__)

Detailed Description

Represents a secure cookie.  You can subclass this class and provide
an alternative mac method.  The import thing is that the mac method
is a function with a similar interface to the hashlib.  Required
methods are update() and digest().

Example usage:

>>> x = SecureCookie({"foo": 42, "baz": (1, 2, 3)}, "deadbeef")
>>> x["foo"]
42
>>> x["baz"]
(1, 2, 3)
>>> x["blafasel"] = 23
>>> x.should_save
True

:param data: the initial data.  Either a dict, list of tuples or `None`.
:param secret_key: the secret key.  If not set `None` or not specified
                   it has to be set before :meth:`serialize` is called.
:param new: The initial value of the `new` flag.

Definition at line 121 of file securecookie.py.


Constructor & Destructor Documentation

def MoinMoin.support.werkzeug.contrib.securecookie.SecureCookie.__init__ (   self,
  data = None,
  secret_key = None,
  new = True 
)

Definition at line 157 of file securecookie.py.

00157 
00158     def __init__(self, data=None, secret_key=None, new=True):
00159         ModificationTrackingDict.__init__(self, data or ())
00160         # explicitly convert it into a bytestring because python 2.6
00161         # no longer performs an implicit string conversion on hmac
00162         if secret_key is not None:
00163             secret_key = str(secret_key)
00164         self.secret_key = secret_key
00165         self.new = new


Member Function Documentation

Definition at line 166 of file securecookie.py.

00166 
00167     def __repr__(self):
00168         return '<%s %s%s>' % (
00169             self.__class__.__name__,
00170             dict.__repr__(self),
00171             self.should_save and '*' or ''
00172         )

def MoinMoin.support.werkzeug.contrib.securecookie.SecureCookie.load_cookie (   cls,
  request,
  key = 'session',
  secret_key = None 
)
Loads a :class:`SecureCookie` from a cookie in request.  If the
cookie is not set, a new :class:`SecureCookie` instanced is
returned.

:param request: a request object that has a `cookies` attribute
        which is a dict of all cookie values.
:param key: the name of the cookie.
:param secret_key: the secret key used to unquote the cookie.
           Always provide the value even though it has
           no default!

Definition at line 293 of file securecookie.py.

00293 
00294     def load_cookie(cls, request, key='session', secret_key=None):
00295         """Loads a :class:`SecureCookie` from a cookie in request.  If the
00296         cookie is not set, a new :class:`SecureCookie` instanced is
00297         returned.
00298 
00299         :param request: a request object that has a `cookies` attribute
00300                         which is a dict of all cookie values.
00301         :param key: the name of the cookie.
00302         :param secret_key: the secret key used to unquote the cookie.
00303                            Always provide the value even though it has
00304                            no default!
00305         """
00306         data = request.cookies.get(key)
00307         if not data:
00308             return SecureCookie(secret_key=secret_key)
00309         return SecureCookie.unserialize(data, secret_key)

Here is the call graph for this function:

Quote the value for the cookie.  This can be any object supported
by :attr:`serialization_method`.

:param value: the value to quote.

Definition at line 181 of file securecookie.py.

00181 
00182     def quote(cls, value):
00183         """Quote the value for the cookie.  This can be any object supported
00184         by :attr:`serialization_method`.
00185 
00186         :param value: the value to quote.
00187         """
00188         if cls.serialization_method is not None:
00189             value = cls.serialization_method.dumps(value)
00190         if cls.quote_base64:
00191             value = ''.join(value.encode('base64').splitlines()).strip()
00192         return value

Here is the caller graph for this function:

def MoinMoin.support.werkzeug.contrib.securecookie.SecureCookie.save_cookie (   self,
  response,
  key = 'session',
  expires = None,
  session_expires = None,
  max_age = None,
  path = '/',
  domain = None,
  secure = None,
  httponly = False,
  force = False 
)
Saves the SecureCookie in a cookie on response object.  All
parameters that are not described here are forwarded directly
to :meth:`~BaseResponse.set_cookie`.

:param response: a response object that has a
         :meth:`~BaseResponse.set_cookie` method.
:param key: the name of the cookie.
:param session_expires: the expiration date of the secure cookie
                stored information.  If this is not provided
                the cookie `expires` date is used instead.

Definition at line 312 of file securecookie.py.

00312 
00313                     secure=None, httponly=False, force=False):
00314         """Saves the SecureCookie in a cookie on response object.  All
00315         parameters that are not described here are forwarded directly
00316         to :meth:`~BaseResponse.set_cookie`.
00317 
00318         :param response: a response object that has a
00319                          :meth:`~BaseResponse.set_cookie` method.
00320         :param key: the name of the cookie.
00321         :param session_expires: the expiration date of the secure cookie
00322                                 stored information.  If this is not provided
00323                                 the cookie `expires` date is used instead.
00324         """
00325         if force or self.should_save:
00326             data = self.serialize(session_expires or expires)
00327             response.set_cookie(key, data, expires=expires, max_age=max_age,
00328                                 path=path, domain=domain, secure=secure,
00329                                 httponly=httponly)

Here is the call graph for this function:

Here is the caller graph for this function:

Serialize the secure cookie into a string.

If expires is provided, the session will be automatically invalidated
after expiration when you unseralize it. This provides better
protection against session cookie theft.

:param expires: an optional expiration date for the cookie (a
        :class:`datetime.datetime` object)

Definition at line 212 of file securecookie.py.

00212 
00213     def serialize(self, expires=None):
00214         """Serialize the secure cookie into a string.
00215 
00216         If expires is provided, the session will be automatically invalidated
00217         after expiration when you unseralize it. This provides better
00218         protection against session cookie theft.
00219 
00220         :param expires: an optional expiration date for the cookie (a
00221                         :class:`datetime.datetime` object)
00222         """
00223         if self.secret_key is None:
00224             raise RuntimeError('no secret key defined')
00225         if expires:
00226             self['_expires'] = _date_to_unix(expires)
00227         result = []
00228         mac = hmac(self.secret_key, None, self.hash_method)
00229         for key, value in sorted(self.items()):
00230             result.append('%s=%s' % (
00231                 url_quote_plus(key),
00232                 self.quote(value)
00233             ))
00234             mac.update('|' + result[-1])
00235         return '%s?%s' % (
00236             mac.digest().encode('base64').strip(),
00237             '&'.join(result)
00238         )

Here is the call graph for this function:

Here is the caller graph for this function:

True if the session should be saved.  By default this is only true
for :attr:`modified` cookies, not :attr:`new`.

Definition at line 173 of file securecookie.py.

00173 
00174     def should_save(self):
00175         """True if the session should be saved.  By default this is only true
00176         for :attr:`modified` cookies, not :attr:`new`.
00177         """
        return self.modified

Here is the caller graph for this function:

Unquote the value for the cookie.  If unquoting does not work a
:exc:`UnquoteError` is raised.

:param value: the value to unquote.

Definition at line 194 of file securecookie.py.

00194 
00195     def unquote(cls, value):
00196         """Unquote the value for the cookie.  If unquoting does not work a
00197         :exc:`UnquoteError` is raised.
00198 
00199         :param value: the value to unquote.
00200         """
00201         try:
00202             if cls.quote_base64:
00203                 value = value.decode('base64')
00204             if cls.serialization_method is not None:
00205                 value = cls.serialization_method.loads(value)
00206             return value
00207         except:
00208             # unfortunately pickle and other serialization modules can
00209             # cause pretty every error here.  if we get one we catch it
00210             # and convert it into an UnquoteError
00211             raise UnquoteError()

Load the secure cookie from a serialized string.

:param string: the cookie value to unserialize.
:param secret_key: the secret key used to serialize the cookie.
:return: a new :class:`SecureCookie`.

Definition at line 240 of file securecookie.py.

00240 
00241     def unserialize(cls, string, secret_key):
00242         """Load the secure cookie from a serialized string.
00243 
00244         :param string: the cookie value to unserialize.
00245         :param secret_key: the secret key used to serialize the cookie.
00246         :return: a new :class:`SecureCookie`.
00247         """
00248         if isinstance(string, unicode):
00249             string = string.encode('utf-8', 'ignore')
00250         try:
00251             base64_hash, data = string.split('?', 1)
00252         except (ValueError, IndexError):
00253             items = ()
00254         else:
00255             items = {}
00256             mac = hmac(secret_key, None, cls.hash_method)
00257             for item in data.split('&'):
00258                 mac.update('|' + item)
00259                 if not '=' in item:
00260                     items = None
00261                     break
00262                 key, value = item.split('=', 1)
00263                 # try to make the key a string
00264                 key = url_unquote_plus(key)
00265                 try:
00266                     key = str(key)
00267                 except UnicodeError:
00268                     pass
00269                 items[key] = value
00270 
00271             # no parsing error and the mac looks okay, we can now
00272             # sercurely unpickle our cookie.
00273             try:
00274                 client_hash = base64_hash.decode('base64')
00275             except Exception:
00276                 items = client_hash = None
00277             if items is not None and client_hash == mac.digest():
00278                 try:
00279                     for key, value in items.iteritems():
00280                         items[key] = cls.unquote(value)
00281                 except UnquoteError:
00282                     items = ()
00283                 else:
00284                     if '_expires' in items:
00285                         if time() > items['_expires']:
00286                             items = ()
00287                         else:
00288                             del items['_expires']
00289             else:
00290                 items = ()
00291         return cls(items, secret_key, False)

Here is the call graph for this function:


Member Data Documentation

Definition at line 147 of file securecookie.py.

Definition at line 164 of file securecookie.py.

Definition at line 155 of file securecookie.py.

Definition at line 163 of file securecookie.py.

Definition at line 151 of file securecookie.py.


Property Documentation

Definition at line 178 of file securecookie.py.


The documentation for this class was generated from the following file: