|
| 1 | +# Copyright 2018 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 | + |
| 16 | +# [START functions_cors] |
| 17 | +def cors_enabled_function(request): |
| 18 | + # Set CORS headers for the preflight request |
| 19 | + # e.g. allows GETs from any origin with the Content-Type header |
| 20 | + # and cache preflight response for an 3600s |
| 21 | + preflight_request_headers = { |
| 22 | + 'Access-Control-Allow-Origin': '*', |
| 23 | + 'Access-Control-Allow-Methods': 'GET', |
| 24 | + 'Access-Control-Allow-Headers': 'Content-Type', |
| 25 | + 'Access-Control-Max-Age': '3600' |
| 26 | + } |
| 27 | + |
| 28 | + # Send response to OPTIONS requests and terminate the function execution |
| 29 | + if request.method == 'OPTIONS': |
| 30 | + return ('', 204, preflight_request_headers) |
| 31 | + |
| 32 | + # Set CORS headers for the main request |
| 33 | + main_request_headers = { |
| 34 | + 'Access-Control-Allow-Origin': '*' |
| 35 | + } |
| 36 | + |
| 37 | + return ('Hello World!', 200, main_request_headers) |
| 38 | +# [END functions_cors] |
| 39 | + |
| 40 | + |
| 41 | +# [START functions_cors_authentication] |
| 42 | +def cors_enabled_function_auth(request): |
| 43 | + # Set CORS headers for preflight requests |
| 44 | + # e.g. allows GETS from origin https://mydomain.com with Authorization |
| 45 | + # header |
| 46 | + preflight_request_headers = { |
| 47 | + 'Access-Control-Allow-Origin': 'https://mydomain.com', |
| 48 | + 'Access-Control-Allow-Methods': 'GET', |
| 49 | + 'Access-Control-Allow-Headers': 'Authorization', |
| 50 | + 'Access-Control-Max-Age': '3600', |
| 51 | + 'Access-Control-Allow-Credentials': 'true' |
| 52 | + } |
| 53 | + |
| 54 | + # Send response to OPTIONS requests and terminate the function execution |
| 55 | + if request.method == 'OPTIONS': |
| 56 | + return ('', 204, preflight_request_headers) |
| 57 | + |
| 58 | + # Set CORS headers for main requests |
| 59 | + main_request_headers = { |
| 60 | + 'Access-Control-Allow-Origin': 'https://mydomain.com', |
| 61 | + 'Access-Control-Allow-Credentials': 'true' |
| 62 | + } |
| 63 | + |
| 64 | + return ('Hello World!', 200, main_request_headers) |
| 65 | +# [END functions_cors_authentication] |
0 commit comments