|
| 1 | +from urllib.parse import urlencode |
| 2 | + |
| 3 | +import requests |
| 4 | +from django.conf import settings |
1 | 5 | from django.contrib.auth.models import User |
| 6 | +from django.shortcuts import redirect |
2 | 7 | from rest_framework import generics, status |
| 8 | +from rest_framework.permissions import AllowAny |
3 | 9 | from rest_framework.response import Response |
| 10 | +from rest_framework.views import APIView |
4 | 11 | from rest_framework_simplejwt.tokens import RefreshToken |
5 | 12 |
|
6 | 13 | from .models import UserProfile |
@@ -62,3 +69,59 @@ def create(self, request, *args, **kwags): |
62 | 69 | }, |
63 | 70 | status=status.HTTP_200_OK, |
64 | 71 | ) |
| 72 | + |
| 73 | + |
| 74 | +""" |
| 75 | +class GoogleLogin(SocialLoginView): |
| 76 | + adapter_class = GoogleOAuth2Adapter |
| 77 | + client_class = OAuth2Client |
| 78 | + callback_url = "http://127.0.0.1:8000/accounts/google/login/callback/" |
| 79 | +""" |
| 80 | + |
| 81 | + |
| 82 | +class OAuthLoginView(APIView): |
| 83 | + permission_classes = [AllowAny] |
| 84 | + |
| 85 | + def get(self, request, provider): |
| 86 | + if provider != "google": |
| 87 | + return Response({"error": "Unsupported provider"}, status=400) |
| 88 | + params = { |
| 89 | + "client_id": settings.GOOGLE_CLIENT_ID, |
| 90 | + "redirect_uri": settings.GOOGLE_REDIRECT_URI, |
| 91 | + "response_type": "code", |
| 92 | + "scope": "openid email profile", |
| 93 | + "access_type": "offline", |
| 94 | + } |
| 95 | + google_url = "https://accounts.google.com/o/oauth2/v2/auth?" + urlencode(params) |
| 96 | + return redirect(google_url) |
| 97 | + |
| 98 | + |
| 99 | +class OAuthCallbackView(APIView): |
| 100 | + permission_classes = [AllowAny] |
| 101 | + |
| 102 | + def get(self, request, provider): |
| 103 | + if provider != "google": |
| 104 | + return Response({"error": "Unsupported provider"}, status=400) |
| 105 | + code = request.GET.get("code") |
| 106 | + if not code: |
| 107 | + return Response({"error": "Authorization code missing"}, status=400) |
| 108 | + token_response = requests.post( |
| 109 | + "https://oauth2.googleapis.com/token", |
| 110 | + data={ |
| 111 | + "code": code, |
| 112 | + "client_id": settings.GOOGLE_CLIENT_ID, |
| 113 | + "client_secret": settings.GOOGLE_CLIENT_SECRET, |
| 114 | + "redirect_uri": settings.GOOGLE_REDIRECT_URI, |
| 115 | + "grant_type": "authorization_code", |
| 116 | + }, |
| 117 | + ) |
| 118 | + token_data = token_response.json() |
| 119 | + access_token = token_data.get("access_token") |
| 120 | + if not access_token: |
| 121 | + return Response({"error": "Failed to get access_token"}, status=400) |
| 122 | + user_response = requests.get( |
| 123 | + "https://www.googleapis.com/oauth2/v2/userinfo", |
| 124 | + headers={"Authorization": f"Bearer {access_token}"}, |
| 125 | + ) |
| 126 | + user_data = user_response.json() |
| 127 | + return Response(user_data) |
0 commit comments