test.py
· 1.2 KiB · Python
Raw
import google.auth.transport.requests
import google_auth_oauthlib.flow
CLIENT_SECRETS_FILE = "client_secrets.json"
SCOPES = ["openid", "https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email"]
def authenticate_user():
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
CLIENT_SECRETS_FILE, SCOPES)
credentials = flow.run_local_server(port=0)
return credentials
def main():
credentials = authenticate_user()
#Test print to see the request
#print("OAuth Credentials:", json.dumps(credentials.to_json(), indent=2))
user_info_url = "https://www.googleapis.com/oauth2/v2/userinfo"
headers = {"Authorization": f"Bearer {credentials.token}"}
response = google.auth.transport.requests.Request().session.get(user_info_url, headers=headers)
if response.status_code == 200:
user_info = response.json()
print("Logged-in User's Google Name:", user_info.get("name"))
print("Logged-in User's Google Email:", user_info.get("email"))
else:
print("Failed to retrieve user information.")
if __name__ == "__main__":
main()
| 1 | import google.auth.transport.requests |
| 2 | import google_auth_oauthlib.flow |
| 3 | |
| 4 | CLIENT_SECRETS_FILE = "client_secrets.json" |
| 5 | SCOPES = ["openid", "https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email"] |
| 6 | |
| 7 | def authenticate_user(): |
| 8 | flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file( |
| 9 | CLIENT_SECRETS_FILE, SCOPES) |
| 10 | |
| 11 | credentials = flow.run_local_server(port=0) |
| 12 | |
| 13 | return credentials |
| 14 | |
| 15 | def main(): |
| 16 | credentials = authenticate_user() |
| 17 | |
| 18 | #Test print to see the request |
| 19 | #print("OAuth Credentials:", json.dumps(credentials.to_json(), indent=2)) |
| 20 | |
| 21 | user_info_url = "https://www.googleapis.com/oauth2/v2/userinfo" |
| 22 | headers = {"Authorization": f"Bearer {credentials.token}"} |
| 23 | |
| 24 | response = google.auth.transport.requests.Request().session.get(user_info_url, headers=headers) |
| 25 | |
| 26 | if response.status_code == 200: |
| 27 | user_info = response.json() |
| 28 | print("Logged-in User's Google Name:", user_info.get("name")) |
| 29 | print("Logged-in User's Google Email:", user_info.get("email")) |
| 30 | else: |
| 31 | print("Failed to retrieve user information.") |
| 32 | |
| 33 | if __name__ == "__main__": |
| 34 | main() |
| 35 |