Skip to content

Instantly share code, notes, and snippets.

@dzhavat
Created February 23, 2021 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dzhavat/ae3bda9b997680834a6f4cdcedc89e09 to your computer and use it in GitHub Desktop.
Save dzhavat/ae3bda9b997680834a6f4cdcedc89e09 to your computer and use it in GitHub Desktop.
Timer triggered Azure Function for renewing an access token
const fetch = require("node-fetch");
const azure = require('azure-storage');
module.exports = function (context, myTimer) {
const tableService = azure.createTableService();
const query = new azure.TableQuery()
.where("RowKey eq 'ClientID' or RowKey eq 'ClientSecret' or RowKey eq 'RefreshToken'");
tableService.queryEntities('<table-name-here>', query, null, function(error, result, response) {
if (!error) {
const grantType = 'refresh_token';
let clientID, refreshToken, clientSecret;
result.entries.forEach(item => {
if (item.RowKey._ === 'ClientID') {
clientID = item.Value._;
} else if (item.RowKey._ === 'ClientSecret') {
clientSecret = item.Value._;
} else if (item.RowKey._ === 'RefreshToken') {
refreshToken = item.Value._;
}
});
const queries = `client_id=${clientID}&client_secret=${clientSecret}&refresh_token=${refreshToken}&grant_type=${grantType}`;
const url = `https://www.strava.com/oauth/token?${queries}`;
fetch(url, { method: 'POST' })
.then(response => response.json())
.then(response => {
const updateRefreshToken = {
PartitionKey: { '_': 'Token' },
RowKey: { '_': 'RefreshToken' },
Value: { '_': response.refresh_token }
};
const updateAccessToken = {
PartitionKey: { '_': 'Token' },
RowKey: { '_': 'AccessToken' },
Value: { '_': response.access_token }
};
const batch = new azure.TableBatch();
batch.replaceEntity(updateRefreshToken);
batch.replaceEntity(updateAccessToken);
tableService.executeBatch('<table-name-here>', batch, function(error, result, response) {
context.done();
});
})
.catch(() => context.done());
} else {
context.done()
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment