Explorar el Código

clean up OAuth token logic

Mohammed Khan hace 1 año
padre
commit
8e163a0e8c
Se han modificado 3 ficheros con 25 adiciones y 41 borrados
  1. 8 19
      backend/main/views.py
  2. 17 5
      backend/users/models.py
  3. 0 17
      backend/users/views.py

+ 8 - 19
backend/main/views.py

@@ -17,9 +17,6 @@ from .util import *
 @login_required
 def home(request):
     user_profile = request.user
-    watching = user_profile.playlists.filter(Q(marked_as="watching") & Q(is_in_db=True)).order_by("-num_of_accesses")
-    recently_accessed_playlists = user_profile.playlists.filter(is_in_db=True).order_by("-updated_at")[:6]
-    recently_added_playlists = user_profile.playlists.filter(is_in_db=True).order_by("-created_at")[:6]
 
     #### FOR NEWLY JOINED USERS ######
     channel_found = True
@@ -32,32 +29,24 @@ def home(request):
         
         show_import_page is only set false in the import_in_progress.html page, i.e when user cancels YT import
         """
-        # user_profile.show_import_page = False
-        if user_profile.profile.access_token.strip() == "" or user_profile.profile.refresh_token.strip() == "":
-            user_social_token = SocialToken.objects.get(account__user=request.user)
-            user_profile.profile.access_token = user_social_token.token
-            user_profile.profile.refresh_token = user_social_token.token_secret
-            user_profile.profile.expires_at = user_social_token.expires_at
-            user_profile.save()
-            Playlist.objects.getUserYTChannelID(request.user)
-
+        # after user imports all their YT playlists no need to show_import_page again
         if user_profile.profile.imported_yt_playlists:
-            user_profile.profile.show_import_page = False  # after user imports all their YT playlists no need to show_import_page again
+            user_profile.profile.show_import_page = False
             user_profile.profile.save(update_fields=['show_import_page'])
             imported_playlists_count = request.user.playlists.filter(Q(is_user_owned=True) & Q(is_in_db=True)).exclude(
                 playlist_id="LL").count()
-            return render(request, "home.html",
-                          {"import_successful": True, "imported_playlists_count": imported_playlists_count})
+            return render(request, "home.html", {"import_successful": True, "imported_playlists_count": imported_playlists_count})
 
+        Playlist.objects.getUserYTChannelID(request.user)
         return render(request, "import_in_progress.html")
     ##################################
 
+    watching = user_profile.playlists.filter(Q(marked_as="watching") & Q(is_in_db=True)).order_by("-num_of_accesses")
+    recently_accessed_playlists = user_profile.playlists.filter(is_in_db=True).order_by("-updated_at")[:6]
+    recently_added_playlists = user_profile.playlists.filter(is_in_db=True).order_by("-created_at")[:6]
     playlist_tags = request.user.playlist_tags.filter(times_viewed_per_week__gte=1).order_by('-times_viewed_per_week')
-
     videos = request.user.videos.filter(Q(is_unavailable_on_yt=False) & Q(was_deleted_on_yt=False))
-
-    channels = videos.values(
-        'channel_name').annotate(channel_videos_count=Count('video_id'))
+    channels = videos.values('channel_name').annotate(channel_videos_count=Count('video_id'))
 
     return render(request, 'home.html', {"channel_found": channel_found,
                                          "playlist_tags": playlist_tags,

+ 17 - 5
backend/users/models.py

@@ -3,11 +3,12 @@ from django.contrib.auth.models import User
 from django.db.models import Count, Q
 from django.db.models.signals import post_save
 from django.dispatch import receiver
-from allauth.socialaccount.models import SocialApp
+from allauth.socialaccount.models import SocialToken
 from google.oauth2.credentials import Credentials
 from google.auth.transport.requests import Request
+from django.conf import settings
+
 
-# Create your models here.
 class Untube(models.Model):
     page_likes = models.IntegerField(default=0)
 
@@ -60,13 +61,24 @@ class Profile(models.Model):
         return f"{self.untube_user.username} ({self.untube_user.email})"
 
     def get_credentials(self):
-        app = SocialApp.objects.get(provider='google')
+        """
+        Returns Google OAuth credentials object by using user's OAuth token
+        """
+        # if the profile model does not hold the tokens, retrieve them from user's SocialToken entry and save them into profile
+        if self.access_token.strip() == "" or self.refresh_token.strip() == "":
+            user_social_token = SocialToken.objects.get(account__user=self.untube_user)
+            self.access_token = user_social_token.token
+            self.refresh_token = user_social_token.token_secret
+            self.expires_at = user_social_token.expires_at
+            self.save(update_fields=['access_token', 'refresh_token', 'expires_at'])
+
+        # app = SocialApp.objects.get(provider='google')
         credentials = Credentials(
             token=self.access_token,
             refresh_token=self.refresh_token,
             token_uri="https://oauth2.googleapis.com/token",
-            client_id=app.client_id,
-            client_secret=app.secret,
+            client_id=settings.GOOGLE_OAUTH_CLIENT_ID,  # app.client_id,
+            client_secret=settings.GOOGLE_OAUTH_CLIENT_SECRET,  # app.secret,
             scopes=['https://www.googleapis.com/auth/youtube']
         )
 

+ 0 - 17
backend/users/views.py

@@ -170,15 +170,6 @@ def log_out(request):
 
 def cancel_import(request):
     user_profile = request.user.profile
-
-    if user_profile.access_token.strip() == "" or user_profile.refresh_token.strip() == "":
-        user_social_token = SocialToken.objects.get(account__user=request.user)
-        user_profile.access_token = user_social_token.token
-        user_profile.refresh_token = user_social_token.token_secret
-        user_profile.expires_at = user_social_token.expires_at
-
-        # request.user.save()
-
     user_profile.imported_yt_playlists = False
     user_profile.show_import_page = False
     user_profile.save()
@@ -203,14 +194,6 @@ def start_import(request):
     """
     user_profile = request.user.profile
 
-    if user_profile.access_token.strip() == "" or user_profile.refresh_token.strip() == "":
-        user_social_token = SocialToken.objects.get(account__user=request.user)
-        user_profile.access_token = user_social_token.token
-        user_profile.refresh_token = user_social_token.token_secret
-        user_profile.expires_at = user_social_token.expires_at
-
-        request.user.save()
-
     result = Playlist.objects.initializePlaylist(request.user)
     if result["status"] == -1:
         print("User has no YT channel")