dodge adblock
[wolnelektury.git] / apps / piston / forms.py
1 import hmac, base64
2
3 from django import forms
4 from django.conf import settings
5
6 class Form(forms.Form):
7     pass
8
9 class ModelForm(forms.ModelForm):
10     """
11     Subclass of `forms.ModelForm` which makes sure
12     that the initial values are present in the form
13     data, so you don't have to send all old values
14     for the form to actually validate. Django does not
15     do this on its own, which is really annoying.
16     """
17     def merge_from_initial(self):
18         self.data._mutable = True
19         filt = lambda v: v not in self.data.keys()
20         for field in filter(filt, getattr(self.Meta, 'fields', ())):
21             self.data[field] = self.initial.get(field, None)
22
23
24 class OAuthAuthenticationForm(forms.Form):
25     oauth_token = forms.CharField(widget=forms.HiddenInput)
26     oauth_callback = forms.CharField(widget=forms.HiddenInput, required=False)
27     authorize_access = forms.BooleanField(required=True)
28     csrf_signature = forms.CharField(widget=forms.HiddenInput)
29
30     def __init__(self, *args, **kwargs):
31         forms.Form.__init__(self, *args, **kwargs)
32
33         self.fields['csrf_signature'].initial = self.initial_csrf_signature
34
35     def clean_csrf_signature(self):
36         sig = self.cleaned_data['csrf_signature']
37         token = self.cleaned_data['oauth_token']
38
39         sig1 = OAuthAuthenticationForm.get_csrf_signature(settings.SECRET_KEY, token)
40
41         if sig != sig1:
42             raise forms.ValidationError("CSRF signature is not valid")
43
44         return sig
45
46     def initial_csrf_signature(self):
47         token = self.initial['oauth_token']
48         return OAuthAuthenticationForm.get_csrf_signature(settings.SECRET_KEY, token)
49
50     @staticmethod
51     def get_csrf_signature(key, token):
52         # Check signature...
53         try:
54             import hashlib # 2.5
55             hashed = hmac.new(key, token, hashlib.sha1)
56         except:
57             import sha # deprecated
58             hashed = hmac.new(key, token, sha)
59
60         # calculate the digest base 64
61         return base64.b64encode(hashed.digest())
62