editor update: aside.gap in ui, aside.gap styling
[redakcja.git] / apps / apiclient / views.py
1 import cgi
2
3 from django.contrib.auth.decorators import login_required
4 from django.core.urlresolvers import reverse
5 from django.http import HttpResponseRedirect, HttpResponse
6 import oauth2
7
8 from apiclient.models import OAuthConnection
9 from apiclient import wl_consumer
10 from apiclient.settings import (WL_REQUEST_TOKEN_URL, WL_ACCESS_TOKEN_URL, 
11         WL_AUTHORIZE_URL)
12
13
14 @login_required
15 def oauth(request):
16     if wl_consumer is None:
17         return HttpResponse("OAuth consumer not configured.")
18
19     client = oauth2.Client(wl_consumer)
20     resp, content = client.request(WL_REQUEST_TOKEN_URL)
21     if resp['status'] != '200':
22         raise Exception("Invalid response %s." % resp['status'])
23
24     request_token = dict(cgi.parse_qsl(content))
25     
26     conn = OAuthConnection.get(request.user)
27     # this might reset existing auth!
28     conn.access = False
29     conn.token = request_token['oauth_token']
30     conn.token_secret = request_token['oauth_token_secret']
31     conn.save()
32
33     url = "%s?oauth_token=%s&oauth_callback=%s" % (
34             WL_AUTHORIZE_URL, 
35             request_token['oauth_token'],
36             request.build_absolute_uri(reverse("apiclient_oauth_callback")),
37             )
38
39     return HttpResponseRedirect(url)
40
41
42 @login_required
43 def oauth_callback(request):
44     if wl_consumer is None:
45         return HttpResponse("OAuth consumer not configured.")
46
47     oauth_verifier = request.GET.get('oauth_verifier')
48     conn = OAuthConnection.get(request.user)
49     token = oauth2.Token(conn.token, conn.token_secret)
50     token.set_verifier(oauth_verifier)
51     client = oauth2.Client(wl_consumer, token)
52     resp, content = client.request(WL_ACCESS_TOKEN_URL, method="POST")
53     access_token = dict(cgi.parse_qsl(content))
54
55     conn.access = True
56     conn.token = access_token['oauth_token']
57     conn.token_secret = access_token['oauth_token_secret']
58     conn.save()
59
60     return HttpResponseRedirect('/')