Skip to content

Commit

Permalink
Adds token refresh to HTTP example. (#517)
Browse files Browse the repository at this point in the history
* Adds token refresh to HTTP example.

* Review feedback
  • Loading branch information
gguuss authored Nov 3, 2017
1 parent 594525a commit 8e2b651
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
1 change: 1 addition & 0 deletions iot/http_example/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ Options:
Either RS256 (RSA) or ES256 (Eliptic Curve)
--cloud_region [region] GCP cloud region
--num_messages [num] Number of messages to publish.
--token_exp_mins [num] Minutes to JWT token expiration.
--http_bridge_address [address] HTTP bridge address.
--message_type [events|state] The message type to publish.

Expand Down
17 changes: 16 additions & 1 deletion iot/http_example/cloudiot_http_example_nodejs.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,12 @@ var argv = require(`yargs`)
requiresArg: true,
type: 'number'
},
token_exp_mins: {
default: 20,
description: 'Minutes to JWT token expiration.',
requiresArg: true,
type: 'number'
},
http_bridge_address: {
default: 'cloudiot-device.googleapis.com',
description: 'HTTP bridge address.',
Expand Down Expand Up @@ -145,6 +151,14 @@ function publishAsync (messageCount, numMessages) {
// If we have published fewer than numMessage messages, publish payload
// messageCount + 1.
setTimeout(function () {
let secsFromIssue = parseInt(Date.now() / 1000) - iatTime;
if (secsFromIssue > argv.token_exp_mins * 60) {
iatTime = parseInt(Date.now() / 1000);
console.log(`\tRefreshing token after ${secsFromIssue} seconds.`);

authToken = createJwt(argv.project_id, argv.private_key_file, argv.algorithm);
}

publishAsync(messageCount + 1, numMessages);
}, delayMs);
}
Expand All @@ -161,7 +175,8 @@ const devicePath = `projects/${argv.project_id}/locations/${argv.cloud_region}/r
const pathSuffix = argv.message_type === 'events'
? ':publishEvent' : ':setState';
const url = `https://${argv.http_bridge_address}/v1beta1/${devicePath}${pathSuffix}`;
const authToken = createJwt(argv.project_id, argv.private_key_file, argv.algorithm);
let iatTime = parseInt(Date.now() / 1000);
let authToken = createJwt(argv.project_id, argv.private_key_file, argv.algorithm);

// Publish messages.
publishAsync(1, argv.num_messages);
Expand Down

0 comments on commit 8e2b651

Please sign in to comment.