attachment list for links + bad links in red
[redakcja.git] / apps / apiclient / views.py
1 # -*- coding: utf-8 -*-
2 import urlparse
3
4 from django.contrib.auth.decorators import login_required
5 from django.core.urlresolvers import reverse
6 from django.http import HttpResponseRedirect, HttpResponse
7 import oauth2
8
9 from apiclient.models import OAuthConnection
10 from apiclient import wl_consumer
11 from apiclient.settings import (WL_REQUEST_TOKEN_URL, WL_ACCESS_TOKEN_URL, 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(urlparse.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(urlparse.parse_qsl(content))
54
55     if 'oauth_token' in access_token:
56         conn.access = True
57         conn.token = access_token['oauth_token']
58         conn.token_secret = access_token['oauth_token_secret']
59         conn.save()
60     else:
61         return HttpResponse(request.GET.get('error'))
62
63     return HttpResponseRedirect('/')