Commit 8620bf98 authored by Robert Knight's avatar Robert Knight Committed by GitHub

Merge pull request #219 from hypothesis/dont-reuse-oauth-grant-tokens

Don't reuse OAuth grant tokens
parents 7f75f29e d0bfcce7
......@@ -16,11 +16,6 @@ function auth($http, settings) {
var cachedToken;
var tokenUrl = resolve('token', settings.apiUrl);
var grantToken;
if (Array.isArray(settings.services) && settings.services.length > 0) {
grantToken = settings.services[0].grantToken;
}
// Exchange the JWT grant token for an access token.
// See https://tools.ietf.org/html/rfc7523#section-4
function exchangeToken(grantToken) {
......@@ -41,21 +36,25 @@ function auth($http, settings) {
}
function tokenGetter() {
// performance.now() is used instead of Date.now() because it is
// monotonically increasing.
if (cachedToken && cachedToken.expiresAt > performance.now()) {
if (cachedToken) {
return Promise.resolve(cachedToken.token);
} else if (grantToken) {
var refreshStart = performance.now();
} else {
var grantToken;
if (Array.isArray(settings.services) && settings.services.length > 0) {
grantToken = settings.services[0].grantToken;
}
if (!grantToken) {
return Promise.resolve(null);
}
return exchangeToken(grantToken).then(function (tokenInfo) {
cachedToken = {
token: tokenInfo.access_token,
expiresAt: refreshStart + tokenInfo.expires_in * 1000,
};
return cachedToken.token;
});
} else {
return Promise.resolve(null);
}
}
......
......@@ -84,22 +84,5 @@ describe('oauth auth', function () {
assert.equal(token, null);
});
});
it('should refresh the access token if it has expired', function () {
return auth.tokenGetter().then(function () {
var now = performance.now();
nowStub.returns(now + DEFAULT_TOKEN_EXPIRES_IN_SECS * 1000 + 100);
fakeHttp.post.returns(Promise.resolve({
status: 200,
data: {
access_token: 'a-different-access-token',
expires_in: DEFAULT_TOKEN_EXPIRES_IN_SECS,
},
}));
return auth.tokenGetter();
}).then(function (token) {
assert.equal(token, 'a-different-access-token');
});
});
});
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment