Convert gr-auth to class and use new API for auth check

auth-check API is available since: https://gerrit-review.googlesource.com/c/gerrit/+/185990

Change-Id: Icd5e0183ee42e746c32bfd7929af9796ab752627
This commit is contained in:
Tao Zhou
2020-01-09 13:59:45 +01:00
parent a72096e146
commit 4761e3f3d0
10 changed files with 758 additions and 564 deletions

View File

@@ -324,7 +324,11 @@ limitations under the License.
element.handleEvent(element.EventType.HIGHLIGHTJS_LOADED, {hljs: testHljs});
});
test('getAccount', done => {
test('getLoggedIn', done => {
// fake fetch for authCheck
sandbox.stub(window, 'fetch', () => {
return Promise.resolve({status: 204});
});
plugin.restApi().getLoggedIn().then(loggedIn => {
assert.isTrue(loggedIn);
done();

View File

@@ -20,22 +20,86 @@
// Prevent redefinition.
if (window.Gerrit.Auth) { return; }
const MAX_AUTH_CHECK_WAIT_TIME_MS = 1000 * 30; // 30s
const MAX_GET_TOKEN_RETRIES = 2;
Gerrit.Auth = {
TYPE: {
XSRF_TOKEN: 'xsrf_token',
ACCESS_TOKEN: 'access_token',
},
/**
* Auth class.
*
* Gerrit.Auth is an instance of this class.
*/
class Auth {
constructor() {
this._type = null;
this._cachedTokenPromise = null;
this._defaultOptions = {};
this._retriesLeft = MAX_GET_TOKEN_RETRIES;
this._status = Auth.STATUS.UNDETERMINED;
this._authCheckPromise = null;
this._last_auth_check_time = Date.now();
}
_type: null,
_cachedTokenPromise: null,
_defaultOptions: {},
_retriesLeft: MAX_GET_TOKEN_RETRIES,
/**
* Returns if user is authed or not.
*
* @returns {!Promise<boolean>}
*/
authCheck() {
if (!this._authCheckPromise ||
(Date.now() - this._last_auth_check_time > MAX_AUTH_CHECK_WAIT_TIME_MS)
) {
// Refetch after last check expired
this._authCheckPromise = fetch('/auth-check');
this._last_auth_check_time = Date.now();
}
return this._authCheckPromise.then(res => {
// auth-check will return 204 if authed
// treat the rest as unauthed
if (res.status === 204) {
this._setStatus(Auth.STATUS.AUTHED);
return true;
} else {
this._setStatus(Auth.STATUS.NOT_AUTHED);
return false;
}
}).catch(e => {
this._setStatus(Auth.STATUS.ERROR);
// Reset _authCheckPromise to avoid caching the failed promise
this._authCheckPromise = null;
return false;
});
}
clearCache() {
this._authCheckPromise = null;
}
/**
* @param {string} status
*/
_setStatus(status) {
if (this._status === status) return;
if (this._status === Auth.STATUS.AUTHED) {
Gerrit.emit('auth-error', {
message: Auth.CREDS_EXPIRED_MSG, action: 'Refresh credentials',
});
}
this._status = status;
}
get status() {
return this._status;
}
get isAuthed() {
return this._status === Auth.STATUS.AUTHED;
}
_getToken() {
return Promise.resolve(this._cachedTokenPromise);
},
}
/**
* Enable cross-domain authentication using OAuth access token.
@@ -51,7 +115,7 @@
setup(getToken, defaultOptions) {
this._retriesLeft = MAX_GET_TOKEN_RETRIES;
if (getToken) {
this._type = Gerrit.Auth.TYPE.ACCESS_TOKEN;
this._type = Auth.TYPE.ACCESS_TOKEN;
this._cachedTokenPromise = null;
this._getToken = getToken;
}
@@ -61,7 +125,7 @@
this._defaultOptions[p] = defaultOptions[p];
}
}
},
}
/**
* Perform network fetch with authentication.
@@ -74,7 +138,7 @@
const options = Object.assign({
headers: new Headers(),
}, this._defaultOptions, opt_options);
if (this._type === Gerrit.Auth.TYPE.ACCESS_TOKEN) {
if (this._type === Auth.TYPE.ACCESS_TOKEN) {
return this._getAccessToken().then(
accessToken =>
this._fetchWithAccessToken(url, options, accessToken)
@@ -82,7 +146,7 @@
} else {
return this._fetchWithXsrfToken(url, options);
}
},
}
_getCookie(name) {
const key = name + '=';
@@ -95,7 +159,7 @@
}
});
return result;
},
}
_isTokenValid(token) {
if (!token) { return false; }
@@ -105,7 +169,7 @@
if (Date.now() >= expiration.getTime()) { return false; }
return true;
},
}
_fetchWithXsrfToken(url, options) {
if (options.method && options.method !== 'GET') {
@@ -116,7 +180,7 @@
}
options.credentials = 'same-origin';
return fetch(url, options);
},
}
/**
* @return {!Promise<string>}
@@ -138,7 +202,7 @@
// Fall back to anonymous access.
return null;
});
},
}
_fetchWithAccessToken(url, options, accessToken) {
const params = [];
@@ -180,8 +244,24 @@
url = url + (url.indexOf('?') === -1 ? '?' : '&') + params.join('&');
}
return fetch(url, options);
},
}
}
Auth.TYPE = {
XSRF_TOKEN: 'xsrf_token',
ACCESS_TOKEN: 'access_token',
};
window.Gerrit.Auth = Gerrit.Auth;
Auth.STATUS = {
UNDETERMINED: 0,
AUTHED: 1,
NOT_AUTHED: 2,
ERROR: 3,
};
Auth.CREDS_EXPIRED_MSG = 'Credentails expired.';
// TODO(taoalpha): this whole thing should be moved to a service
window.Auth = Auth;
Gerrit.Auth = new Auth();
})(window);

View File

@@ -35,7 +35,6 @@ limitations under the License.
setup(() => {
sandbox = sinon.sandbox.create();
sandbox.stub(window, 'fetch').returns(Promise.resolve({ok: true}));
auth = Gerrit.Auth;
});
@@ -43,29 +42,222 @@ limitations under the License.
sandbox.restore();
});
suite('default (xsrf token header)', () => {
test('GET', () => {
return auth.fetch('/url', {bar: 'bar'}).then(() => {
const [url, options] = fetch.lastCall.args;
assert.equal(url, '/url');
assert.equal(options.credentials, 'same-origin');
suite('Auth class methods', () => {
let fakeFetch;
setup(() => {
auth = new Auth();
fakeFetch = sandbox.stub(window, 'fetch');
});
test('auth-check returns 403', done => {
fakeFetch.returns(Promise.resolve({status: 403}));
auth.authCheck().then(authed => {
assert.isFalse(authed);
assert.equal(auth.status, Auth.STATUS.NOT_AUTHED);
done();
});
});
test('POST', () => {
test('auth-check returns 204', done => {
fakeFetch.returns(Promise.resolve({status: 204}));
auth.authCheck().then(authed => {
assert.isTrue(authed);
assert.equal(auth.status, Auth.STATUS.AUTHED);
done();
});
});
test('auth-check returns 502', done => {
fakeFetch.returns(Promise.resolve({status: 502}));
auth.authCheck().then(authed => {
assert.isFalse(authed);
assert.equal(auth.status, Auth.STATUS.NOT_AUTHED);
done();
});
});
test('auth-check failed', done => {
fakeFetch.returns(Promise.reject(new Error('random error')));
auth.authCheck().then(authed => {
assert.isFalse(authed);
assert.equal(auth.status, Auth.STATUS.ERROR);
done();
});
});
});
suite('cache and events behaivor', () => {
let fakeFetch;
let clock;
setup(() => {
auth = new Auth();
clock = sinon.useFakeTimers();
fakeFetch = sandbox.stub(window, 'fetch');
});
test('cache auth-check result', done => {
fakeFetch.returns(Promise.resolve({status: 403}));
auth.authCheck().then(authed => {
assert.isFalse(authed);
assert.equal(auth.status, Auth.STATUS.NOT_AUTHED);
fakeFetch.returns(Promise.resolve({status: 204}));
auth.authCheck().then(authed2 => {
assert.isFalse(authed);
assert.equal(auth.status, Auth.STATUS.NOT_AUTHED);
done();
});
});
});
test('clearCache should refetch auth-check result', done => {
fakeFetch.returns(Promise.resolve({status: 403}));
auth.authCheck().then(authed => {
assert.isFalse(authed);
assert.equal(auth.status, Auth.STATUS.NOT_AUTHED);
fakeFetch.returns(Promise.resolve({status: 204}));
auth.clearCache();
auth.authCheck().then(authed2 => {
assert.isTrue(authed2);
assert.equal(auth.status, Auth.STATUS.AUTHED);
done();
});
});
});
test('cache expired on auth-check after certain time', done => {
fakeFetch.returns(Promise.resolve({status: 403}));
auth.authCheck().then(authed => {
assert.isFalse(authed);
assert.equal(auth.status, Auth.STATUS.NOT_AUTHED);
clock.tick(1000 * 10000);
fakeFetch.returns(Promise.resolve({status: 204}));
auth.authCheck().then(authed2 => {
assert.isTrue(authed2);
assert.equal(auth.status, Auth.STATUS.AUTHED);
done();
});
});
});
test('no cache if auth-check failed', done => {
fakeFetch.returns(Promise.reject(new Error('random error')));
auth.authCheck().then(authed => {
assert.isFalse(authed);
assert.equal(auth.status, Auth.STATUS.ERROR);
assert.equal(fakeFetch.callCount, 1);
auth.authCheck().then(() => {
assert.equal(fakeFetch.callCount, 2);
done();
});
});
});
test('fire event when switch from authed to unauthed', done => {
fakeFetch.returns(Promise.resolve({status: 204}));
auth.authCheck().then(authed => {
assert.isTrue(authed);
assert.equal(auth.status, Auth.STATUS.AUTHED);
clock.tick(1000 * 10000);
fakeFetch.returns(Promise.resolve({status: 403}));
const emitStub = sinon.stub();
Gerrit.emit = emitStub;
auth.authCheck().then(authed2 => {
assert.isFalse(authed2);
assert.equal(auth.status, Auth.STATUS.NOT_AUTHED);
assert.isTrue(emitStub.called);
done();
});
});
});
test('fire event when switch from authed to error', done => {
fakeFetch.returns(Promise.resolve({status: 204}));
auth.authCheck().then(authed => {
assert.isTrue(authed);
assert.equal(auth.status, Auth.STATUS.AUTHED);
clock.tick(1000 * 10000);
fakeFetch.returns(Promise.reject(new Error('random error')));
const emitStub = sinon.stub();
Gerrit.emit = emitStub;
auth.authCheck().then(authed2 => {
assert.isFalse(authed2);
assert.isTrue(emitStub.called);
assert.equal(auth.status, Auth.STATUS.ERROR);
done();
});
});
});
test('no event from non-authed to other status', done => {
fakeFetch.returns(Promise.resolve({status: 403}));
auth.authCheck().then(authed => {
assert.isFalse(authed);
assert.equal(auth.status, Auth.STATUS.NOT_AUTHED);
clock.tick(1000 * 10000);
fakeFetch.returns(Promise.resolve({status: 204}));
const emitStub = sinon.stub();
Gerrit.emit = emitStub;
auth.authCheck().then(authed2 => {
assert.isTrue(authed2);
assert.isFalse(emitStub.called);
assert.equal(auth.status, Auth.STATUS.AUTHED);
done();
});
});
});
test('no event from non-authed to other status', done => {
fakeFetch.returns(Promise.resolve({status: 403}));
auth.authCheck().then(authed => {
assert.isFalse(authed);
assert.equal(auth.status, Auth.STATUS.NOT_AUTHED);
clock.tick(1000 * 10000);
fakeFetch.returns(Promise.reject(new Error('random error')));
const emitStub = sinon.stub();
Gerrit.emit = emitStub;
auth.authCheck().then(authed2 => {
assert.isFalse(authed2);
assert.isFalse(emitStub.called);
assert.equal(auth.status, Auth.STATUS.ERROR);
done();
});
});
});
});
suite('default (xsrf token header)', () => {
setup(() => {
sandbox.stub(window, 'fetch').returns(Promise.resolve({ok: true}));
});
test('GET', done => {
auth.fetch('/url', {bar: 'bar'}).then(() => {
const [url, options] = fetch.lastCall.args;
assert.equal(url, '/url');
assert.equal(options.credentials, 'same-origin');
done();
});
});
test('POST', done => {
sandbox.stub(auth, '_getCookie')
.withArgs('XSRF_TOKEN')
.returns('foobar');
return auth.fetch('/url', {method: 'POST'}).then(() => {
auth.fetch('/url', {method: 'POST'}).then(() => {
const [url, options] = fetch.lastCall.args;
assert.equal(url, '/url');
assert.equal(options.credentials, 'same-origin');
assert.equal(options.headers.get('X-Gerrit-Auth'), 'foobar');
done();
});
});
});
suite('cors (access token)', () => {
setup(() => {
sandbox.stub(window, 'fetch').returns(Promise.resolve({ok: true}));
});
let getToken;
const makeToken = opt_accessToken => {
@@ -81,62 +273,68 @@ limitations under the License.
auth.setup(getToken);
});
test('base url support', () => {
test('base url support', done => {
const baseUrl = 'http://foo';
sandbox.stub(Gerrit.BaseUrlBehavior, 'getBaseUrl').returns(baseUrl);
return auth.fetch(baseUrl + '/url', {bar: 'bar'}).then(() => {
auth.fetch(baseUrl + '/url', {bar: 'bar'}).then(() => {
const [url] = fetch.lastCall.args;
assert.equal(url, 'http://foo/a/url?access_token=zbaz');
done();
});
});
test('fetch not signed in', () => {
test('fetch not signed in', done => {
getToken.returns(Promise.resolve());
return auth.fetch('/url', {bar: 'bar'}).then(() => {
auth.fetch('/url', {bar: 'bar'}).then(() => {
const [url, options] = fetch.lastCall.args;
assert.equal(url, '/url');
assert.equal(options.bar, 'bar');
assert.equal(Object.keys(options.headers).length, 0);
done();
});
});
test('fetch signed in', () => {
return auth.fetch('/url', {bar: 'bar'}).then(() => {
test('fetch signed in', done => {
auth.fetch('/url', {bar: 'bar'}).then(() => {
const [url, options] = fetch.lastCall.args;
assert.equal(url, '/a/url?access_token=zbaz');
assert.equal(options.bar, 'bar');
done();
});
});
test('getToken calls are cached', () => {
return Promise.all([
test('getToken calls are cached', done => {
Promise.all([
auth.fetch('/url-one'), auth.fetch('/url-two')]).then(() => {
assert.equal(getToken.callCount, 1);
done();
});
});
test('getToken refreshes token', () => {
test('getToken refreshes token', done => {
sandbox.stub(auth, '_isTokenValid');
auth._isTokenValid
.onFirstCall().returns(true)
.onSecondCall().returns(false)
.onThirdCall().returns(true);
return auth.fetch('/url-one').then(() => {
auth.fetch('/url-one').then(() => {
getToken.returns(Promise.resolve(makeToken('bzzbb')));
return auth.fetch('/url-two');
}).then(() => {
const [[firstUrl], [secondUrl]] = fetch.args;
assert.equal(firstUrl, '/a/url-one?access_token=zbaz');
assert.equal(secondUrl, '/a/url-two?access_token=bzzbb');
done();
});
});
test('signed in token error falls back to anonymous', () => {
test('signed in token error falls back to anonymous', done => {
getToken.returns(Promise.resolve('rubbish'));
return auth.fetch('/url', {bar: 'bar'}).then(() => {
auth.fetch('/url', {bar: 'bar'}).then(() => {
const [url, options] = fetch.lastCall.args;
assert.equal(url, '/url');
assert.equal(options.bar, 'bar');
done();
});
});
@@ -154,12 +352,12 @@ limitations under the License.
}));
});
test('HTTP PUT with content type', () => {
test('HTTP PUT with content type', done => {
const originalOptions = {
method: 'PUT',
headers: new Headers({'Content-Type': 'mail/pigeon'}),
};
return auth.fetch('/url', originalOptions).then(() => {
auth.fetch('/url', originalOptions).then(() => {
assert.isTrue(getToken.called);
const [url, options] = fetch.lastCall.args;
assert.include(url, '$ct=mail%2Fpigeon');
@@ -167,14 +365,15 @@ limitations under the License.
assert.include(url, 'access_token=zbaz');
assert.equal(options.method, 'POST');
assert.equal(options.headers.get('Content-Type'), 'text/plain');
done();
});
});
test('HTTP PUT without content type', () => {
test('HTTP PUT without content type', done => {
const originalOptions = {
method: 'PUT',
};
return auth.fetch('/url', originalOptions).then(() => {
auth.fetch('/url', originalOptions).then(() => {
assert.isTrue(getToken.called);
const [url, options] = fetch.lastCall.args;
assert.include(url, '$ct=text%2Fplain');
@@ -182,6 +381,7 @@ limitations under the License.
assert.include(url, 'access_token=zbaz');
assert.equal(options.method, 'POST');
assert.equal(options.headers.get('Content-Type'), 'text/plain');
done();
});
});
});

View File

@@ -66,12 +66,6 @@
* @event network-error
*/
/**
* Fired when credentials were rejected by server (e.g. expired).
*
* @event auth-error
*/
/**
* Fired after an RPC completes.
*
@@ -89,10 +83,6 @@
type: Object,
value: new SiteBasedCache(), // Shared across instances.
},
_credentialCheck: {
type: Object,
value: {checking: false}, // Shared across instances.
},
_sharedFetchPromises: {
type: Object,
value: new FetchPromisesCache(), // Shared across instances.
@@ -112,40 +102,12 @@
type: Object,
value: {}, // Intentional to share the object across instances.
},
_auth: {
type: Object,
value: Gerrit.Auth, // Share across instances.
},
};
}
created() {
super.created();
/* Polymer 1 and Polymer 2 have slightly different lifecycle.
* Differences are not very well documented (see
* https://github.com/Polymer/old-docs-site/issues/2322).
* In Polymer 1, created() is called when properties values is not set
* and ready() is always called later, even if element is not added
* to a DOM. I.e. in Polymer 1 _cache and other properties are undefined,
* while in Polymer 2 they are set to default values.
* In Polymer 2, created() is called after properties values set and
* ready() is called only after element is attached to a DOM.
* There are several places in the code, where element is created with
* document.createElement('gr-rest-api-interface') and is not added
* to a DOM.
* In such cases, Polymer 1 calls both created() and ready() methods,
* but Polymer 2 calls only created() method.
* To workaround these differences, we should try to create _restApiHelper
* in both methods.
*/
//
this._initRestApiHelper();
}
ready() {
super.ready();
// See comments in created()
this._auth = Gerrit.Auth;
this._initRestApiHelper();
}
@@ -153,10 +115,9 @@
if (this._restApiHelper) {
return;
}
if (this._cache && this._auth && this._sharedFetchPromises &&
this._credentialCheck) {
if (this._cache && this._auth && this._sharedFetchPromises) {
this._restApiHelper = new GrRestApiHelper(this._cache, this._auth,
this._sharedFetchPromises, this._credentialCheck, this);
this._sharedFetchPromises, this);
}
}
@@ -850,11 +811,7 @@
}
getLoggedIn() {
return this.getAccount().then(account => {
return account != null;
}).catch(() => {
return false;
});
return this._auth.authCheck();
}
getIsAdmin() {
@@ -869,10 +826,6 @@
});
}
checkCredentials() {
return this._restApiHelper.checkCredentials();
}
getDefaultPreferences() {
return this._fetchSharedCacheURL({
url: '/config/server/preferences',
@@ -1347,6 +1300,10 @@
this._restApiHelper.invalidateFetchPromisesPrefix('/projects/?');
}
invalidateAccountsCache() {
this._restApiHelper.invalidateFetchPromisesPrefix('/accounts/');
}
/**
* @param {string} filter
* @param {number} groupsPerPage
@@ -2805,4 +2762,4 @@
}
customElements.define(GrRestApiInterface.is, GrRestApiInterface);
})();
})();

View File

@@ -48,8 +48,6 @@ limitations under the License.
window.CANONICAL_PATH = `test${ctr}`;
sandbox = sinon.sandbox.create();
element = fixture('basic');
element._projectLookup = {};
const testJSON = ')]}\'\n{"hello": "bonjour"}';
sandbox.stub(window, 'fetch').returns(Promise.resolve({
ok: true,
@@ -57,6 +55,10 @@ limitations under the License.
return Promise.resolve(testJSON);
},
}));
// fake auth
sandbox.stub(Gerrit.Auth, 'authCheck').returns(Promise.resolve(true));
element = fixture('basic');
element._projectLookup = {};
});
teardown(() => {
@@ -365,117 +367,6 @@ limitations under the License.
});
});
test('auth failure', done => {
const fakeAuthResponse = {
ok: false,
status: 403,
};
window.fetch.onFirstCall().returns(
Promise.reject(new Error('Failed to fetch')));
window.fetch.onSecondCall().returns(Promise.resolve(fakeAuthResponse));
// Emulate logged in.
element._restApiHelper._cache.set('/accounts/self/detail', {});
const serverErrorStub = sandbox.stub();
element.addEventListener('server-error', serverErrorStub);
const authErrorStub = sandbox.stub();
element.addEventListener('auth-error', authErrorStub);
element._restApiHelper.fetchJSON({url: '/bar'}).finally(r => {
flush(() => {
assert.isTrue(authErrorStub.called);
assert.isFalse(serverErrorStub.called);
assert.isFalse(element._cache.has('/accounts/self/detail'));
done();
});
});
});
test('auth failure - test all failed to fetch', done => {
window.fetch.returns(
Promise.reject(new Error('Failed to fetch')));
// Emulate logged in.
element._cache.set('/accounts/self/detail', {});
const serverErrorStub = sandbox.stub();
element.addEventListener('server-error', serverErrorStub);
const authErrorStub = sandbox.stub();
element.addEventListener('auth-error', authErrorStub);
element._restApiHelper.fetchJSON({url: '/bar'}).finally(r => {
flush(() => {
assert.isTrue(authErrorStub.called);
assert.isFalse(serverErrorStub.called);
assert.isFalse(element._cache.has('/accounts/self/detail'));
done();
});
});
});
test('getLoggedIn returns false when network/auth failure', done => {
window.fetch.returns(
Promise.reject(new Error('Failed to fetch')));
element.getLoggedIn().then(isLoggedIn => {
assert.isFalse(isLoggedIn);
done();
});
});
test('checkCredentials', done => {
const responses = [
{
ok: false,
status: 403,
text() { return Promise.resolve(); },
},
{
ok: true,
status: 200,
text() { return Promise.resolve(')]}\'{}'); },
},
];
window.fetch.restore();
sandbox.stub(window, 'fetch', url => {
if (url === window.CANONICAL_PATH + '/accounts/self/detail') {
return Promise.resolve(responses.shift());
}
});
element.getLoggedIn().then(account => {
assert.isNotOk(account);
element.checkCredentials().then(account => {
assert.isOk(account);
done();
});
});
});
test('checkCredentials promise rejection', () => {
window.fetch.restore();
element._cache.set('/accounts/self/detail', true);
const checkCredentialsSpy =
sandbox.spy(element._restApiHelper, 'checkCredentials');
sandbox.stub(window, 'fetch', url => {
return Promise.reject(new Error('Failed to fetch'));
});
return element.getConfig(true)
.catch(err => undefined)
.then(() => {
// When the top-level fetch call throws an error, it invokes
// checkCredentials, which in turn makes another fetch call.
// The second fetch call also fails, which leads to a second
// invocation of checkCredentials, which should immediately
// return instead of making further fetch calls.
assert.isTrue(checkCredentialsSpy .calledTwice);
assert.isTrue(window.fetch.calledTwice);
});
});
test('checkCredentials accepts only json', () => {
const authFetchStub = sandbox.stub(element._auth, 'fetch')
.returns(Promise.resolve());
element.checkCredentials();
assert.isTrue(authFetchStub.called);
assert.equal(authFetchStub.lastCall.args[1].headers.get('Accept'),
'application/json');
});
test('legacy n,z key in change url is replaced', () => {
const stub = sandbox.stub(element._restApiHelper, 'fetchJSON')
.returns(Promise.resolve([]));
@@ -922,6 +813,18 @@ limitations under the License.
assert.isFalse(element._cache.has(url));
});
test('invalidateAccountsCache', () => {
const url = '/accounts/self/detail';
element._cache.set(url, {});
element.invalidateAccountsCache();
assert.isUndefined(element._sharedFetchPromises[url]);
assert.isFalse(element._cache.has(url));
});
suite('getRepos', () => {
const defaultQuery = 'state%3Aactive%20OR%20state%3Aread-only';
let fetchCacheURLStub;

View File

@@ -18,7 +18,6 @@
'use strict';
const JSON_PREFIX = ')]}\'';
const FAILED_TO_FETCH_ERROR = 'Failed to fetch';
/**
* Wrapper around Map for caching server responses. Site-based so that
@@ -107,15 +106,13 @@
* @param {SiteBasedCache} cache
* @param {object} auth
* @param {FetchPromisesCache} fetchPromisesCache
* @param {object} credentialCheck
* @param {object} restApiInterface
*/
constructor(cache, auth, fetchPromisesCache, credentialCheck,
constructor(cache, auth, fetchPromisesCache,
restApiInterface) {
this._cache = cache;// TODO: make it public
this._auth = auth;
this._fetchPromisesCache = fetchPromisesCache;
this._credentialCheck = credentialCheck;
this._restApiInterface = restApiInterface;
}
@@ -190,15 +187,10 @@
}
return res;
}).catch(err => {
const isLoggedIn = !!this._cache.get('/accounts/self/detail');
if (isLoggedIn && err && err.message === FAILED_TO_FETCH_ERROR) {
this.checkCredentials();
if (req.errFn) {
req.errFn.call(undefined, null, err);
} else {
if (req.errFn) {
req.errFn.call(undefined, null, err);
} else {
this.fire('network-error', {error: err});
}
this.fire('network-error', {error: err});
}
throw err;
});
@@ -384,37 +376,6 @@
return xhr;
}
checkCredentials() {
if (this._credentialCheck.checking) {
return;
}
this._credentialCheck.checking = true;
let req = {url: '/accounts/self/detail', reportUrlAsIs: true};
req = this.addAcceptJsonHeader(req);
// Skip the REST response cache.
return this.fetchRawJSON(req).then(res => {
if (!res) { return; }
if (res.status === 403) {
this.fire('auth-error');
this._cache.delete('/accounts/self/detail');
} else if (res.ok) {
return this.getResponseObject(res);
}
}).then(res => {
this._credentialCheck.checking = false;
if (res) {
this._cache.set('/accounts/self/detail', res);
}
return res;
}).catch(err => {
this._credentialCheck.checking = false;
if (err && err.message === FAILED_TO_FETCH_ERROR) {
this.fire('auth-error');
this._cache.delete('/accounts/self/detail');
}
});
}
/**
* @param {string} prefix
*/
@@ -428,4 +389,3 @@
window.FetchPromisesCache = FetchPromisesCache;
window.GrRestApiHelper = GrRestApiHelper;
})(window);

View File

@@ -41,7 +41,6 @@ limitations under the License.
sandbox = sinon.sandbox.create();
cache = new SiteBasedCache();
fetchPromisesCache = new FetchPromisesCache();
const credentialCheck = {checking: false};
window.CANONICAL_PATH = 'testhelper';
@@ -59,7 +58,7 @@ limitations under the License.
}));
helper = new GrRestApiHelper(cache, Gerrit.Auth, fetchPromisesCache,
credentialCheck, mockRestApiInterface);
mockRestApiInterface);
});
teardown(() => {