10000 Make auth work :joy: · tf2keras/cloud-functions-python@b81d72e · GitHub
[go: up one dir, main page]

Skip to content

Commit b81d72e

Browse files
committed
Make auth work 😂
1 parent 17fb2bb commit b81d72e

File tree

11 files changed

+80
-40
lines changed

11 files changed

+80
-40
lines changed

README.md

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,19 @@ Output: ./cloudfn/target/index.js
9090
This library works with [pip](https://pypi.python.org/pypi) OOTB. Just add your `requirements.txt` file in the root
9191
of the repo and you are golden. It obviously needs `pycloudfn` to be present.
9292

93+
## Autentication
94+
Since this is not really supported by google, there is one thing that needs to be done to
95+
make this work smoothly: You can't use the default clients directly. It's solvable though,
96+
just do
97+
98+
```python
99+
from cloudfn.google_account import get_credentials
100+
101+
biquery_client = bigquery.Client(credentials=get_credentials())
102+
```
103+
104+
And everything is taken care of for you!! no more actions need be done.
105+
93106
### Handling a http request
94107

95108
look at the [Request](https://github.com/MartinSahlen/cloud-functions-python/blob/master/cloudfn/http.py)
@@ -123,18 +136,18 @@ to see how easy it is!
123136

124137
```python
125138
from cloudfn.flask_handler import handle_http_event
139+
from cloudfn.google_account import get_credentials
126140
from flask import Flask, request
127141
from flask.json import jsonify
128142
from google.cloud import bigquery
129143

130-
131144
app = Flask('the-function')
132-
client = bigquery.Client()
145+
biquery_client = bigquery.Client(credentials=get_credentials())
133146

134147

135148
@app.route('/', methods=['POST', 'GET'])
136149
def hello():
137-
print request.args
150+
print request.headers
138151
return jsonify(message='Hello world!', json=request.get_json()), 201
139152

140153

@@ -146,7 +159,7 @@ def helloLol():
146159
@app.route('/bigquery-datasets', methods=['POST', 'GET'])
147160
def bigquery():
148161
datasets = []
149-
for dataset in client.list_datasets():
162+
for dataset in biquery_client.list_datasets():
150163
datasets.append(dataset.name)
151164
return jsonify(message='Hello world!', datasets={
152165
'datasets': datasets

cloudfn/cli.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,13 +187,25 @@ def build_javascript(function_name, trigger_type):
187187
}
188188
)
189189
open('cloudfn/index.js', 'w').write(rendered_js)
190+
open('cloudfn/package.json', 'w').write('''{
191+
"name": "target",
192+
"version": "1.0.0",
193+
"description": "",
194+
"main": "index.js",
195+
"author": "",
196+
"license": "ISC",
197+
"dependencies": {
198+
"google-auto-auth": "^0.7.0"
199+
}
200+
}
201+
''')
190202

191203

192204
@make_spin(Default, 'Cleaning up...')
193205
def cleanup():
194206
p = subprocess.Popen(
195207
'cd cloudfn && rm -rf target && mkdir target && mv index.js target ' +
196-
'&& mv dist target',
208+
'&& mv package.json target && mv dist target',
197209
stdout=subprocess.PIPE,
198210
stderr=subprocess.STDOUT,
199211
shell=True)

cloudfn/google_account.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import os
2+
from google.oauth2 import credentials
3+
4+
5+
def get_credentials():
6+
return credentials.Credentials(os.getenv('GOOGLE_OAUTH_TOKEN', ''))

cloudfn/template/index.js

Lines changed: 33 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,42 @@
1+
var googleAuth = require('google-auto-auth')();
12
//Handle Background events according to spec
23
function shimHandler(data) {
34
return new Promise((resolve, reject) => {
4-
//Spawn the function and inject the env from the parent process.
5-
const p = require('child_process').execFile('./dist/{{config["output_name"]}}/{{config["output_name"]}}', {
6-
env: process.env,
7-
});
8-
var lastMessage;
9-
p.stdin.setEncoding('utf-8');
10-
//Log standard err messages to standard err
11-
p.stderr.on('data', (err) => {
12-
console.error(err.toString());
13-
})
14-
p.stdout.on('data', (out) => {
15-
console.log(out.toString());
16-
lastMessage = out;
17-
})
18-
p.on('close', (code) => {
19-
if (code !== 0) {
20-
//This means the shim failed / panicked. So we reject hard.
21-
reject();
5+
googleAuth.getToken(function (err, oauthToken) {
6+
if (err) {
7+
reject()
228
} else {
23-
// Resolve the promise with the latest output from stdout
24-
// In case of shimming http, this is the response object.
25-
resolve(lastMessage);
9+
const p = require('child_process').execFile('./dist/{{config["output_name"]}}/{{config["output_name"]}}', {
10+
env: Object.assign(process.env, {
11+
'GOOGLE_OAUTH_TOKEN': oauthToken,
12+
})
13+
});
14+
var lastMessage;
15+
p.stdin.setEncoding('utf-8');
16+
//Log standard err messages to standard err
17+
p.stderr.on('data', (err) => {
18+
console.error(err.toString());
19+
})
20+
p.stdout.on('data', (out) => {
21+
console.log(out.toString());
22+
lastMessage = out;
23+
})
24+
p.on('close', (code) => {
25+
if (code !== 0) {
26+
//This means the shim failed / panicked. So we reject hard.
27+
reject();
28+
} else {
29+
// Resolve the promise with the latest output from stdout
30+
// In case of shimming http, this is the response object.
31+
resolve(lastMessage);
32+
}
33+
});
34+
//Write the object/message/request to the shim's stdin and signal
35+
//End of input.
36+
p.stdin.write(JSON.stringify(data));
37+
p.stdin.end();
2638
}
2739
});
28-
//Write the object/message/request to the shim's stdin and signal
29-
//End of input.
30-
p.stdin.write(JSON.stringify(data));
31-
p.stdin.end();
3240
});
3341
}
3442

examples/django/requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
django==1.11
2-
pycloudfn==0.1.199
2+
pycloudfn==0.1.205
33
djangorestframework==3.6.3

examples/flask/function.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
from cloudfn.flask_handler import handle_http_event
2+
from cloudfn.google_account import get_credentials
23
from flask import Flask, request
34
from flask.json import jsonify
45
from google.cloud import bigquery
56

6-
77
app = Flask('the-function')
8-
client = bigquery.Client()
8+
biquery_client = bigquery.Client(credentials=get_credentials())
99

1010

1111
@app.route('/', methods=['POST', 'GET'])
1212
def hello():
13-
print request.args
13+
print request.headers
1414
return jsonify(message='Hello world!', json=request.get_json()), 201
1515

1616

@@ -22,7 +22,7 @@ def helloLol():
2222
@app.route('/bigquery-datasets', methods=['POST', 'GET'])
2323
def bigquery():
2424
datasets = []
25-
for dataset in client.list_datasets():
25+
for dataset in biquery_client.list_datasets():
2626
datasets.append(dataset.name)
2727
return jsonify(message='Hello world!', datasets={
2828
'datasets': datasets

examples/flask/requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
pycloudfn==0.1.199
1+
pycloudfn==0.1.205
22
flask==0.12
33
google-cloud-bigquery==0.24.0

examples/http/requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
pycloudfn==0.1.199
1+
pycloudfn==0.1.205

examples/pubsub/requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
pycloudfn==0.1.199
1+
pycloudfn==0.1.205
22
jsonpickle==0.9.4

examples/storage/requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
pycloudfn==0.1.199
1+
pycloudfn==0.1.205
22
jsonpickle==0.9.4

0 commit comments

Comments
 (0)
0