Неправильная область доступа к событиям

HttpError at /calendar
<HttpError 403 when requesting https://www.googleapis.com/calendar/v3/calendars/primary/events?singleEvents=true&orderBy=startTime&alt=json returned "Request had insufficient authentication scopes.". Details: "[{'message': 'Insufficient Permission', 'domain': 'global', 'reason': 'insufficientPermissions'}]">
Request Method: GET
Request URL:    http://localhost:8000/calendar
Django Version: 3.2.9
Exception Type: HttpError
Exception Value:    

Затем делает это через некоторое время

RefreshError at /calendar
The credentials do not contain the necessary fields need to refresh the access token. You must specify refresh_token, token_uri, client_id, and client_secret.

Похоже, что я не обладаю правильной областью видимости при доступе к календарю, и похоже, что в настоящее время появляется access_token.

from google.oauth2.credentials import Credentials
def get_user_events(request):
    credentials = Credentials(get_access_token(request), scopes=SCOPES)
    service = googleapiclient.discovery.build('calendar', 'v3', credentials=credentials)
    google_calendar_events = service.events().list(calendarId='primary', singleEvents=True,
                                          orderBy='startTime').execute()
    google_calendar_events = google_calendar_events.get('items', [])
    return google_calendar_events

def get_access_token(request): 
    social = request.user.social_auth.get(provider='google-oauth2') 
    return social.extra_data['access_token']

"Запрос не имел достаточных диапазонов аутентификации.".

Если мы проверим документацию для events.get, то обнаружим, что этот метод работает с частными данными пользователя, а это означает, что нам необходимо быть авторизованными для доступа к ним. Кроме того, мы должны быть авторизованы с одним из следующих диапазонов

enter image description here

Из вашего кода я не могу понять, какие диапазоны вы запрашиваете. Первое, что нужно сделать, это убедиться, что вы запрашиваете одну из вышеуказанных областей при авторизации пользователя. Если вы измените сферу, помните, что вы должны снова запросить согласие пользователя, чтобы оно вступило в силу.

Вы должны указать refresh_token, token_uri, client_id и client_secret.

<<<Похоже, что вы неправильно храните маркер обновления. get_access_token не будет работать, если маркер обновления не сохранен.

В официальном примере обратите внимание, как они хранят данные пользователя в файле token.json, а затем библиотека автоматически запрашивает новый токен доступа, когда ей это необходимо.

 """Shows basic usage of the Google Calendar API.
    Prints the start and name of the next 10 events on the user's calendar.
    """
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())
Вернуться на верх