Опубликовать запрос, где Google OAUT требуется - PullRequest
0 голосов
/ 19 марта 2020

Итак, я написал бота и приложение flask, с которым я хочу работать вместе. Бот должен сделать HTTP-запрос POST к серверу flask. Однако для завершения запроса POST звонящий должен пройти проверку подлинности с помощью Google oauth.

Мой код:

@app.route('/test')
def test_api_request():

  if 'credentials' not in flask.session:
    return flask.redirect('authorize')


  # Load credentials from the session.
  credentials = google.oauth2.credentials.Credentials(
      **flask.session['credentials'])

  calender = googleapiclient.discovery.build(
      API_SERVICE_NAME, API_VERSION, credentials=credentials)

  print(flask.session.get('minDate'))
  print(flask.session.get('maxDate'))
  event = {
  'summary': 'Summary',
  'location': 'Karlstad',
  'description': 'A test event.',
  'start': {
      'dateTime': str(flask.session.get('minDate')).replace(" ", "+"),
  },
  'end': {
      'dateTime': str(flask.session.get('maxDate')).replace(" ", "+"),
  }}

  result = calender.events().insert(calendarId='primary', body=event).execute()

  calendars = calender.calendarList().list().execute()
  # Save credentials back to session in case access token was refreshed.
  # ACTION ITEM: In a production app, you likely want to save these
  #              credentials in a persistent database instead.
  #flask.session['credentials'] = credentials_to_dict(credentials)

  return flask.jsonify(**calendars)


@app.route('/authorize')
def authorize():

  # Create flow instance to manage the OAuth 2.0 Authorization Grant Flow steps.
  flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
      CLIENT_SECRETS_FILE, scopes=SCOPES)

  # The URI created here must exactly match one of the authorized redirect URIs
  # for the OAuth 2.0 client, which you configured in the API Console. If this
  # value doesn't match an authorized URI, you will get a 'redirect_uri_mismatch'
  # error.
  flow.redirect_uri = flask.url_for('oauth2callback', _external=True)

  authorization_url, state = flow.authorization_url(
      # Enable offline access so that you can refresh an access token without
      # re-prompting the user for permission. Recommended for web server apps.
      access_type='offline',
      # Enable incremental authorization. Recommended as a best practice.
      include_granted_scopes='true')

  # Store the state so the callback can verify the auth server response.
  flask.session['state'] = state

  #authorization_url = authorization_url.replace('http', 'https')
  print("")
  print(authorization_url)
  print("")
  return flask.redirect(authorization_url)


@app.route('/oauth2callback')
def oauth2callback():
  # Specify the state when creating the flow in the callback so that it can
  # verified in the authorization server response.

  state = flask.session['state']

  flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
      CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)

  flow.redirect_uri = flask.url_for('oauth2callback', _external=True)

  # Use the authorization server's response to fetch the OAuth 2.0 tokens.
  authorization_response = flask.request.url
  authorization_response = authorization_response.replace('http', 'https')

  flow.fetch_token(authorization_response=authorization_response)


  # Store credentials in the session.
  # ACTION ITEM: In a production app, you likely want to save these
  #              credentials in a persistent database instead.
  credentials = flow.credentials

  flask.session['credentials'] = credentials_to_dict(credentials)

  print(flask.url_for('test_api_request'))
  return flask.redirect(flask.url_for('test_api_request'))

Этот код в значительной степени основан на этом примере: https://developers.google.com/identity/protocols/oauth2/web-server

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...