Home > Blockchain >  Google oauth django - cant authenticate from saved data
Google oauth django - cant authenticate from saved data

Time:06-04

Okay, so i got the flow working, but it only works on the current session, if i try to load the data in, even with just a refresh the credentials dont hold up.

So this works which is where oauth redirects to after user accepts prompts:

def oauth_redir(request):
    u=Employee.objects.filter(dashboard_user=request.user)
    if not u:
        u=Employee.objects.create(dashboard_user=request.user)
    else:
        u=u[0]
    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        CLIENT_SECRETS_FILE, scopes=SCOPES, state=request.GET.get("state"))
    flow.redirect_uri = REDIRECT_URL
    flow.fetch_token(authorization_response=request.build_absolute_uri().replace("http:","https:"))

    #saving credentials for future use
    credentials = flow.credentials
    if not Emp_google_creds.objects.filter(employee=u):
        Emp_google_creds.objects.create(
        token= credentials.token,
        refresh_token= credentials.refresh_token,
        token_uri = credentials.token_uri,
        client_id = credentials.client_id,
        client_secret= credentials.client_secret,
        scopes = " ".join(credentials.scopes),
        employee = u
        )
    else:
        creds=Emp_google_creds.objects.get(employee=u)
        creds.token = credentials.token,
        creds.refresh_token = credentials.refresh_token,
        creds.token_uri = credentials.token_uri,
        creds.client_id = credentials.client_id,
        creds.client_secret = credentials.client_secret,
        creds.scopes = " ".join(credentials.scopes),
        creds.save()


    if not credentials or not credentials.valid:
        print(credentials, credentials.valid, credentials.expiry)
        # credentials.refresh(Request())
        # return redirect("/calendar/cal_auth/")
    try:
        service = googleapiclient.discovery.build('calendar', 'v3', credentials=credentials)

        # Call the Calendar API
        now = datetime.datetime.utcnow().isoformat()   'Z'  # 'Z' indicates UTC time
        print('Getting the upcoming 10 events')
        events_result = service.events().list(calendarId='primary', timeMin=now,
                                              maxResults=10, singleEvents=True,
                                              orderBy='startTime').execute()
        events = events_result.get('items', [])

        if not events:
            print('No upcoming events found.')
            return

        # Prints the start and name of the next 10 events
        for event in events:
            start = event['start'].get('dateTime', event['start'].get('date'))
            print(start, event['summary'])

    except HttpError as error:
        print('An error occurred: %s' % error)
    print("end of redir func")
    return render(request,"schedule.html")

this loads the schedule as expected. however if you refresh in order to use the stored credentials they never work, they never refresh, i'm unsure on what to do.

def calendar_home(request):
    u = Employee.objects.filter(dashboard_user=request.user)
    if not u:
        u = Employee.objects.create(dashboard_user=request.user)
    else:
        u = u[0]

    print(Emp_google_creds.objects.filter(employee=u))
    if not Emp_google_creds.objects.filter(employee=u):
        return redirect("/calendar/cal_auth/")
    else:
        creds=Emp_google_creds.objects.filter(employee=u)[0]
        gcreds=google.oauth2.credentials.Credentials.from_authorized_user_info(creds.to_dict())
        if not gcreds or not gcreds.valid:
            print(gcreds, gcreds.valid, gcreds.expiry)
            # gcreds.refresh(Request())
            return redirect("/calendar/cal_auth/")
        try:
            service = googleapiclient.discovery.build('calendar', 'v3', credentials=gcreds)

            # Call the Calendar API
            now = datetime.datetime.utcnow().isoformat()   'Z'  # 'Z' indicates UTC time
            print('Getting the upcoming 10 events')
            events_result = service.events().list(calendarId='primary', timeMin=now,
                                                  maxResults=10, singleEvents=True,
                                                  orderBy='startTime').execute()
            events = events_result.get('items', [])

            if not events:
                print('No upcoming events found.')
                return

            # Prints the start and name of the next 10 events
            for event in events:
                start = event['start'].get('dateTime', event['start'].get('date'))
                print(start, event['summary'])

        except HttpError as error:
            print('An error occurred: %s' % error)
    return render(request,"schedule.html")

basically this:

print(gcreds, gcreds.valid, gcreds.expiry) => 
<google.oauth2.credentials.Credentials object at 0x7f322a00b340> False 2022-06-03 14:44:02.232624

and if i comment the redirect out i get:

('invalid_client: The OAuth client was not found.', {'error': 'invalid_client', 'error_description': 'The OAuth client was not found.'})

caused on this line:

events_result = service.events().list(calendarId='primary', timeMin=now, ... 

CodePudding user response:

I just went through all of this last week. Maybe try building the credentials manually like I did instead of using Credentials.from_authorized_user_info(). I found out the hard way that Google likes to change things without updating their documentation.

    user_creds = json.loads(Emp_google_creds.objects.filter(employee=u)[0])
    creds=Credentials(
    token=user_creds['token'],
    refresh_token=user_creds['refresh_token'],
    token_uri=user_creds['token_uri'],
    client_id=user_creds['client_id'],
    client_secret=user_creds['client_secret']
    )
    service = build('calendar', 'v3', credentials=creds)
  • Related