Standardize CAS view names for django_cas_ng.
[audio.git] / src / apiclient / views.py
index f41f8f3..25fd5c6 100644 (file)
@@ -1,12 +1,13 @@
+import json
 from django.contrib.auth.decorators import login_required
 from django.urls import reverse
 from django.http import HttpResponseRedirect, HttpResponse
 import requests
 from django.contrib.auth.decorators import login_required
 from django.urls import reverse
 from django.http import HttpResponseRedirect, HttpResponse
 import requests
-from requests_oauthlib import OAuth1Session
+from requests_oauthlib import OAuth1Session, OAuth2Session
 
 
-from apiclient.models import OAuthConnection
+from apiclient.models import OAuthConnection, YouTubeToken
 from apiclient.settings import WL_CONSUMER_KEY, WL_CONSUMER_SECRET
 from apiclient.settings import WL_CONSUMER_KEY, WL_CONSUMER_SECRET
-from apiclient.settings import WL_REQUEST_TOKEN_URL, WL_ACCESS_TOKEN_URL, WL_AUTHORIZE_URL
+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
 
 
 @login_required
 
 
 @login_required
@@ -42,3 +43,25 @@ def oauth_callback(request):
     conn.save()
 
     return HttpResponseRedirect('/')
     conn.save()
 
     return HttpResponseRedirect('/')
+
+
+@login_required
+def oauth2(request):
+    redirect_uri = request.build_absolute_uri(reverse("apiclient_oauth2_redirect"))
+    oauth = OAuth2Session(YOUTUBE_CLIENT_ID, redirect_uri=redirect_uri, scope=YOUTUBE_SCOPE)
+    authorization_url, state = oauth.authorization_url(YOUTUBE_AUTH_URL)
+    return HttpResponseRedirect(authorization_url)
+
+
+@login_required
+def oauth2_redirect(request):
+    redirect_uri = request.build_absolute_uri(reverse("apiclient_oauth2_redirect"))
+    oauth = OAuth2Session(YOUTUBE_CLIENT_ID, redirect_uri=redirect_uri, scope=YOUTUBE_SCOPE)
+    token = oauth.fetch_token(
+            YOUTUBE_TOKEN_URL,
+            authorization_response=request.get_full_path(),
+            client_secret=YOUTUBE_CLIENT_SECRET,
+        )
+    YouTubeToken.objects.all().delete()
+    YouTubeToken.objects.create(token=json.dumps(token))
+    return HttpResponseRedirect('/')