|
| 1 | +# Copyright 2019 Google, LLC. |
| 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 | +# [START app] |
| 16 | +import base64 |
| 17 | +from flask import current_app, Flask, render_template, request |
| 18 | +import json |
| 19 | +import logging |
| 20 | +import os |
| 21 | + |
| 22 | +from google.auth import jwt |
| 23 | +from google.auth.transport import requests |
| 24 | +from google.cloud import pubsub_v1 |
| 25 | +from google.oauth2 import id_token |
| 26 | + |
| 27 | + |
| 28 | +app = Flask(__name__) |
| 29 | + |
| 30 | +# Configure the following environment variables via app.yaml |
| 31 | +# This is used in the push request handler to verify that the request came from |
| 32 | +# pubsub and originated from a trusted source. |
| 33 | +app.config['PUBSUB_VERIFICATION_TOKEN'] = \ |
| 34 | + os.environ['PUBSUB_VERIFICATION_TOKEN'] |
| 35 | +app.config['PUBSUB_TOPIC'] = os.environ['PUBSUB_TOPIC'] |
| 36 | +app.config['GCLOUD_PROJECT'] = os.environ['GOOGLE_CLOUD_PROJECT'] |
| 37 | + |
| 38 | +# Global list to store messages, tokens, etc. received by this instance. |
| 39 | +MESSAGES = [] |
| 40 | +TOKENS = [] |
| 41 | +HEADERS = [] |
| 42 | +CLAIMS = [] |
| 43 | + |
| 44 | +# [START index] |
| 45 | +@app.route('/', methods=['GET', 'POST']) |
| 46 | +def index(): |
| 47 | + if request.method == 'GET': |
| 48 | + return render_template('index.html', messages=MESSAGES, tokens=TOKENS, |
| 49 | + headers=HEADERS, claims=CLAIMS) |
| 50 | + |
| 51 | + data = request.form.get('payload', 'Example payload').encode('utf-8') |
| 52 | + |
| 53 | + publisher = pubsub_v1.PublisherClient() |
| 54 | + topic_path = publisher.topic_path(app.config['GCLOUD_PROJECT'], |
| 55 | + app.config['PUBSUB_TOPIC']) |
| 56 | + future = publisher.publish(topic_path, data) |
| 57 | + future.result() |
| 58 | + return 'OK', 200 |
| 59 | +# [END index] |
| 60 | + |
| 61 | + |
| 62 | +# [START push] |
| 63 | +@app.route('/_ah/push-handlers/receive_messages', methods=['POST']) |
| 64 | +def receive_messages_handler(): |
| 65 | + # Verify that the request originates from the application. |
| 66 | + if (request.args.get('token', '') != |
| 67 | + current_app.config['PUBSUB_VERIFICATION_TOKEN']): |
| 68 | + return 'Invalid request', 400 |
| 69 | + |
| 70 | + # Verify that the push request originates from Cloud Pub/Sub. |
| 71 | + try: |
| 72 | + # Get the Cloud Pub/Sub-generated JWT in the "Authorization" header. |
| 73 | + bearer_token = request.headers.get('Authorization') |
| 74 | + token = bearer_token.split(' ')[1] |
| 75 | + TOKENS.append(token) |
| 76 | + |
| 77 | + header = jwt.decode_header(token) |
| 78 | + HEADERS.append(header) |
| 79 | + |
| 80 | + # Verify and decode the JWT. Underneath it checks the signature against |
| 81 | + # Google's public certs at https://www.googleapis.com/oauth2/v1/certs. |
| 82 | + # It also checks the token expiration time. |
| 83 | + claim = id_token.verify_oauth2_token(token, requests.Request()) |
| 84 | + CLAIMS.append(claim) |
| 85 | + |
| 86 | + # Check the audience field in the claim. It was specified in |
| 87 | + # `--push-auth-token-audience` when you created the subscription. |
| 88 | + assert claim['aud'] == 'example.com' |
| 89 | + except Exception as e: |
| 90 | + return 'Invalid token: {}\n'.format(e), 400 |
| 91 | + |
| 92 | + envelope = json.loads(request.data.decode('utf-8')) |
| 93 | + payload = base64.b64decode(envelope['message']['data']) |
| 94 | + MESSAGES.append(payload) |
| 95 | + # Returning any 2xx status indicates successful receipt of the message. |
| 96 | + return 'OK', 200 |
| 97 | +# [END push] |
| 98 | + |
| 99 | + |
| 100 | +@app.errorhandler(500) |
| 101 | +def server_error(e): |
| 102 | + logging.exception('An error occurred during a request.') |
| 103 | + return """ |
| 104 | + An internal error occurred: <pre>{}</pre> |
| 105 | + See logs for full stacktrace. |
| 106 | + """.format(e), 500 |
| 107 | + |
| 108 | + |
| 109 | +if __name__ == '__main__': |
| 110 | + # This is used when running locally. Gunicorn is used to run the |
| 111 | + # application on Google App Engine. See entrypoint in app.yaml. |
| 112 | + app.run(host='127.0.0.1', port=8080, debug=True) |
| 113 | +# [END app] |
0 commit comments