Skip to content
This repository has been archived by the owner on Sep 20, 2024. It is now read-only.

Add feature: refresh MSTeams token before it expires #1230

Merged
merged 10 commits into from Jan 29, 2018
63 changes: 63 additions & 0 deletions __test__/lib/Teams.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
'use strict';
let teamsBot;
let teamsApi;
let config = {
clientId: 'client',
clientSecret: 'secret',
debug: false
};

describe('authentication', () => {
beforeEach(() => {
jest.doMock('../../lib/TeamsAPI', () => {
return jest.fn((configuration) => {
return {
getToken: jest.fn((cb) => {
configuration.token = 'token';
configuration.token_expires_in = '3600';
cb(null);
})
};
});
});

jest.useFakeTimers();
teamsApi = require('../../lib/TeamsAPI');
});

afterEach(() => {
jest.resetModules();
jest.clearAllTimers();
});

test('get token', () => {
let bot = require('../../lib/Teams')(config);
expect(bot.api.getToken).toHaveBeenCalledTimes(1);
});

test('refresh token before expiry', () => {
let bot = require('../../lib/Teams')(config);
expect(bot.api.getToken).toHaveBeenCalledTimes(1);
jest.runOnlyPendingTimers();
expect(bot.api.getToken).toHaveBeenCalledTimes(2);
});

test('token valid for 20 mins should refresh after 10 mins', () => {
teamsApi.mockImplementation(jest.fn((configuration) => {
return {
getToken: jest.fn((cb) => {
configuration.token = 'token';
configuration.token_expires_in = '1200';
cb(null);
})
};
}));
let bot = require('../../lib/Teams')(config);
expect(bot.config.token_expires_in).toBe('1200');
expect(bot.api.getToken).toHaveBeenCalledTimes(1);
jest.runTimersToTime(1000 * 60 * 9);
expect(bot.api.getToken).toHaveBeenCalledTimes(1);
jest.runTimersToTime(1000 * 60 * 1.1);
expect(bot.api.getToken).toHaveBeenCalledTimes(2);
});
});
11 changes: 7 additions & 4 deletions lib/Teams.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,17 @@ function TeamsBot(configuration) {
var controller = Botkit(configuration || {});

controller.api = TeamsAPI(configuration || {});

controller.api.getToken(function(err) {
function tokenHandler(err) {
if (err) {
// this is a fatal error - could not create a Teams API client
throw new Error(err);
}
});

//use the expires_in value, convert to ms and remove 10 mins in ms
let tokenExpiresIn = (configuration.token_expires_in || 3600) * 1000;
let expiryCheckDelta = 1000 * 60 * 10;
setTimeout(controller.api.getToken, (tokenExpiresIn - expiryCheckDelta), tokenHandler);
};
controller.api.getToken(tokenHandler);

controller.defineBot(function(botkit, config) {
var bot = {
Expand Down
1 change: 1 addition & 0 deletions lib/TeamsAPI.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ module.exports = function(configuration) {
return cb(json.error_description);
}
configuration.token = json.access_token;
configuration.token_expires_in = json.expires_in;
cb(null);
}
}
Expand Down