Google oauth + django - 无法从保存的数据进行身份验证

Google oauth + django - cant authenticate from saved data

好的,所以我让流程正常工作,但它只适用于当前会话,如果我尝试加载数据,即使只是刷新凭据也不会停止。

所以这就是 oauth 在用户接受提示后重定向到的地方:

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")

这会按预期加载时间表。但是,如果您刷新以使用存储的凭据,它们永远不会工作,它们永远不会刷新,我不确定该怎么做。

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")

基本上是这样的:

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

如果我评论重定向我得到:

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

由于这条线:

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

我上周刚刚经历了这一切。也许尝试像我一样手动构建凭据,而不是使用 Credentials.from_authorized_user_info()。我发现 Google 喜欢在不更新文档的情况下更改内容。

    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)