simplify piston authorize form
[wolnelektury.git] / src / api / piston_patch.py
1 # -*- coding: utf-8 -*-
2
3 # modified from django-piston
4 import base64
5 import hmac
6
7 from django import forms
8 from django.conf import settings
9 from django.contrib.auth.decorators import login_required
10 from django.core.urlresolvers import get_callable
11 from django.http import HttpResponseRedirect, HttpResponse
12 from django.shortcuts import render_to_response
13 from django.template.context import RequestContext
14 from piston import oauth
15 from piston.authentication import initialize_server_request, INVALID_PARAMS_RESPONSE, send_oauth_error
16
17
18 class OAuthAuthenticationForm(forms.Form):
19     oauth_token = forms.CharField(widget=forms.HiddenInput)
20     oauth_callback = forms.CharField(widget=forms.HiddenInput)  # changed from URLField - too strict
21     # removed authorize_access - redundant
22     csrf_signature = forms.CharField(widget=forms.HiddenInput)
23
24     def __init__(self, *args, **kwargs):
25         forms.Form.__init__(self, *args, **kwargs)
26
27         self.fields['csrf_signature'].initial = self.initial_csrf_signature
28
29     def clean_csrf_signature(self):
30         sig = self.cleaned_data['csrf_signature']
31         token = self.cleaned_data['oauth_token']
32
33         sig1 = OAuthAuthenticationForm.get_csrf_signature(settings.SECRET_KEY, token)
34
35         if sig != sig1:
36             raise forms.ValidationError("CSRF signature is not valid")
37
38         return sig
39
40     def initial_csrf_signature(self):
41         token = self.initial['oauth_token']
42         return OAuthAuthenticationForm.get_csrf_signature(settings.SECRET_KEY, token)
43
44     @staticmethod
45     def get_csrf_signature(key, token):
46         # Check signature...
47         import hashlib  # 2.5
48         hashed = hmac.new(key, token, hashlib.sha1)
49
50         # calculate the digest base 64
51         return base64.b64encode(hashed.digest())
52
53
54 # The only thing changed in the views below is the form used
55
56
57 def oauth_auth_view(request, token, callback, params):
58     form = OAuthAuthenticationForm(initial={
59         'oauth_token': token.key,
60         'oauth_callback': callback,
61     })
62
63     return render_to_response('piston/authorize_token.html',
64                               {'form': form}, RequestContext(request))
65
66
67 @login_required
68 def oauth_user_auth(request):
69     oauth_server, oauth_request = initialize_server_request(request)
70
71     if oauth_request is None:
72         return INVALID_PARAMS_RESPONSE
73
74     try:
75         token = oauth_server.fetch_request_token(oauth_request)
76     except oauth.OAuthError, err:
77         return send_oauth_error(err)
78
79     try:
80         callback = oauth_server.get_callback(oauth_request)
81     except:
82         callback = None
83
84     if request.method == "GET":
85         params = oauth_request.get_normalized_parameters()
86
87         oauth_view = getattr(settings, 'OAUTH_AUTH_VIEW', None)
88         if oauth_view is None:
89             return oauth_auth_view(request, token, callback, params)
90         else:
91             return get_callable(oauth_view)(request, token, callback, params)
92     elif request.method == "POST":
93         try:
94             form = OAuthAuthenticationForm(request.POST)
95             if form.is_valid():
96                 token = oauth_server.authorize_token(token, request.user)
97                 args = '?' + token.to_string(only_key=True)
98             else:
99                 args = '?error=%s' % 'Access not granted by user.'
100
101             if not callback:
102                 callback = getattr(settings, 'OAUTH_CALLBACK_VIEW')
103                 return get_callable(callback)(request, token)
104
105             response = HttpResponseRedirect(callback + args)
106
107         except oauth.OAuthError, err:
108             response = send_oauth_error(err)
109     else:
110         response = HttpResponse('Action not allowed.')
111
112     return response