Created
February 23, 2021 20:37
-
-
Save dzhavat/ae3bda9b997680834a6f4cdcedc89e09 to your computer and use it in GitHub Desktop.
Timer triggered Azure Function for renewing an access token
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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