Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 34 additions & 5 deletions python/auth-app/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,27 @@ please read the
1. Enable the Cloud Datastore API for your project using
[this wizard](https://console.cloud.google.com/flows/enableapi?apiid=datastore.googleapis.com).
1. Follow [instructions](https://support.google.com/googleapi/answer/6158849?hl=en) for creating
an oauth client ID for your project. Use the type "Web application" and a redirect
URI of \
`https://<project ID>.appspot.com/auth/callback`.
an oauth client ID for your project. Use the type "Web application".
1. Download the associated JSON file, move it to this directory, and name it
`client_secret.json`.
`client_secrets.json`.

1. Run the following command to deploy the app:
```
gcloud app deploy
```
1. Fetch the URL:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: describe the expected result

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated the instructions

```
gcloud app browse
```
1. Replace the `redirect_uris` in your `client_secrets.json` with `<URL from the previous step>/auth/callback`.
1. Create a [service account](https://support.google.com/a/answer/7378726?hl=en#)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove hl=en from the URL parameters

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated the instructions

1. Make the service account the default in the [App Engine Application Settings](https://console.cloud.google.com/appengine/settings)
1. Grant the service account permissions to access the datastore
```
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:$SERVICE_ACCOUNT_EMAIL" \
--role="roles/datastore.owner"
```

## Configure the app for Google Chat

Expand Down Expand Up @@ -76,7 +87,25 @@ To verify that the sample is running and responds with the correct data
to incoming requests, run the following command from the terminal:

```
curl -H 'Content-Type: application/json' --data '{"type": "MESSAGE", "configCompleteRedirectUrl": "https://www.example.com", "message": { "text": "header keyvalue", "thread": null }, "user": { "name": "users/123", "displayName": "me"}, "space": { "displayName": "space", "name": "spaces/-oMssgAAAAE"}}' http://127.0.0.1:8080/
curl \
-H 'Content-Type: application/json' \
--data '{
"type": "MESSAGE",
"configCompleteRedirectUrl": "https://www.example.com",
"message": {
"text": "header keyvalue",
"thread": null
},
"user": {
"name": "users/123",
"displayName": "me"
},
"space": {
"displayName": "space",
"name": "spaces/-oMssgAAAAE"
}
}' \
http://127.0.0.1:8080/
```

## Shut down the local environment
Expand Down
2 changes: 2 additions & 0 deletions python/auth-app/app.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,5 @@ runtime: python310
env_variables:
CLIENT_SECRET_PATH: "client_secret.json"
SESSION_SECRET: "notasecret"

service_account: <SERVICE_ACCOUNT>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm assuming that this value needs to be set before deploying, should we add an additional step in the README instructions?

Alternatively, you could add a quick comment that define what it is.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated the instructions

223 changes: 129 additions & 94 deletions python/auth-app/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,21 +32,22 @@
from google.oauth2.credentials import Credentials
from google_auth_oauthlib import flow

CLIENT_SECRET_PATH = os.environ.get('CLIENT_SECRET_PATH', 'client_secret.json')
JWT_SECRET = os.environ.get('SESSION_SECRET', 'notasecret')
CLIENT_SECRET_PATH = os.environ.get("CLIENT_SECRET_PATH", "client_secrets.json")
JWT_SECRET = os.environ.get("SESSION_SECRET", "notasecret")

mod = flask.Blueprint('auth', __name__)
mod = flask.Blueprint("auth", __name__)

# Scopes required to access the People API.
PEOPLE_API_SCOPES = [
'openid',
'https://www.googleapis.com/auth/user.emails.read',
'https://www.googleapis.com/auth/user.addresses.read',
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/user.phonenumbers.read',
"openid",
"https://www.googleapis.com/auth/user.emails.read",
"https://www.googleapis.com/auth/user.addresses.read",
"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/user.phonenumbers.read",
]


class Store:
"""Manages storage in Google Cloud Datastore."""

Expand All @@ -62,12 +63,15 @@ def get_user_credentials(self, user_name: str) -> Credentials | None:
Returns:
A Credentials object, or None if the user has not authorized the app.
"""
key = self.datastore_client.key('RefreshToken', user_name)
entity = self.datastore_client.get(key)

if entity is None or 'credentials' not in entity:
try:
key = self.datastore_client.key("RefreshToken", user_name)
entity = self.datastore_client.get(key)
if entity is None or "credentials" not in entity:
return None
return Credentials(**entity["credentials"])
except Exception as e:
logging.exception("Error retrieving credentials: %s", e)
return None
return Credentials(**entity['credentials'])

def put_user_credentials(self, user_name: str, creds: Credentials) -> None:
"""Stores OAuth2 credentials for a user.
Expand All @@ -76,35 +80,51 @@ def put_user_credentials(self, user_name: str, creds: Credentials) -> None:
user_name (str): The identifier for the associated user.
creds (Credentials): The OAuth2 credentials obtained for the user.
"""
key = self.datastore_client.key('RefreshToken', user_name)
entity = datastore.Entity(key)
entity.update({
'credentials': {
'token': creds.token,
'refresh_token': creds.refresh_token,
'token_uri': creds.token_uri,
'client_id': creds.client_id,
'client_secret': creds.client_secret,
'scopes': creds.scopes,
},
'timestamp': time.time()
})
self.datastore_client.put(entity)
try:
key = self.datastore_client.key("RefreshToken", user_name)
entity = datastore.Entity(key)
entity.update(
{
"credentials": {
"token": creds.token,
"refresh_token": creds.refresh_token,
"token_uri": creds.token_uri,
"client_id": creds.client_id,
"client_secret": creds.client_secret,
"scopes": creds.scopes,
},
"timestamp": time.time(),
}
)
self.datastore_client.put(entity)
except Exception as e:
logging.exception("Error storing credentials: %s", e)

def delete_user_credentials(self, user_name: str) -> None:
"""Deleted stored OAuth2 credentials for a user.

Args:
user_name (str): The identifier for the associated user.
"""
key = self.datastore_client.key('RefreshToken', user_name)
try:
key = self.datastore_client.key("RefreshToken", user_name)
self.datastore_client.delete(key)
except Exception as e:
logging.exception("Error deleting credentials: %s", e)

key = self.datastore_client.key("RefreshToken", user_name)
self.datastore_client.delete(key)


def get_user_credentials(user_name: str) -> Credentials:
"""Gets stored crednetials for a user, if it exists."""
store = Store()
return store.get_user_credentials(user_name)
try:
store = Store()
return store.get_user_credentials(user_name)
except Exception as e:
logging.exception("Error getting credentials: %s", e)
return None


def get_config_url(event) -> Any:
"""Gets the authorization URL to redirect the user to.
Expand All @@ -116,11 +136,14 @@ def get_config_url(event) -> Any:
Returns:
str: The authorization URL to direct the user to.
"""
payload = {
'completion_url': event['configCompleteRedirectUrl']
}
token = jwt.encode(payload, JWT_SECRET, algorithm='HS256')
return flask.url_for('auth.start_auth', token=token, _external=True)
try:
payload = {"completion_url": event["configCompleteRedirectUrl"]}
token = jwt.encode(payload, JWT_SECRET, algorithm="HS256")
return flask.url_for("auth.start_auth", token=token, _external=True)
except Exception as e:
logging.exception("Error getting config URL: %s", e)
return None


def logout(user_name: str) -> None:
"""Logs out the user, removing their stored credentials and revoking the
Expand All @@ -129,66 +152,78 @@ def logout(user_name: str) -> None:
Args:
user_name (str): The identifier of the user.
"""
store = Store()
user_credentials = store.get_user_credentials(user_name)
if user_credentials is None:
logging.info('Ignoring logout request for user %s', user_name)
return
logging.info('Logging out user %s', user_name)
store.delete_user_credentials(user_name)
request = requests.Request()
request.post(
'https://accounts.google.com/o/oauth2/revoke',
params={'token': user_credentials.token},
headers={'Content-Type': 'application/x-www-form-urlencoded'})


@mod.route('/start')
try:
store = Store()
user_credentials = store.get_user_credentials(user_name)
if user_credentials is None:
logging.info("Ignoring logout request for user %s", user_name)
return
logging.info("Logging out user %s", user_name)
store.delete_user_credentials(user_name)
request = requests.Request()
request.post(
"https://accounts.google.com/o/oauth2/revoke",
params={"token": user_credentials.token},
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
except Exception as e:
logging.exception("Error logging out user: %s", e)


@mod.route("/start")
def start_auth() -> flask.Response:
"""Begins the oauth flow to authorize access to profile data."""
token = flask.request.args['token']
request = jwt.decode(token, JWT_SECRET, algorithm='HS256')

flask.session['completion_url'] = request['completion_url']
oauth2_flow = flow.Flow.from_client_secrets_file(
CLIENT_SECRET_PATH,
scopes=PEOPLE_API_SCOPES,
redirect_uri=flask.url_for('auth.on_oauth2_callback', _external=True))
oauth2_url, state = oauth2_flow.authorization_url(
access_type='offline',
include_granted_scopes='true',
prompt='consent')
flask.session['state'] = state
return flask.redirect(oauth2_url)

@mod.route('/callback')
try:
token = flask.request.args["token"]
request = jwt.decode(token, JWT_SECRET, algorithms=["HS256"])

flask.session["completion_url"] = request["completion_url"]
oauth2_flow = flow.Flow.from_client_secrets_file(
CLIENT_SECRET_PATH,
scopes=PEOPLE_API_SCOPES,
redirect_uri=flask.url_for("auth.on_oauth2_callback", _external=True),
)
oauth2_url, state = oauth2_flow.authorization_url(
access_type="offline", include_granted_scopes="true", prompt="consent"
)
flask.session["state"] = state
return flask.redirect(oauth2_url)
except Exception as e:
logging.exception("Error starting auth: %s", e)
return flask.abort(403)


@mod.route("/callback")
def on_oauth2_callback() -> flask.Response:
"""Handles the OAuth callback."""
saved_state = flask.session['state']
state = flask.request.args['state']

if state != saved_state:
logging.warn('Mismatched state in oauth response')
try:
saved_state = flask.session["state"]
state = flask.request.args["state"]

if state != saved_state:
logging.warn("Mismatched state in oauth response")
return flask.abort(403)

redirect_uri = flask.url_for("auth.on_oauth2_callback", _external=True)
oauth2_flow = flow.Flow.from_client_secrets_file(
CLIENT_SECRET_PATH, scopes=PEOPLE_API_SCOPES, redirect_uri=redirect_uri
)
oauth2_flow.fetch_token(authorization_response=flask.request.url)
creds = oauth2_flow.credentials

# Use the id_token to identify the chat user.
request = requests.Request()
id_info = id_token.verify_oauth2_token(creds.id_token, request, creds.client_id)

if id_info["iss"] != "https://accounts.google.com":
flask.abort(403)

user_id = id_info["sub"]
user_name = "users/{user_id}".format(user_id=user_id)
store = Store()
store.put_user_credentials(user_name, creds)
completion_url = flask.session["completion_url"]
return flask.redirect(completion_url)
except Exception as e:
logging.exception("Error completing auth: %s", e)
return flask.abort(403)

redirect_uri = flask.url_for('auth.on_oauth2_callback', _external=True)
oauth2_flow = flow.Flow.from_client_secrets_file(
CLIENT_SECRET_PATH,
scopes=PEOPLE_API_SCOPES,
redirect_uri=redirect_uri)
oauth2_flow.fetch_token(authorization_response=flask.request.url)
creds = oauth2_flow.credentials

# Use the id_token to identify the chat user.
request = requests.Request()
id_info = id_token.verify_oauth2_token(creds.id_token, request, creds.client_id)

if id_info['iss'] != 'https://accounts.google.com':
flask.abort(403)

user_id = id_info['sub']
user_name = 'users/{user_id}'.format(user_id=user_id)
store = Store()
store.put_user_credentials(user_name, creds)
completion_url = flask.session['completion_url']
return flask.redirect(completion_url)
5 changes: 5 additions & 0 deletions python/auth-app/install.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#!/bin/bash

python3 -m venv .venv
source .venv/bin/activate
python3 -m pip install --upgrade -r requirements.txt
Loading