Simple test

Ensure your device works with this simple test.

examples/oauth2_simpletest.py
 1# SPDX-FileCopyrightText: 2020 Brent Rubell, written for Adafruit Industries
 2#
 3# SPDX-License-Identifier: Unlicense
 4import ssl
 5import wifi
 6import socketpool
 7import adafruit_requests
 8from adafruit_oauth2 import OAuth2
 9
10# Add a secrets.py to your filesystem that has a dictionary called secrets with "ssid" and
11# "password" keys with your WiFi credentials. DO NOT share that file or commit it into Git or other
12# source control.
13# pylint: disable=no-name-in-module,wrong-import-order
14try:
15    from secrets import secrets
16except ImportError:
17    print("Credentials and tokens are kept in secrets.py, please add them there!")
18    raise
19
20print("Connecting to %s" % secrets["ssid"])
21wifi.radio.connect(secrets["ssid"], secrets["password"])
22print("Connected to %s!" % secrets["ssid"])
23
24pool = socketpool.SocketPool(wifi.radio)
25requests = adafruit_requests.Session(pool, ssl.create_default_context())
26
27
28# Set scope(s) of access required by the API you're using
29scopes = ["email"]
30
31# Initialize an OAuth2 object
32google_auth = OAuth2(
33    requests, secrets["google_client_id"], secrets["google_client_secret"], scopes
34)
35
36# Request device and user codes
37# https://developers.google.com/identity/protocols/oauth2/limited-input-device#step-1:-request-device-and-user-codes
38google_auth.request_codes()
39
40# Display user code and verification url
41# NOTE: If you are displaying this on a screen, ensure the text label fields are
42# long enough to handle the user_code and verification_url.
43# Details in link below:
44# https://developers.google.com/identity/protocols/oauth2/limited-input-device#displayingthecode
45print(
46    "1) Navigate to the following URL in a web browser:", google_auth.verification_url
47)
48print("2) Enter the following code:", google_auth.user_code)
49
50# Poll Google's authorization server
51print("Waiting for browser authorization...")
52if not google_auth.wait_for_authorization():
53    raise RuntimeError("Timed out waiting for browser response!")
54
55print("Successfully authorized with Google!")
56print("-" * 40)
57print("\tAccess Token:", google_auth.access_token)
58print("\tAccess Token Scope:", google_auth.access_token_scope)
59print("\tAccess token expires in: %d seconds" % google_auth.access_token_expiration)
60print("\tRefresh Token:", google_auth.refresh_token)
61print("-" * 40)
62
63# Refresh an access token
64print("Refreshing access token...")
65if not google_auth.refresh_access_token():
66    raise RuntimeError("Unable to refresh access token - has the token been revoked?")
67print("-" * 40)
68print("\tNew Access Token: ", google_auth.access_token)
69print("-" * 40)