Fix infinite recursion on hiding panel when created during fullscreen mode.
[chromium-blink-merge.git] / chrome / browser / resources / gaia_auth_host / gaia_auth_host.js
bloba7dadc937f781ea2cedb7e7ea830911844868081
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 /**
6 * @fileoverview An UI component to host gaia auth extension in an iframe.
7 * After the component binds with an iframe, call its {@code load} to start the
8 * authentication flow. There are two events would be raised after this point:
9 * a 'ready' event when the authentication UI is ready to use and a 'completed'
10 * event when the authentication is completed successfully. If caller is
11 * interested in the user credentials, he may supply a success callback with
12 * {@code load} call. The callback will be invoked when the authentication is
13 * completed successfully and with the available credential data.
16 cr.define('cr.login', function() {
17 'use strict';
19 /**
20 * Base URL of gaia auth extension.
21 * @const
23 var AUTH_URL_BASE = 'chrome-extension://mfffpogegjflfpflabcdkioaeobkgjik';
25 /**
26 * Auth URL to use for online flow.
27 * @const
29 var AUTH_URL = AUTH_URL_BASE + '/main.html';
31 /**
32 * Auth URL to use for offline flow.
33 * @const
35 var OFFLINE_AUTH_URL = AUTH_URL_BASE + '/offline.html';
37 /**
38 * Origin of the gaia sign in page.
39 * @const
41 var GAIA_ORIGIN = 'https://accounts.google.com';
43 /**
44 * Supported params of auth extension. For a complete list, check out the
45 * auth extension's main.js.
46 * @type {!Array.<string>}
47 * @const
49 var SUPPORTED_PARAMS = [
50 'gaiaUrl', // Gaia url to use;
51 'gaiaPath', // Gaia path to use without a leading slash;
52 'hl', // Language code for the user interface;
53 'email', // Pre-fill the email field in Gaia UI;
54 'service', // Name of Gaia service;
55 'continueUrl', // Continue url to use;
56 'frameUrl', // Initial frame URL to use. If empty defaults to gaiaUrl.
57 'constrained' // Whether the extension is loaded in a constrained window;
60 /**
61 * Supported localized strings. For a complete list, check out the auth
62 * extension's offline.js
63 * @type {!Array.<string>}
64 * @const
66 var LOCALIZED_STRING_PARAMS = [
67 'stringSignIn',
68 'stringEmail',
69 'stringPassword',
70 'stringEmptyEmail',
71 'stringEmptyPassword',
72 'stringError'
75 /**
76 * Enum for the authorization mode, must match AuthMode defined in
77 * chrome/browser/ui/webui/inline_login_ui.cc.
78 * @enum {number}
80 var AuthMode = {
81 DEFAULT: 0,
82 OFFLINE: 1,
83 DESKTOP: 2
86 /**
87 * Enum for the auth flow.
88 * @enum {number}
90 var AuthFlow = {
91 GAIA: 0,
92 SAML: 1
95 /**
96 * Creates a new gaia auth extension host.
97 * @param {HTMLIFrameElement|string} container The iframe element or its id
98 * to host the auth extension.
99 * @constructor
100 * @extends {cr.EventTarget}
102 function GaiaAuthHost(container) {
103 this.frame_ = typeof container == 'string' ? $(container) : container;
104 assert(this.frame_);
105 window.addEventListener('message',
106 this.onMessage_.bind(this), false);
109 GaiaAuthHost.prototype = {
110 __proto__: cr.EventTarget.prototype,
113 * An url to use with {@code reload}.
114 * @type {?string}
115 * @private
117 reloadUrl_: null,
120 * The domain name of the current auth page.
121 * @type {string}
123 authDomain: '',
126 * Invoked when authentication is completed successfully with credential
127 * data. A credential data object looks like this:
128 * <pre>
129 * {@code
131 * email: 'xx@gmail.com',
132 * password: 'xxxx', // May not present
133 * authCode: 'x/xx', // May not present
134 * authMode: 'x', // Authorization mode, default/offline/desktop.
137 * </pre>
138 * @type {function(Object)}
139 * @private
141 successCallback_: null,
144 * Invoked when GAIA indicates login success and SAML was used. At this
145 * point, GAIA cookies are present but the identity of the authenticated
146 * user is not known. The embedder of GaiaAuthHost should extract the GAIA
147 * cookies from the cookie jar, query GAIA for the authenticated user's
148 * e-mail address and invoke GaiaAuthHost.setAuthenticatedUserEmail with the
149 * result. The argument is an opaque token that should be passed back to
150 * GaiaAuthHost.setAuthenticatedUserEmail.
151 * @type {function(number)}
153 retrieveAuthenticatedUserEmailCallback_: null,
156 * Invoked when the auth flow needs a user to confirm his/her passwords.
157 * This could happen when there are more than one passwords scraped during
158 * SAML flow. The embedder of GaiaAuthHost should show an UI to collect a
159 * password from user then call GaiaAuthHost.verifyConfirmedPassword to
160 * verify. If the password is good, the auth flow continues with success
161 * path. Otherwise, confirmPasswordCallback_ is invoked again.
162 * @type {function()}
164 confirmPasswordCallback_: null,
167 * Similar to confirmPasswordCallback_ but is used when there is no
168 * password scraped after a success authentication. The authenticated user
169 * account is passed to the callback. The embedder should take over the
170 * flow and decide what to do next.
171 * @type {function(string)}
173 noPasswordCallback_: null,
176 * The iframe container.
177 * @type {HTMLIFrameElement}
179 get frame() {
180 return this.frame_;
184 * Sets retrieveAuthenticatedUserEmailCallback_.
185 * @type {function()}
187 set retrieveAuthenticatedUserEmailCallback(callback) {
188 this.retrieveAuthenticatedUserEmailCallback_ = callback;
192 * Sets confirmPasswordCallback_.
193 * @type {function()}
195 set confirmPasswordCallback(callback) {
196 this.confirmPasswordCallback_ = callback;
200 * Sets noPasswordCallback_.
201 * @type {function()}
203 set noPasswordCallback(callback) {
204 this.noPasswordCallback_ = callback;
208 * Loads the auth extension.
209 * @param {AuthMode} authMode Authorization mode.
210 * @param {Object} data Parameters for the auth extension. See the auth
211 * extension's main.js for all supported params and their defaults.
212 * @param {function(Object)} successCallback A function to be called when
213 * the authentication is completed successfully. The callback is
214 * invoked with a credential object.
216 load: function(authMode, data, successCallback) {
217 var params = [];
219 var populateParams = function(nameList, values) {
220 if (!values)
221 return;
223 for (var i in nameList) {
224 var name = nameList[i];
225 if (values[name])
226 params.push(name + '=' + encodeURIComponent(values[name]));
230 populateParams(SUPPORTED_PARAMS, data);
231 populateParams(LOCALIZED_STRING_PARAMS, data.localizedStrings);
232 params.push('parentPage=' + encodeURIComponent(window.location.origin));
234 var url;
235 switch (authMode) {
236 case AuthMode.OFFLINE:
237 url = OFFLINE_AUTH_URL;
238 break;
239 case AuthMode.DESKTOP:
240 url = AUTH_URL;
241 params.push('desktopMode=1');
242 break;
243 default:
244 url = AUTH_URL;
246 url += '?' + params.join('&');
248 this.frame_.src = url;
249 this.reloadUrl_ = url;
250 this.successCallback_ = successCallback;
251 this.authFlow = AuthFlow.GAIA;
255 * Reloads the auth extension.
257 reload: function() {
258 this.frame_.src = this.reloadUrl_;
259 this.authFlow = AuthFlow.GAIA;
263 * Verifies the supplied password by sending it to the auth extension,
264 * which will then check if it matches the scraped passwords.
265 * @param {string} password The confirmed password that needs verification.
267 verifyConfirmedPassword: function(password) {
268 var msg = {
269 method: 'verifyConfirmedPassword',
270 password: password
272 this.frame_.contentWindow.postMessage(msg, AUTH_URL_BASE);
276 * Sends the authenticated user's e-mail address to the auth extension.
277 * @param {number} attemptToken The opaque token provided to the
278 * retrieveAuthenticatedUserEmailCallback_.
279 * @param {string} email The authenticated user's e-mail address.
281 setAuthenticatedUserEmail: function(attemptToken, email) {
282 var msg = {
283 method: 'setAuthenticatedUserEmail',
284 attemptToken: attemptToken,
285 email: email
287 this.frame_.contentWindow.postMessage(msg, AUTH_URL_BASE);
291 * Invoked to process authentication success.
292 * @param {Object} credentials Credential object to pass to success
293 * callback.
294 * @private
296 onAuthSuccess_: function(credentials) {
297 if (this.successCallback_)
298 this.successCallback_(credentials);
299 cr.dispatchSimpleEvent(this, 'completed');
303 * Checks if message comes from the loaded authentication extension.
304 * @param {Object} e Payload of the received HTML5 message.
305 * @type {boolean}
307 isAuthExtMessage_: function(e) {
308 return this.frame_.src &&
309 this.frame_.src.indexOf(e.origin) == 0 &&
310 e.source == this.frame_.contentWindow;
314 * Event handler that is invoked when HTML5 message is received.
315 * @param {object} e Payload of the received HTML5 message.
317 onMessage_: function(e) {
318 var msg = e.data;
320 if (!this.isAuthExtMessage_(e))
321 return;
323 if (msg.method == 'loginUILoaded') {
324 cr.dispatchSimpleEvent(this, 'ready');
325 return;
328 if (/^complete(Login|Authentication)$|^offlineLogin$/.test(msg.method)) {
329 if (!msg.email && !this.email_ && !msg.skipForNow) {
330 var msg = {method: 'redirectToSignin'};
331 this.frame_.contentWindow.postMessage(msg, AUTH_URL_BASE);
332 return;
334 this.onAuthSuccess_({email: msg.email,
335 password: msg.password,
336 useOffline: msg.method == 'offlineLogin',
337 usingSAML: msg.usingSAML || false,
338 chooseWhatToSync: msg.chooseWhatToSync,
339 skipForNow: msg.skipForNow || false,
340 sessionIndex: msg.sessionIndex || ''});
341 return;
344 if (msg.method == 'retrieveAuthenticatedUserEmail') {
345 if (this.retrieveAuthenticatedUserEmailCallback_) {
346 this.retrieveAuthenticatedUserEmailCallback_(msg.attemptToken,
347 msg.apiUsed);
348 } else {
349 console.error(
350 'GaiaAuthHost: Invalid retrieveAuthenticatedUserEmailCallback_.');
352 return;
355 if (msg.method == 'confirmPassword') {
356 if (this.confirmPasswordCallback_)
357 this.confirmPasswordCallback_(msg.passwordCount);
358 else
359 console.error('GaiaAuthHost: Invalid confirmPasswordCallback_.');
360 return;
363 if (msg.method == 'noPassword') {
364 if (this.noPasswordCallback_)
365 this.noPasswordCallback_(msg.email);
366 else
367 console.error('GaiaAuthHost: Invalid noPasswordCallback_.');
368 return;
371 if (msg.method == 'authPageLoaded') {
372 this.authDomain = msg.domain;
373 this.authFlow = msg.isSAML ? AuthFlow.SAML : AuthFlow.GAIA;
374 return;
377 if (msg.method == 'switchToFullTab') {
378 chrome.send('switchToFullTab', [msg.url]);
379 return;
382 console.error('Unknown message method=' + msg.method);
387 * The current auth flow of the hosted gaia_auth extension.
388 * @type {AuthFlow}
390 cr.defineProperty(GaiaAuthHost, 'authFlow');
392 GaiaAuthHost.SUPPORTED_PARAMS = SUPPORTED_PARAMS;
393 GaiaAuthHost.LOCALIZED_STRING_PARAMS = LOCALIZED_STRING_PARAMS;
394 GaiaAuthHost.AuthMode = AuthMode;
395 GaiaAuthHost.AuthFlow = AuthFlow;
397 return {
398 GaiaAuthHost: GaiaAuthHost