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
4
5import ssl
6from os import getenv
7
8import adafruit_requests
9import socketpool
10import wifi
11
12from adafruit_oauth2 import OAuth2
13
14# Get WiFi details and Google keys, ensure these are setup in settings.toml
15ssid = getenv("CIRCUITPY_WIFI_SSID")
16password = getenv("CIRCUITPY_WIFI_PASSWORD")
17google_client_id = getenv("google_client_id")
18google_client_secret = getenv("google_client_secret")
19
20print(f"Connecting to {ssid}")
21wifi.radio.connect(ssid, password)
22print(f"Connected to {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(requests, google_client_id, google_client_secret, scopes)
33
34# Request device and user codes
35# https://developers.google.com/identity/protocols/oauth2/limited-input-device#step-1:-request-device-and-user-codes
36google_auth.request_codes()
37
38# Display user code and verification url
39# NOTE: If you are displaying this on a screen, ensure the text label fields are
40# long enough to handle the user_code and verification_url.
41# Details in link below:
42# https://developers.google.com/identity/protocols/oauth2/limited-input-device#displayingthecode
43print("1) Navigate to the following URL in a web browser:", google_auth.verification_url)
44print("2) Enter the following code:", google_auth.user_code)
45
46# Poll Google's authorization server
47print("Waiting for browser authorization...")
48if not google_auth.wait_for_authorization():
49 raise RuntimeError("Timed out waiting for browser response!")
50
51print("Successfully authorized with Google!")
52print("-" * 40)
53print("\tAccess Token:", google_auth.access_token)
54print("\tAccess Token Scope:", google_auth.access_token_scope)
55print(f"\tAccess token expires in: {google_auth.access_token_expiration:d} seconds")
56print("\tRefresh Token:", google_auth.refresh_token)
57print("-" * 40)
58
59# Refresh an access token
60print("Refreshing access token...")
61if not google_auth.refresh_access_token():
62 raise RuntimeError("Unable to refresh access token - has the token been revoked?")
63print("-" * 40)
64print("\tNew Access Token: ", google_auth.access_token)
65print("-" * 40)