351dd2e0cba5530239f4e0169f537feed61851cb
[audio.git] / src / 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 requests
7 from requests_oauthlib import OAuth1Session
8
9 from apiclient.models import OAuthConnection
10 from apiclient.settings import WL_CONSUMER_KEY, WL_CONSUMER_SECRET
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     oauth = OAuth1Session(WL_CONSUMER_KEY, WL_CONSUMER_SECRET)
17     request_token = oauth.fetch_request_token(WL_REQUEST_TOKEN_URL)
18
19     conn = OAuthConnection.get(request.user)
20     conn.access = False
21     conn.token = request_token['oauth_token']
22     conn.token_secret = request_token['oauth_token_secret']
23     conn.save()
24
25     url = oauth.authorization_url(WL_AUTHORIZE_URL)
26     url += '&oauth_callback=' + request.build_absolute_uri(reverse("apiclient_oauth_callback"))
27     return HttpResponseRedirect(url)
28
29
30 @login_required
31 def oauth_callback(request):
32     conn = OAuthConnection.get(request.user)
33     oauth_verifier = request.GET.get('oauth_verifier', 'verifier')
34
35     oauth = OAuth1Session(
36         WL_CONSUMER_KEY, WL_CONSUMER_SECRET,
37                           conn.token, conn.token_secret,
38                           verifier=oauth_verifier)
39     access_token = oauth.fetch_access_token(WL_ACCESS_TOKEN_URL)
40
41     conn.access = True
42     conn.token = access_token['oauth_token']
43     conn.token_secret = access_token['oauth_token_secret']
44     conn.save()
45
46     return HttpResponseRedirect('/')