1.1 --- a/imipweb/resource.py Sat Apr 23 00:41:58 2016 +0200
1.2 +++ b/imipweb/resource.py Fri May 06 23:06:35 2016 +0200
1.3 @@ -29,8 +29,10 @@
1.4 from imipweb.env import CGIEnvironment
1.5 from urllib import urlencode
1.6 import babel.dates
1.7 +import hashlib, hmac
1.8 import markup
1.9 import pytz
1.10 +import time
1.11
1.12 class Resource:
1.13
1.14 @@ -224,6 +226,42 @@
1.15
1.16 "Utility methods resource mix-in."
1.17
1.18 + def get_validation_token(self, details=None):
1.19 +
1.20 + "Return a token suitable for validating a form submission."
1.21 +
1.22 + # Use a secret held in the user's preferences.
1.23 +
1.24 + prefs = self.get_preferences()
1.25 + if not prefs.has_key("secret"):
1.26 + prefs["secret"] = str(time.time())
1.27 +
1.28 + # Combine it with the user identity and any supplied details.
1.29 +
1.30 + secret = prefs["secret"].encode("utf-8")
1.31 + details = u"".join([self.env.get_user()] + (details or [])).encode("utf-8")
1.32 +
1.33 + return hmac.new(secret, details, hashlib.sha256).hexdigest()
1.34 +
1.35 + def check_validation_token(self, name="token", details=None):
1.36 +
1.37 + """
1.38 + Check the field having the given 'name', returning if its value matches
1.39 + the validation token generated using any given 'details'.
1.40 + """
1.41 +
1.42 + return self.env.get_args().get(name, [None])[0] == self.get_validation_token(details)
1.43 +
1.44 + def validator(self, name="token", details=None):
1.45 +
1.46 + """
1.47 + Show a control having the given 'name' that is used to validate form
1.48 + submissions, employing any additional 'details' in the construction of
1.49 + the validation token.
1.50 + """
1.51 +
1.52 + self.page.input(name=name, type="hidden", value=self.get_validation_token(details))
1.53 +
1.54 def prefixed_args(self, prefix, convert=None):
1.55
1.56 """