Skip to content

Commit

Permalink
* Added signed_cookie method to WebOb Request/Response sub-classes.
Browse files Browse the repository at this point in the history
--HG--
branch : trunk
  • Loading branch information
bbangert committed Mar 9, 2008
1 parent b5ac9f3 commit 7fe20fb
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG
Expand Up @@ -2,6 +2,7 @@ Pylons Changelog
=================

0.9.7 (**tip**)
* Added signed_cookie method to WebOb Request/Response sub-classes.
* Updated project template to setup appropriate template loader and controller
template to doc how to import render.
* Added documentation for render functions in pylons.templating.
Expand Down
43 changes: 43 additions & 0 deletions pylons/controllers/util.py
Expand Up @@ -2,10 +2,18 @@
``etag_cache``, ``redirect_to``, and ``abort``.
"""
import base64
import hmac
import logging
import mimetypes
import sha
import warnings

try:
import cPickle as pickle
except ImportError:
import pickle

import paste.httpexceptions as httpexceptions
from routes import url_for
from webob import Request as WebObRequest
Expand Down Expand Up @@ -39,6 +47,28 @@ def languages(self):

def match_accept(self, mimetypes):
return self.accept.first_match(mimetypes)

def signed_cookie(self, name, secret):
"""Extract a signed cookie of ``name`` from the request
The cookie is expected to have been created with
``Response.signed_cookie``, and the ``secret`` should be the
same as the one used to sign it.
"""
cookie = self.str_cookies.get(name)
if not cookie:
return None
try:
encoded_data = base64.decodestring(cookie)
except:
# Badly formed data can make base64 die
return None
sig, pickled = encoded_data[:40], encoded_data[40:]
if hmac.new(secret, pickled, sha).hexdigest() == sig:
return pickle.loads(pickled)
else:
return None


class Response(WebObResponse):
Expand Down Expand Up @@ -67,6 +97,19 @@ def write(self, content):

def wsgi_response(self):
return self.status, self.headers, self.body

def signed_cookie(self, name, data, secret=None, **kwargs):
"""Save a signed cookie with ``secret`` signature
Saves a signed cookie of the pickled data. All other keyword
arguments that ``WebOb.set_cookie`` accepts are usable and
passed to the WebOb set_cookie method after creating the signed
cookie value.
"""
pickled = pickle.dumps(data, pickle.HIGHEST_PROTOCOL)
sig = hmac.new(secret, pickled, sha).hexdigest()
self.set_cookie(name, base64.encodestring(sig + pickled), **kwargs)


class MIMETypes(object):
Expand Down

0 comments on commit 7fe20fb

Please sign in to comment.