Commit 0f6b5194 authored by robliao@chromium.org's avatar robliao@chromium.org

Revert of Convert Google Now's Authentication Manager to use Promises...

Revert of Convert Google Now's Authentication Manager to use Promises (https://codereview.chromium.org/162273002/)

Reason for revert:
Promise.catch may not always be called back, breaking an assumption about the task tracking system.

Original issue's description:
> Convert Google Now's Authentication Manager to use Promises
> 
> BUG=164227
> R=rgustafson@chromium.org, skare@chromium.org, vadimt@chromium.org
> 
> Committed: https://src.chromium.org/viewvc/chrome?view=rev&revision=252109

TBR=skare@chromium.org,rgustafson@chromium.org,vadimt@chromium.org
NOTREECHECKS=true
NOTRY=true
BUG=164227

Review URL: https://codereview.chromium.org/171713007

git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252134 0039d316-1c4b-4281-b951-d872f2087c98
parent 6ca44200
...@@ -265,7 +265,12 @@ function recordEvent(event) { ...@@ -265,7 +265,12 @@ function recordEvent(event) {
* parameter. * parameter.
*/ */
function setAuthorization(request, callbackBoolean) { function setAuthorization(request, callbackBoolean) {
authenticationManager.getAuthToken().then(function(token) { authenticationManager.getAuthToken(function(token) {
if (!token) {
callbackBoolean(false);
return;
}
request.setRequestHeader('Authorization', 'Bearer ' + token); request.setRequestHeader('Authorization', 'Bearer ' + token);
// Instrument onloadend to remove stale auth tokens. // Instrument onloadend to remove stale auth tokens.
...@@ -273,7 +278,7 @@ function setAuthorization(request, callbackBoolean) { ...@@ -273,7 +278,7 @@ function setAuthorization(request, callbackBoolean) {
request.onloadend = wrapper.wrapCallback(function(event) { request.onloadend = wrapper.wrapCallback(function(event) {
if (request.status == HTTP_FORBIDDEN || if (request.status == HTTP_FORBIDDEN ||
request.status == HTTP_UNAUTHORIZED) { request.status == HTTP_UNAUTHORIZED) {
authenticationManager.removeToken(token).then(function() { authenticationManager.removeToken(token, function() {
originalOnLoadEnd(event); originalOnLoadEnd(event);
}); });
} else { } else {
...@@ -282,8 +287,6 @@ function setAuthorization(request, callbackBoolean) { ...@@ -282,8 +287,6 @@ function setAuthorization(request, callbackBoolean) {
}); });
callbackBoolean(true); callbackBoolean(true);
}).catch(function() {
callbackBoolean(false);
}); });
} }
...@@ -1085,7 +1088,7 @@ function updateRunningState( ...@@ -1085,7 +1088,7 @@ function updateRunningState(
function onStateChange() { function onStateChange() {
tasks.add(STATE_CHANGED_TASK_NAME, function() { tasks.add(STATE_CHANGED_TASK_NAME, function() {
Promise.all([ Promise.all([
authenticationManager.isSignedIn(), isSignedIn(),
isGeolocationEnabled(), isGeolocationEnabled(),
canEnableBackground(), canEnableBackground(),
isNotificationsEnabled(), isNotificationsEnabled(),
...@@ -1096,6 +1099,18 @@ function onStateChange() { ...@@ -1096,6 +1099,18 @@ function onStateChange() {
}); });
} }
/**
* Determines if the user is signed in.
* @return {Promise} A promise to evaluate the signed in state.
*/
function isSignedIn() {
return new Promise(function(resolve) {
authenticationManager.isSignedIn(function(signedIn) {
resolve(signedIn);
});
});
}
/** /**
* Gets the geolocation enabled preference. * Gets the geolocation enabled preference.
* @return {Promise} A promise to get the geolocation enabled preference. * @return {Promise} A promise to get the geolocation enabled preference.
......
...@@ -70,7 +70,6 @@ function mockInitializeDependencies(fixture) { ...@@ -70,7 +70,6 @@ function mockInitializeDependencies(fixture) {
'instrumented.notifications.getPermissionLevel', 'instrumented.notifications.getPermissionLevel',
'instrumented.preferencesPrivate.googleGeolocationAccessEnabled.get', 'instrumented.preferencesPrivate.googleGeolocationAccessEnabled.get',
'instrumented.storage.local.get', 'instrumented.storage.local.get',
'instrumented.webstorePrivate.getBrowserLogin',
'tasks.add', 'tasks.add',
'updateCardsAttempts.isRunning', 'updateCardsAttempts.isRunning',
'updateCardsAttempts.stop' 'updateCardsAttempts.stop'
...@@ -100,11 +99,14 @@ function expectStateMachineCalls( ...@@ -100,11 +99,14 @@ function expectStateMachineCalls(
testExperimentVariationParams, testExperimentVariationParams,
testNotificationPermissionLevel, testNotificationPermissionLevel,
testGoogleNowEnabled) { testGoogleNowEnabled) {
var authenticationManagerIsSignedInSavedArgs = new SaveMockArguments();
fixture.mockApis.expects(once()). fixture.mockApis.expects(once()).
authenticationManager_isSignedIn(). authenticationManager_isSignedIn(
will(returnValue(new Promise(function(resolve) { authenticationManagerIsSignedInSavedArgs.match(ANYTHING)).
resolve(!!testIdentityToken); will(invokeCallback(
}))); authenticationManagerIsSignedInSavedArgs,
0,
testIdentityToken));
var getVariationParamsSavedArgs = new SaveMockArguments(); var getVariationParamsSavedArgs = new SaveMockArguments();
fixture.mockApis.expects(once()). fixture.mockApis.expects(once()).
...@@ -131,13 +133,13 @@ function expectStateMachineCalls( ...@@ -131,13 +133,13 @@ function expectStateMachineCalls(
0, 0,
testNotificationPermissionLevel)) testNotificationPermissionLevel))
var storageGetSavedArgs = new SaveMockArguments(); var storageGetSavedArgs = new SaveMockArguments();
fixture.mockApis.expects(once()). fixture.mockApis.expects(once()).
instrumented_storage_local_get( instrumented_storage_local_get(
storageGetSavedArgs.match(eq('googleNowEnabled')), storageGetSavedArgs.match(eq('googleNowEnabled')),
storageGetSavedArgs.match(ANYTHING)). storageGetSavedArgs.match(ANYTHING)).
will(invokeCallback( will(invokeCallback(
storageGetSavedArgs, 1, {googleNowEnabled: testGoogleNowEnabled})); storageGetSavedArgs, 1, {googleNowEnabled: testGoogleNowEnabled}));
fixture.mockGlobals.expects(once()). fixture.mockGlobals.expects(once()).
setBackgroundEnable(ANYTHING); setBackgroundEnable(ANYTHING);
...@@ -595,7 +597,7 @@ TEST_F( ...@@ -595,7 +597,7 @@ TEST_F(
// Check the output value. // Check the output value.
var expectedCombinedCards = { var expectedCombinedCards = {
'EXISTING CARD': [ 'EXISTING CARD': [
1, 1,
{ {
receivedNotification: receivedNotificationNoShowTime, receivedNotification: receivedNotificationNoShowTime,
hideTime: 11000 hideTime: 11000
......
...@@ -82,35 +82,16 @@ function getMockHandlerContainer(eventIdentifier) { ...@@ -82,35 +82,16 @@ function getMockHandlerContainer(eventIdentifier) {
var Promise = function() { var Promise = function() {
function PromisePrototypeObject(asyncTask) { function PromisePrototypeObject(asyncTask) {
var result; var result;
var resolved = false;
asyncTask( asyncTask(
function(asyncResult) { function(asyncResult) {
result = asyncResult; result = asyncResult;
resolved = true;
}, },
function(asyncFailureResult) { function() {}); // Errors are unsupported.
result = asyncFailureResult;
resolved = false;
});
function then(callback) { function then(callback) {
if (resolved) { callback.call(null, result);
callback.call(null, result);
}
return this;
}
// Promises use the function name "catch" to call back error handlers.
// We can't use "catch" since function or variable names cannot use the word
// "catch".
function catchFunc(callback) {
if (!resolved) {
callback.call(null, result);
}
return this;
} }
return {then: then, isPromise: true};
return {then: then, catch: catchFunc, isPromise: true};
} }
function all(arrayOfPromises) { function all(arrayOfPromises) {
......
...@@ -437,24 +437,13 @@ wrapper.instrumentChromeApiFunction('identity.removeCachedAuthToken', 1); ...@@ -437,24 +437,13 @@ wrapper.instrumentChromeApiFunction('identity.removeCachedAuthToken', 1);
wrapper.instrumentChromeApiFunction('webstorePrivate.getBrowserLogin', 0); wrapper.instrumentChromeApiFunction('webstorePrivate.getBrowserLogin', 0);
/** /**
* Add task tracking support to Promise.then. * Add task tracking support to Promises.
* @override * @override
*/ */
Promise.prototype.then = function() { Promise.prototype.then = function() {
var originalThen = Promise.prototype.then; var originalThen = Promise.prototype.then;
return function(callback) { return function(callback) {
return originalThen.call(this, wrapper.wrapCallback(callback, false)); originalThen.call(this, wrapper.wrapCallback(callback, false));
}
}();
/**
* Add task tracking support to Promise.catch.
* @override
*/
Promise.prototype.catch = function() {
var originalCatch = Promise.prototype.catch;
return function(callback) {
return originalCatch.call(this, wrapper.wrapCallback(callback, false));
} }
}(); }();
...@@ -737,46 +726,36 @@ function buildAuthenticationManager() { ...@@ -737,46 +726,36 @@ function buildAuthenticationManager() {
/** /**
* Gets an OAuth2 access token. * Gets an OAuth2 access token.
* @return {Promise} A promise to get the authentication token. If there is * @param {function(string=)} callback Called on completion.
* no token, the request is rejected. * The string contains the token. It's undefined if there was an error.
*/ */
function getAuthToken() { function getAuthToken(callback) {
return new Promise(function(resolve, reject) { instrumented.identity.getAuthToken({interactive: false}, function(token) {
instrumented.identity.getAuthToken({interactive: false}, function(token) { token = chrome.runtime.lastError ? undefined : token;
if (chrome.runtime.lastError || !token) { callback(token);
reject();
} else {
resolve(token);
}
});
}); });
} }
/** /**
* Determines whether there is an account attached to the profile. * Determines whether there is an account attached to the profile.
* @return {Promise} A promise to determine if there is an account attached * @param {function(boolean)} callback Called on completion.
* to the profile.
*/ */
function isSignedIn() { function isSignedIn(callback) {
return new Promise(function(resolve) { instrumented.webstorePrivate.getBrowserLogin(function(accountInfo) {
instrumented.webstorePrivate.getBrowserLogin(function(accountInfo) { callback(!!accountInfo.login);
resolve(!!accountInfo.login);
});
}); });
} }
/** /**
* Removes the specified cached token. * Removes the specified cached token.
* @param {string} token Authentication Token to remove from the cache. * @param {string} token Authentication Token to remove from the cache.
* @return {Promise} A promise that resolves on completion. * @param {function()} callback Called on completion.
*/ */
function removeToken(token) { function removeToken(token, callback) {
return new Promise(function(resolve) { instrumented.identity.removeCachedAuthToken({token: token}, function() {
instrumented.identity.removeCachedAuthToken({token: token}, function() { // Let Chrome now about a possible problem with the token.
// Let Chrome know about a possible problem with the token. getAuthToken(function() {});
getAuthToken(); callback();
resolve();
});
}); });
} }
...@@ -796,7 +775,7 @@ function buildAuthenticationManager() { ...@@ -796,7 +775,7 @@ function buildAuthenticationManager() {
* If it doesn't, it notifies the listeners of the change. * If it doesn't, it notifies the listeners of the change.
*/ */
function checkAndNotifyListeners() { function checkAndNotifyListeners() {
isSignedIn().then(function(signedIn) { isSignedIn(function(signedIn) {
instrumented.storage.local.get('lastSignedInState', function(items) { instrumented.storage.local.get('lastSignedInState', function(items) {
items = items || {}; items = items || {};
if (items.lastSignedInState != signedIn) { if (items.lastSignedInState != signedIn) {
......
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