From 162a4fdce512e86d64436bb38d4128993f322138 Mon Sep 17 00:00:00 2001 From: Marian Sigler Date: Fri, 21 Sep 2012 04:12:12 +0200 Subject: add functions to create confirmation links --- utils.py | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) (limited to 'utils.py') diff --git a/utils.py b/utils.py index c6737b8..bdb7f18 100644 --- a/utils.py +++ b/utils.py @@ -1,10 +1,13 @@ # -*- coding: utf-8 -*- +import hmac import ldap +import pickle import re +from Crypto.Cipher import AES from functools import wraps from flask import flash, g, redirect, render_template, request, session, url_for +from hashlib import sha1 from random import randint -from Crypto.Cipher import AES from werkzeug.exceptions import Forbidden @@ -82,6 +85,38 @@ def decrypt_password(ciphertext): return encryptor.decrypt(ciphertext[16:]).rstrip('\0') +def create_confirmation(realm, data): + """ + Create a confirmation token e.g. for confirmation mails. + + Expects as input a realm to distinguish data for several applications and + some data (pickle-able). + """ + key = '\0'.join((app.config['SECRET_KEY'], realm)) + payload = pickle.dumps(data) + mac = hmac.new(key, payload, sha1) + return ''.join((mac.digest(), payload)).encode('base64').strip() + +class InvalidConfirmation(ValueError): + """Raised by `verify_confirmation` on invalid input data""" + +def verify_confirmation(realm, token): + """ + Verify a confirmation created by `create_confirmation` and, if it is + valid, return the original data. + """ + key = '\0'.join((app.config['SECRET_KEY'], realm)) + + token = token.decode('base64') + mac = token[:20] + payload = token[20:] + + if mac != hmac.new(key, payload, sha1).digest(): + raise InvalidConfirmation('MAC does not match') + + return pickle.loads(payload) + + # circular import from app import app -- cgit v1.2.3-1-g7c22