f41f8f35e4beec4e9c67ce84e8fa1fb623b744a9
[audio.git] / src / apiclient / views.py
1 from django.contrib.auth.decorators import login_required
2 from django.urls import reverse
3 from django.http import HttpResponseRedirect, HttpResponse
4 import requests
5 from requests_oauthlib import OAuth1Session
6
7 from apiclient.models import OAuthConnection
8 from apiclient.settings import WL_CONSUMER_KEY, WL_CONSUMER_SECRET
9 from apiclient.settings import WL_REQUEST_TOKEN_URL, WL_ACCESS_TOKEN_URL, WL_AUTHORIZE_URL
10
11
12 @login_required
13 def oauth(request):
14     oauth = OAuth1Session(WL_CONSUMER_KEY, WL_CONSUMER_SECRET)
15     request_token = oauth.fetch_request_token(WL_REQUEST_TOKEN_URL)
16
17     conn = OAuthConnection.get(request.user)
18     conn.access = False
19     conn.token = request_token['oauth_token']
20     conn.token_secret = request_token['oauth_token_secret']
21     conn.save()
22
23     url = oauth.authorization_url(WL_AUTHORIZE_URL)
24     url += '&oauth_callback=' + request.build_absolute_uri(reverse("apiclient_oauth_callback"))
25     return HttpResponseRedirect(url)
26
27
28 @login_required
29 def oauth_callback(request):
30     conn = OAuthConnection.get(request.user)
31     oauth_verifier = request.GET.get('oauth_verifier', 'verifier')
32
33     oauth = OAuth1Session(
34         WL_CONSUMER_KEY, WL_CONSUMER_SECRET,
35                           conn.token, conn.token_secret,
36                           verifier=oauth_verifier)
37     access_token = oauth.fetch_access_token(WL_ACCESS_TOKEN_URL)
38
39     conn.access = True
40     conn.token = access_token['oauth_token']
41     conn.token_secret = access_token['oauth_token_secret']
42     conn.save()
43
44     return HttpResponseRedirect('/')