2 from django.contrib.auth.decorators import login_required
3 from django.urls import reverse
4 from django.http import HttpResponseRedirect, HttpResponse
6 from requests_oauthlib import OAuth1Session, OAuth2Session
8 from apiclient.models import OAuthConnection, YouTubeToken
9 from apiclient.settings import WL_CONSUMER_KEY, WL_CONSUMER_SECRET
10 from apiclient.settings import WL_REQUEST_TOKEN_URL, WL_ACCESS_TOKEN_URL, WL_AUTHORIZE_URL, YOUTUBE_AUTH_URL, YOUTUBE_TOKEN_URL, YOUTUBE_CLIENT_ID, YOUTUBE_CLIENT_SECRET, YOUTUBE_SCOPE
15 oauth = OAuth1Session(WL_CONSUMER_KEY, WL_CONSUMER_SECRET)
16 request_token = oauth.fetch_request_token(WL_REQUEST_TOKEN_URL)
18 conn = OAuthConnection.get(request.user)
20 conn.token = request_token['oauth_token']
21 conn.token_secret = request_token['oauth_token_secret']
24 url = oauth.authorization_url(WL_AUTHORIZE_URL)
25 url += '&oauth_callback=' + request.build_absolute_uri(reverse("apiclient_oauth_callback"))
26 return HttpResponseRedirect(url)
30 def oauth_callback(request):
31 conn = OAuthConnection.get(request.user)
32 oauth_verifier = request.GET.get('oauth_verifier', 'verifier')
34 oauth = OAuth1Session(
35 WL_CONSUMER_KEY, WL_CONSUMER_SECRET,
36 conn.token, conn.token_secret,
37 verifier=oauth_verifier)
38 access_token = oauth.fetch_access_token(WL_ACCESS_TOKEN_URL)
41 conn.token = access_token['oauth_token']
42 conn.token_secret = access_token['oauth_token_secret']
45 return HttpResponseRedirect('/')
50 redirect_uri = request.build_absolute_uri(reverse("apiclient_oauth2_redirect"))
51 oauth = OAuth2Session(YOUTUBE_CLIENT_ID, redirect_uri=redirect_uri, scope=YOUTUBE_SCOPE)
52 authorization_url, state = oauth.authorization_url(YOUTUBE_AUTH_URL)
53 return HttpResponseRedirect(authorization_url)
57 def oauth2_redirect(request):
58 redirect_uri = request.build_absolute_uri(reverse("apiclient_oauth2_redirect"))
59 oauth = OAuth2Session(YOUTUBE_CLIENT_ID, redirect_uri=redirect_uri, scope=YOUTUBE_SCOPE)
60 token = oauth.fetch_token(
62 authorization_response=request.get_full_path(),
63 client_secret=YOUTUBE_CLIENT_SECRET,
65 YouTubeToken.objects.all().delete()
66 YouTubeToken.objects.create(token=json.dumps(token))
67 return HttpResponseRedirect('/')