|
| 1 | +# Copyright 2025 Google LLC. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the 'License'); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an 'AS IS' BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Functions to handle the OAuth authentication flow.""" |
| 16 | + |
| 17 | +import json |
| 18 | +import logging |
| 19 | +from urllib.parse import parse_qs, urlparse |
| 20 | + |
| 21 | +import flask |
| 22 | +import google_auth_oauthlib.flow |
| 23 | +from google.auth.transport import requests |
| 24 | +from google.oauth2 import id_token |
| 25 | +from google.oauth2.credentials import Credentials |
| 26 | +from firestore_service import store_token |
| 27 | + |
| 28 | +# This variable specifies the name of a file that contains the OAuth 2.0 |
| 29 | +# information for this application, including its client_id and client_secret. |
| 30 | +CLIENT_SECRETS_FILE = "client_secrets.json" |
| 31 | + |
| 32 | +# Application OAuth credentials. |
| 33 | +KEYS = json.load(open(CLIENT_SECRETS_FILE, encoding="UTF-8"))["web"] |
| 34 | + |
| 35 | +# Define the app's authorization scopes. |
| 36 | +# Note: 'openid' is required to that Google Auth will return a JWT with the |
| 37 | +# user id, which we can use to validate that the user who granted consent is |
| 38 | +# the same who requested it (to avoid identity theft). |
| 39 | +SCOPES = ["openid", "https://www.googleapis.com/auth/chat.messages.create"] |
| 40 | + |
| 41 | +def generate_auth_url(user_name: str, config_complete_redirect_url: str) -> str: |
| 42 | + """Generates the URL to start the OAuth2 authorization flow.""" |
| 43 | + flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( |
| 44 | + CLIENT_SECRETS_FILE, scopes=SCOPES) |
| 45 | + flow.redirect_uri = KEYS["redirect_uris"][0] |
| 46 | + # Generate URL for request to Google's OAuth 2.0 server. |
| 47 | + auth_url, _ = flow.authorization_url( |
| 48 | + # Enable offline access so that you can refresh an access token without |
| 49 | + # re-prompting the user for permission. |
| 50 | + access_type="offline", |
| 51 | + # Optional, enable incremental authorization. Recommended as a best practice. |
| 52 | + include_granted_scopes="true", |
| 53 | + state=json.dumps({ |
| 54 | + "userName": user_name, |
| 55 | + "configCompleteRedirectUrl": config_complete_redirect_url |
| 56 | + }) |
| 57 | + ) |
| 58 | + return auth_url |
| 59 | + |
| 60 | +def create_credentials(access_token: str, refresh_token: str) -> Credentials: |
| 61 | + """Returns the Credentials to authenticate using the user tokens.""" |
| 62 | + return Credentials( |
| 63 | + token = access_token, |
| 64 | + refresh_token = refresh_token, |
| 65 | + token_uri = KEYS["token_uri"], |
| 66 | + client_id = KEYS["client_id"], |
| 67 | + client_secret = KEYS["client_secret"], |
| 68 | + scopes = SCOPES |
| 69 | + ) |
| 70 | + |
| 71 | +def oauth2callback(url: str): |
| 72 | + """Handles an OAuth2 callback request. |
| 73 | + If the authorization was succesful, it exchanges the received code with the |
| 74 | + access and refresh tokens and saves them into Firestore to be used when |
| 75 | + calling the Chat API. Then, it redirects the response to the |
| 76 | + configCompleteRedirectUrl specified in the authorization URL. |
| 77 | + If the authorization fails, it just prints an error message to the response. |
| 78 | + """ |
| 79 | + flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( |
| 80 | + CLIENT_SECRETS_FILE, scopes=SCOPES) |
| 81 | + flow.redirect_uri = KEYS["redirect_uris"][0] |
| 82 | + |
| 83 | + # Fetch state from url |
| 84 | + parsed = urlparse(url) |
| 85 | + qs = parse_qs(parsed.query) |
| 86 | + if "error" in qs: |
| 87 | + # An error response e.g. error=access_denied. |
| 88 | + logging.warning("Error: %s", qs["error"][0]) |
| 89 | + return "Error: " + qs["error"][0] |
| 90 | + |
| 91 | + # Use the authorization server's response to fetch the OAuth 2.0 tokens. |
| 92 | + if "code" not in qs: |
| 93 | + logging.warning("Error: invalid query code.") |
| 94 | + return "Error: invalid query code." |
| 95 | + code = qs["code"][0] |
| 96 | + flow.fetch_token(code=code) |
| 97 | + credentials = flow.credentials |
| 98 | + token = id_token.verify_oauth2_token( |
| 99 | + credentials.id_token, requests.Request(), KEYS["client_id"]) |
| 100 | + user_name = "users/" + token["sub"] |
| 101 | + |
| 102 | + # Save tokens to the database so the app can use them to make API calls. |
| 103 | + store_token(user_name, credentials.token, credentials.refresh_token) |
| 104 | + |
| 105 | + # Validate that the user who granted consent is the same who requested it. |
| 106 | + if "state" not in qs: |
| 107 | + logging.warning("Error: invalid query state.") |
| 108 | + return "Error: invalid query state." |
| 109 | + state = json.loads(qs["state"][0]) |
| 110 | + if user_name != state["userName"]: |
| 111 | + logging.warning("Error: token user does not correspond to request user.") |
| 112 | + return """Error: the user who granted consent does not correspond to |
| 113 | + the user who initiated the request. Please start the configuration |
| 114 | + again and use the same account you're using in Google Chat.""" |
| 115 | + |
| 116 | + # Redirect to the URL that tells Google Chat that the configuration is |
| 117 | + # completed. |
| 118 | + return flask.redirect(state["configCompleteRedirectUrl"]) |
0 commit comments