Skip to content

Commit

Permalink
save google user id
Browse files Browse the repository at this point in the history
  • Loading branch information
jefer94 committed Sep 28, 2024
1 parent 5af35df commit 28cd411
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 41 deletions.
1 change: 1 addition & 0 deletions breathecode/authenticate/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,7 @@ class CredentialsGoogle(models.Model):
token = models.CharField(max_length=255)
refresh_token = models.CharField(max_length=255)
id_token = models.CharField(max_length=1152, default="")
google_id = models.CharField(max_length=24, default="")
expires_at = models.DateTimeField()

user = models.OneToOneField(User, on_delete=models.CASCADE)
Expand Down
8 changes: 8 additions & 0 deletions breathecode/authenticate/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
from breathecode.mentorship.models import MentorProfile
from breathecode.mentorship.serializers import GETMentorSmallSerializer
from breathecode.notify.models import SlackTeam
from breathecode.services.google_apps.google_apps import GoogleApps
from breathecode.services.google_cloud import FunctionV1, FunctionV2
from breathecode.utils import GenerateLookupsMixin, HeaderLimitOffsetPagination, capable_of
from breathecode.utils.api_view_extensions.api_view_extensions import APIViewExtensions
Expand Down Expand Up @@ -2119,16 +2120,23 @@ async def save_google_token(request):
print("body123123123123")
print(body)

c = GoogleApps(body["id_token"], refresh)
user_info = await c.get_user_info()

google_credentials, created = await CredentialsGoogle.objects.aget_or_create(
user=user,
defaults={
"expires_at": timezone.now() + timedelta(seconds=body["expires_in"]),
"token": body["access_token"],
"refresh_token": refresh,
"id_token": body["id_token"],
"google_id": user_info["id"],
},
)
if created is False:
google_credentials.token = body["access_token"]
google_credentials.id_token = body["id_token"]
google_credentials.google_id = user_info["id"]
if refresh:
google_credentials.refresh_token = refresh

Expand Down
87 changes: 46 additions & 41 deletions breathecode/services/google_apps/google_apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,45 @@
class GoogleApps:
"""Wrapper for each endpoint that a multibillionaire company can't develop"""

def __init__(self, token: str, refresh_token: Optional[str] = None):
self._credentials = self._get_credentials(token, refresh_token)
def __init__(self, id_token: str, refresh_token: Optional[str] = None):
self._credentials = self._get_credentials(id_token, refresh_token)

# def _get_credentials(
# self, token: Optional[str] = None, refresh_token: Optional[str] = None
# ) -> Optional[Credentials]:
# creds = None

# if token:
# creds = Credentials(
# token=token,
# refresh_token=refresh_token,
# token_uri="https://oauth2.googleapis.com/token",
# client_id=os.getenv("GOOGLE_CLIENT_ID"),
# client_secret=os.getenv("GOOGLE_SECRET"),
# )
# logger.info("Credentials created with token and refresh_token.")
# if creds.expired and creds.refresh_token:
# try:
# creds.refresh(Request())
# logger.info("Credentials refreshed.")
# except Exception as e:
# logger.error(f"Failed to refresh credentials: {e}")
# elif os.path.exists(TOKEN_FILE_NAME):
# with open(TOKEN_FILE_NAME, "rb") as f:
# creds = pickle.load(f)
# logger.info("Credentials loaded from token file.")
# if creds and creds.expired and creds.refresh_token:
# try:
# creds.refresh(Request())
# logger.info("Credentials refreshed from token file.")
# except Exception as e:
# logger.error(f"Failed to refresh credentials from token file: {e}")

# # If there are no valid credentials available, raise an exception
# if not creds or not creds.valid:
# raise Exception("Invalid or expired credentials. Please provide a valid token.")

# return creds

def _get_credentials(
self, token: Optional[str] = None, refresh_token: Optional[str] = None
Expand All @@ -36,53 +73,21 @@ def _get_credentials(
client_id=os.getenv("GOOGLE_CLIENT_ID"),
client_secret=os.getenv("GOOGLE_SECRET"),
)
logger.info("Credentials created with token and refresh_token.")
if creds.expired and creds.refresh_token:
try:
creds.refresh(Request())
logger.info("Credentials refreshed.")
except Exception as e:
logger.error(f"Failed to refresh credentials: {e}")
creds.refresh(Request())
elif os.path.exists(TOKEN_FILE_NAME):
with open(TOKEN_FILE_NAME, "rb") as f:
creds = pickle.load(f)
logger.info("Credentials loaded from token file.")
if creds and creds.expired and creds.refresh_token:
try:
creds.refresh(Request())
logger.info("Credentials refreshed from token file.")
except Exception as e:
logger.error(f"Failed to refresh credentials from token file: {e}")
creds.refresh(Request())

# If there are no valid credentials available, raise an exception
if not creds or not creds.valid:
raise Exception("Invalid or expired credentials. Please provide a valid token.")
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
raise Exception("Invalid or expired credentials. Please provide a valid token.")

return creds

async def get_user_info(self):
if not self._credentials.valid:
raise Exception("Invalid or expired credentials. Please provide a valid token.")

logger.info(f"Access Token: {self._credentials.token}")
logger.info(f"Token Expiry: {self._credentials.expiry}")
logger.info(f"Refresh Token: {self._credentials.refresh_token}")

# Check if the token is expired or about to expire and refresh if necessary
if self._credentials.expired or not self._credentials.token:
try:
self._credentials.refresh(Request())
logger.info("Credentials refreshed before making API call.")
except Exception as e:
logger.error(f"Failed to refresh credentials before making API call: {e}")
raise

service = build("oauth2", "v2", credentials=self._credentials)
logger.info("Google API service built with credentials.")
try:
user_info = service.userinfo().get().execute()
logger.info("User info retrieved successfully.")
return user_info
except Exception as e:
logger.error(f"Failed to retrieve user info: {e}")
raise
return service.userinfo().get().execute()

0 comments on commit 28cd411

Please sign in to comment.