1 // Copyright (c) 2012 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 #include "chrome/browser/ui/sync/one_click_signin_helper.h"
12 #include "base/bind.h"
13 #include "base/callback_forward.h"
14 #include "base/callback_helpers.h"
15 #include "base/compiler_specific.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/message_loop/message_loop_proxy.h"
18 #include "base/metrics/field_trial.h"
19 #include "base/metrics/histogram.h"
20 #include "base/prefs/pref_service.h"
21 #include "base/prefs/scoped_user_pref_update.h"
22 #include "base/strings/string_split.h"
23 #include "base/strings/string_util.h"
24 #include "base/strings/utf_string_conversions.h"
25 #include "base/supports_user_data.h"
26 #include "base/values.h"
27 #include "chrome/browser/browser_process.h"
28 #include "chrome/browser/chrome_notification_types.h"
29 #include "chrome/browser/defaults.h"
30 #include "chrome/browser/history/history_service.h"
31 #include "chrome/browser/history/history_service_factory.h"
32 #include "chrome/browser/profiles/profile.h"
33 #include "chrome/browser/profiles/profile_info_cache.h"
34 #include "chrome/browser/profiles/profile_io_data.h"
35 #include "chrome/browser/profiles/profile_manager.h"
36 #include "chrome/browser/search/search.h"
37 #include "chrome/browser/signin/chrome_signin_client.h"
38 #include "chrome/browser/signin/chrome_signin_client_factory.h"
39 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
40 #include "chrome/browser/signin/signin_manager_factory.h"
41 #include "chrome/browser/signin/signin_names_io_thread.h"
42 #include "chrome/browser/sync/profile_sync_service.h"
43 #include "chrome/browser/sync/profile_sync_service_factory.h"
44 #include "chrome/browser/tab_contents/tab_util.h"
45 #include "chrome/browser/ui/browser_finder.h"
46 #include "chrome/browser/ui/browser_list.h"
47 #include "chrome/browser/ui/browser_tabstrip.h"
48 #include "chrome/browser/ui/browser_window.h"
49 #include "chrome/browser/ui/chrome_pages.h"
50 #include "chrome/browser/ui/sync/one_click_signin_histogram.h"
51 #include "chrome/browser/ui/sync/one_click_signin_sync_observer.h"
52 #include "chrome/browser/ui/sync/one_click_signin_sync_starter.h"
53 #include "chrome/browser/ui/sync/signin_histogram.h"
54 #include "chrome/browser/ui/tab_modal_confirm_dialog.h"
55 #include "chrome/browser/ui/tab_modal_confirm_dialog_delegate.h"
56 #include "chrome/browser/ui/tabs/tab_strip_model.h"
57 #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
58 #include "chrome/common/chrome_version_info.h"
59 #include "chrome/common/net/url_util.h"
60 #include "chrome/common/pref_names.h"
61 #include "chrome/common/url_constants.h"
62 #include "components/autofill/core/common/password_form.h"
63 #include "components/google/core/browser/google_util.h"
64 #include "components/password_manager/core/browser/password_manager.h"
65 #include "components/signin/core/browser/profile_oauth2_token_service.h"
66 #include "components/signin/core/browser/signin_client.h"
67 #include "components/signin/core/browser/signin_error_controller.h"
68 #include "components/signin/core/browser/signin_manager.h"
69 #include "components/signin/core/browser/signin_manager_cookie_helper.h"
70 #include "components/signin/core/common/profile_management_switches.h"
71 #include "components/sync_driver/sync_prefs.h"
72 #include "content/public/browser/browser_thread.h"
73 #include "content/public/browser/navigation_entry.h"
74 #include "content/public/browser/page_navigator.h"
75 #include "content/public/browser/render_frame_host.h"
76 #include "content/public/browser/render_process_host.h"
77 #include "content/public/browser/web_contents.h"
78 #include "content/public/browser/web_contents_delegate.h"
79 #include "content/public/common/frame_navigate_params.h"
80 #include "content/public/common/page_transition_types.h"
81 #include "google_apis/gaia/gaia_auth_util.h"
82 #include "google_apis/gaia/gaia_urls.h"
83 #include "grit/chromium_strings.h"
84 #include "grit/generated_resources.h"
85 #include "grit/theme_resources.h"
86 #include "ipc/ipc_message_macros.h"
87 #include "net/base/url_util.h"
88 #include "net/cookies/cookie_monster.h"
89 #include "net/url_request/url_request.h"
90 #include "ui/base/l10n/l10n_util.h"
96 // ConfirmEmailDialogDelegate -------------------------------------------------
98 class ConfirmEmailDialogDelegate : public TabModalConfirmDialogDelegate {
106 // Callback indicating action performed by the user.
107 typedef base::Callback<void(Action)> Callback;
109 // Ask the user for confirmation before starting to sync.
110 static void AskForConfirmation(content::WebContents* contents,
111 const std::string& last_email,
112 const std::string& email,
116 ConfirmEmailDialogDelegate(content::WebContents* contents,
117 const std::string& last_email,
118 const std::string& email,
120 virtual ~ConfirmEmailDialogDelegate();
122 // TabModalConfirmDialogDelegate:
123 virtual base::string16 GetTitle() OVERRIDE;
124 virtual base::string16 GetDialogMessage() OVERRIDE;
125 virtual base::string16 GetAcceptButtonTitle() OVERRIDE;
126 virtual base::string16 GetCancelButtonTitle() OVERRIDE;
127 virtual base::string16 GetLinkText() const OVERRIDE;
128 virtual void OnAccepted() OVERRIDE;
129 virtual void OnCanceled() OVERRIDE;
130 virtual void OnClosed() OVERRIDE;
131 virtual void OnLinkClicked(WindowOpenDisposition disposition) OVERRIDE;
133 std::string last_email_;
137 // Web contents from which the "Learn more" link should be opened.
138 content::WebContents* web_contents_;
140 DISALLOW_COPY_AND_ASSIGN(ConfirmEmailDialogDelegate);
144 void ConfirmEmailDialogDelegate::AskForConfirmation(
145 content::WebContents* contents,
146 const std::string& last_email,
147 const std::string& email,
149 TabModalConfirmDialog::Create(
150 new ConfirmEmailDialogDelegate(contents, last_email, email,
151 callback), contents);
154 ConfirmEmailDialogDelegate::ConfirmEmailDialogDelegate(
155 content::WebContents* contents,
156 const std::string& last_email,
157 const std::string& email,
159 : TabModalConfirmDialogDelegate(contents),
160 last_email_(last_email),
163 web_contents_(contents) {
166 ConfirmEmailDialogDelegate::~ConfirmEmailDialogDelegate() {
169 base::string16 ConfirmEmailDialogDelegate::GetTitle() {
170 return l10n_util::GetStringUTF16(
171 IDS_ONE_CLICK_SIGNIN_CONFIRM_EMAIL_DIALOG_TITLE);
174 base::string16 ConfirmEmailDialogDelegate::GetDialogMessage() {
175 return l10n_util::GetStringFUTF16(
176 IDS_ONE_CLICK_SIGNIN_CONFIRM_EMAIL_DIALOG_MESSAGE,
177 base::UTF8ToUTF16(last_email_), base::UTF8ToUTF16(email_));
180 base::string16 ConfirmEmailDialogDelegate::GetAcceptButtonTitle() {
181 return l10n_util::GetStringUTF16(
182 IDS_ONE_CLICK_SIGNIN_CONFIRM_EMAIL_DIALOG_OK_BUTTON);
185 base::string16 ConfirmEmailDialogDelegate::GetCancelButtonTitle() {
186 return l10n_util::GetStringUTF16(
187 IDS_ONE_CLICK_SIGNIN_CONFIRM_EMAIL_DIALOG_CANCEL_BUTTON);
190 base::string16 ConfirmEmailDialogDelegate::GetLinkText() const {
191 return l10n_util::GetStringUTF16(IDS_LEARN_MORE);
194 void ConfirmEmailDialogDelegate::OnAccepted() {
195 base::ResetAndReturn(&callback_).Run(CREATE_NEW_USER);
198 void ConfirmEmailDialogDelegate::OnCanceled() {
199 base::ResetAndReturn(&callback_).Run(START_SYNC);
202 void ConfirmEmailDialogDelegate::OnClosed() {
203 base::ResetAndReturn(&callback_).Run(CLOSE);
206 void ConfirmEmailDialogDelegate::OnLinkClicked(
207 WindowOpenDisposition disposition) {
208 content::OpenURLParams params(
209 GURL(chrome::kChromeSyncMergeTroubleshootingURL),
212 content::PAGE_TRANSITION_AUTO_TOPLEVEL,
214 // It is guaranteed that |web_contents_| is valid here because when it's
215 // deleted, the dialog is immediately closed and no further action can be
217 web_contents_->OpenURL(params);
221 // Helpers --------------------------------------------------------------------
223 // Add a specific email to the list of emails rejected for one-click
224 // sign-in, for this profile.
225 void AddEmailToOneClickRejectedList(Profile* profile,
226 const std::string& email) {
227 ListPrefUpdate updater(profile->GetPrefs(),
228 prefs::kReverseAutologinRejectedEmailList);
229 updater->AppendIfNotPresent(new base::StringValue(email));
232 void LogOneClickHistogramValue(int action) {
233 UMA_HISTOGRAM_ENUMERATION("Signin.OneClickActions", action,
234 one_click_signin::HISTOGRAM_MAX);
235 UMA_HISTOGRAM_ENUMERATION("Signin.AllAccessPointActions", action,
236 one_click_signin::HISTOGRAM_MAX);
239 void RedirectToNtpOrAppsPageWithIds(int child_id,
241 signin::Source source) {
242 content::WebContents* web_contents = tab_util::GetWebContentsByID(child_id,
247 OneClickSigninHelper::RedirectToNtpOrAppsPage(web_contents, source);
250 // Start syncing with the given user information.
251 void StartSync(const OneClickSigninHelper::StartSyncArgs& args,
252 OneClickSigninSyncStarter::StartSyncMode start_mode) {
253 if (start_mode == OneClickSigninSyncStarter::UNDO_SYNC) {
254 LogOneClickHistogramValue(one_click_signin::HISTOGRAM_UNDO);
258 // The wrapper deletes itself once it's done.
259 OneClickSigninHelper::SyncStarterWrapper* wrapper =
260 new OneClickSigninHelper::SyncStarterWrapper(args, start_mode);
263 int action = one_click_signin::HISTOGRAM_MAX;
264 switch (args.auto_accept) {
265 case OneClickSigninHelper::AUTO_ACCEPT_EXPLICIT:
267 case OneClickSigninHelper::AUTO_ACCEPT_ACCEPTED:
269 start_mode == OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS ?
270 one_click_signin::HISTOGRAM_AUTO_WITH_DEFAULTS :
271 one_click_signin::HISTOGRAM_AUTO_WITH_ADVANCED;
273 case OneClickSigninHelper::AUTO_ACCEPT_CONFIGURE:
274 DCHECK(start_mode == OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST);
275 action = one_click_signin::HISTOGRAM_AUTO_WITH_ADVANCED;
278 NOTREACHED() << "Invalid auto_accept: " << args.auto_accept;
281 if (action != one_click_signin::HISTOGRAM_MAX)
282 LogOneClickHistogramValue(action);
285 void StartExplicitSync(const OneClickSigninHelper::StartSyncArgs& args,
286 content::WebContents* contents,
287 OneClickSigninSyncStarter::StartSyncMode start_mode,
288 ConfirmEmailDialogDelegate::Action action) {
289 bool enable_inline = !switches::IsEnableWebBasedSignin();
290 if (action == ConfirmEmailDialogDelegate::START_SYNC) {
291 StartSync(args, start_mode);
292 if (!enable_inline) {
293 // Redirect/tab closing for inline flow is handled by the sync callback.
294 OneClickSigninHelper::RedirectToNtpOrAppsPageIfNecessary(
295 contents, args.source);
298 // Perform a redirection to the NTP/Apps page to hide the blank page when
299 // the action is CLOSE or CREATE_NEW_USER. The redirection is useful when
300 // the action is CREATE_NEW_USER because the "Create new user" page might
301 // be opened in a different tab that is already showing settings.
303 // Redirect/tab closing for inline flow is handled by the sync callback.
304 args.callback.Run(OneClickSigninSyncStarter::SYNC_SETUP_FAILURE);
306 // Don't redirect when the visible URL is not a blank page: if the
307 // source is SOURCE_WEBSTORE_INSTALL, |contents| might be showing an app
308 // page that shouldn't be hidden.
310 // If redirecting, don't do so immediately, otherwise there may be 2
311 // nested navigations and a crash would occur (crbug.com/293261). Post
312 // the task to the current thread instead.
313 if (signin::IsContinueUrlForWebBasedSigninFlow(
314 contents->GetVisibleURL())) {
315 base::MessageLoopProxy::current()->PostNonNestableTask(
317 base::Bind(RedirectToNtpOrAppsPageWithIds,
318 contents->GetRenderProcessHost()->GetID(),
319 contents->GetRoutingID(),
323 if (action == ConfirmEmailDialogDelegate::CREATE_NEW_USER) {
324 chrome::ShowSettingsSubPage(args.browser,
325 std::string(chrome::kCreateProfileSubPage));
330 void ClearPendingEmailOnIOThread(content::ResourceContext* context) {
331 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
333 io_data->set_reverse_autologin_pending_email(std::string());
336 // Determines the source of the sign in and the continue URL. It's either one
337 // of the known sign-in access points (first run, NTP, Apps page, menu, or
338 // settings) or it's an implicit sign in via another Google property. In the
339 // former case, "service" is also checked to make sure its "chromiumsync".
340 signin::Source GetSigninSource(const GURL& url, GURL* continue_url) {
341 DCHECK(url.is_valid());
343 net::GetValueForKeyInQuery(url, "service", &value);
344 bool possibly_an_explicit_signin = value == "chromiumsync";
346 // Find the final continue URL for this sign in. In some cases, Gaia can
347 // continue to itself, with the original continue URL buried under a couple
348 // of layers of indirection. Peel those layers away. The final destination
349 // can also be "IsGaiaSignonRealm" so stop if we get to the end (but be sure
350 // we always extract at least one "continue" value).
351 GURL local_continue_url = signin::GetNextPageURLForPromoURL(url);
352 while (gaia::IsGaiaSignonRealm(local_continue_url.GetOrigin())) {
353 GURL next_continue_url =
354 signin::GetNextPageURLForPromoURL(local_continue_url);
355 if (!next_continue_url.is_valid())
357 local_continue_url = next_continue_url;
360 if (continue_url && local_continue_url.is_valid()) {
361 DCHECK(!continue_url->is_valid() || *continue_url == local_continue_url);
362 *continue_url = local_continue_url;
365 return possibly_an_explicit_signin ?
366 signin::GetSourceForPromoURL(local_continue_url) :
367 signin::SOURCE_UNKNOWN;
370 // Returns true if |url| is a valid URL that can occur during the sign in
371 // process. Valid URLs are of the form:
373 // https://accounts.google.{TLD}/...
374 // https://accounts.youtube.com/...
375 // https://accounts.blogger.com/...
377 // All special headers used by one click sign in occur on
378 // https://accounts.google.com URLs. However, the sign in process may redirect
379 // to intermediate Gaia URLs that do not end with .com. For example, an account
380 // that uses SMS 2-factor outside the US may redirect to country specific URLs.
382 // The sign in process may also redirect to youtube and blogger account URLs
383 // so that Gaia acts as a single signon service.
384 bool IsValidGaiaSigninRedirectOrResponseURL(const GURL& url) {
385 std::string hostname = url.host();
386 if (google_util::IsGoogleHostname(hostname, google_util::ALLOW_SUBDOMAIN)) {
387 // Also using IsGaiaSignonRealm() to handle overriding with command line.
388 return gaia::IsGaiaSignonRealm(url.GetOrigin()) ||
389 StartsWithASCII(hostname, "accounts.", false);
392 GURL origin = url.GetOrigin();
393 if (origin == GURL("https://accounts.youtube.com") ||
394 origin == GURL("https://accounts.blogger.com"))
400 // Tells when we are in the process of showing either the signin to chrome page
401 // or the one click sign in to chrome page.
402 // NOTE: This should only be used for logging purposes since it relies on hard
403 // coded URLs that could change.
404 bool AreWeShowingSignin(GURL url, signin::Source source, std::string email) {
405 GURL::Replacements replacements;
406 replacements.ClearQuery();
407 GURL clean_login_url =
408 GaiaUrls::GetInstance()->service_login_url().ReplaceComponents(
411 return (url.ReplaceComponents(replacements) == clean_login_url &&
412 source != signin::SOURCE_UNKNOWN) ||
413 (IsValidGaiaSigninRedirectOrResponseURL(url) &&
414 url.spec().find("ChromeLoginPrompt") != std::string::npos &&
418 // If profile is valid then get signin scoped device id from signin client.
419 // Otherwise returns empty string.
420 std::string GetSigninScopedDeviceId(Profile* profile) {
421 std::string signin_scoped_device_id;
422 SigninClient* signin_client =
423 profile ? ChromeSigninClientFactory::GetForProfile(profile) : NULL;
425 signin_scoped_device_id = signin_client->GetSigninScopedDeviceId();
427 return signin_scoped_device_id;
430 // CurrentHistoryCleaner ------------------------------------------------------
432 // Watch a webcontents and remove URL from the history once loading is complete.
433 // We have to delay the cleaning until the new URL has finished loading because
434 // we're not allowed to remove the last-loaded URL from the history. Objects
435 // of this type automatically self-destruct once they're finished their work.
436 class CurrentHistoryCleaner : public content::WebContentsObserver {
438 explicit CurrentHistoryCleaner(content::WebContents* contents);
439 virtual ~CurrentHistoryCleaner();
441 // content::WebContentsObserver:
442 virtual void WebContentsDestroyed() OVERRIDE;
443 virtual void DidCommitProvisionalLoadForFrame(
444 content::RenderFrameHost* render_frame_host,
446 content::PageTransition transition_type) OVERRIDE;
449 scoped_ptr<content::WebContents> contents_;
450 int history_index_to_remove_;
452 DISALLOW_COPY_AND_ASSIGN(CurrentHistoryCleaner);
455 CurrentHistoryCleaner::CurrentHistoryCleaner(content::WebContents* contents)
456 : WebContentsObserver(contents) {
457 history_index_to_remove_ =
458 web_contents()->GetController().GetLastCommittedEntryIndex();
461 CurrentHistoryCleaner::~CurrentHistoryCleaner() {
464 void CurrentHistoryCleaner::DidCommitProvisionalLoadForFrame(
465 content::RenderFrameHost* render_frame_host,
467 content::PageTransition transition_type) {
468 // Return early if this is not top-level navigation.
469 if (render_frame_host->GetParent())
472 content::NavigationController* nc = &web_contents()->GetController();
473 HistoryService* hs = HistoryServiceFactory::GetForProfile(
474 Profile::FromBrowserContext(web_contents()->GetBrowserContext()),
475 Profile::IMPLICIT_ACCESS);
477 // Have to wait until something else gets added to history before removal.
478 if (history_index_to_remove_ < nc->GetLastCommittedEntryIndex()) {
479 content::NavigationEntry* entry =
480 nc->GetEntryAtIndex(history_index_to_remove_);
481 if (signin::IsContinueUrlForWebBasedSigninFlow(entry->GetURL())) {
482 hs->DeleteURL(entry->GetURL());
483 nc->RemoveEntryAtIndex(history_index_to_remove_);
484 delete this; // Success.
489 void CurrentHistoryCleaner::WebContentsDestroyed() {
490 delete this; // Failure.
496 // StartSyncArgs --------------------------------------------------------------
498 OneClickSigninHelper::StartSyncArgs::StartSyncArgs()
501 auto_accept(AUTO_ACCEPT_NONE),
503 confirmation_required(OneClickSigninSyncStarter::NO_CONFIRMATION),
504 source(signin::SOURCE_UNKNOWN) {}
506 OneClickSigninHelper::StartSyncArgs::StartSyncArgs(
509 OneClickSigninHelper::AutoAccept auto_accept,
510 const std::string& session_index,
511 const std::string& email,
512 const std::string& password,
513 const std::string& refresh_token,
514 content::WebContents* web_contents,
515 bool untrusted_confirmation_required,
516 signin::Source source,
517 OneClickSigninSyncStarter::Callback callback)
520 auto_accept(auto_accept),
521 session_index(session_index),
524 refresh_token(refresh_token),
525 web_contents(web_contents),
528 DCHECK(session_index.empty() != refresh_token.empty());
529 if (untrusted_confirmation_required) {
530 confirmation_required = OneClickSigninSyncStarter::CONFIRM_UNTRUSTED_SIGNIN;
531 } else if (source == signin::SOURCE_SETTINGS ||
532 source == signin::SOURCE_WEBSTORE_INSTALL) {
533 // Do not display a status confirmation for webstore installs or re-auth.
534 confirmation_required = OneClickSigninSyncStarter::NO_CONFIRMATION;
536 confirmation_required = OneClickSigninSyncStarter::CONFIRM_AFTER_SIGNIN;
540 OneClickSigninHelper::StartSyncArgs::~StartSyncArgs() {}
542 // SyncStarterWrapper ---------------------------------------------------------
544 OneClickSigninHelper::SyncStarterWrapper::SyncStarterWrapper(
545 const OneClickSigninHelper::StartSyncArgs& args,
546 OneClickSigninSyncStarter::StartSyncMode start_mode)
547 : args_(args), start_mode_(start_mode), weak_pointer_factory_(this) {
548 BrowserList::AddObserver(this);
550 // Cache the parent desktop for the browser, so we can reuse that same
551 // desktop for any UI we want to display.
552 desktop_type_ = args_.browser ? args_.browser->host_desktop_type()
553 : chrome::GetActiveDesktop();
556 OneClickSigninHelper::SyncStarterWrapper::~SyncStarterWrapper() {
557 BrowserList::RemoveObserver(this);
560 void OneClickSigninHelper::SyncStarterWrapper::Start() {
561 if (args_.refresh_token.empty()) {
562 if (args_.password.empty()) {
563 VerifyGaiaCookiesBeforeSignIn();
565 StartSigninOAuthHelper();
568 OnSigninOAuthInformationAvailable(args_.email, args_.email,
569 args_.refresh_token);
574 OneClickSigninHelper::SyncStarterWrapper::OnSigninOAuthInformationAvailable(
575 const std::string& email,
576 const std::string& display_email,
577 const std::string& refresh_token) {
578 if (!gaia::AreEmailsSame(display_email, args_.email)) {
580 GoogleServiceAuthError(
581 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS).ToString());
583 StartOneClickSigninSyncStarter(email, refresh_token);
586 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
589 void OneClickSigninHelper::SyncStarterWrapper::OnSigninOAuthInformationFailure(
590 const GoogleServiceAuthError& error) {
591 DisplayErrorBubble(error.ToString());
592 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
595 void OneClickSigninHelper::SyncStarterWrapper::OnBrowserRemoved(
597 if (args_.browser == browser)
598 args_.browser = NULL;
601 void OneClickSigninHelper::SyncStarterWrapper::VerifyGaiaCookiesBeforeSignIn() {
602 scoped_refptr<SigninManagerCookieHelper> cookie_helper(
603 new SigninManagerCookieHelper(
604 args_.profile->GetRequestContext(),
605 content::BrowserThread::GetMessageLoopProxyForThread(
606 content::BrowserThread::UI),
607 content::BrowserThread::GetMessageLoopProxyForThread(
608 content::BrowserThread::IO)));
609 cookie_helper->StartFetchingGaiaCookiesOnUIThread(
610 base::Bind(&SyncStarterWrapper::OnGaiaCookiesFetched,
611 weak_pointer_factory_.GetWeakPtr(),
612 args_.session_index));
615 void OneClickSigninHelper::SyncStarterWrapper::OnGaiaCookiesFetched(
616 const std::string session_index, const net::CookieList& cookie_list) {
617 net::CookieList::const_iterator it;
618 bool success = false;
619 for (it = cookie_list.begin(); it != cookie_list.end(); ++it) {
620 // Make sure the LSID cookie is set on the GAIA host, instead of a super-
622 if (it->Name() == "LSID") {
623 if (it->IsHostCookie() && it->IsHttpOnly() && it->IsSecure()) {
624 // Found a valid LSID cookie. Continue loop to make sure we don't have
625 // invalid LSID cookies on any super-domain.
635 StartSigninOAuthHelper();
638 GoogleServiceAuthError(
639 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS).ToString());
640 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
644 void OneClickSigninHelper::SyncStarterWrapper::DisplayErrorBubble(
645 const std::string& error_message) {
646 args_.browser = OneClickSigninSyncStarter::EnsureBrowser(
647 args_.browser, args_.profile, desktop_type_);
648 LoginUIServiceFactory::GetForProfile(args_.profile)->DisplayLoginResult(
649 args_.browser, base::UTF8ToUTF16(error_message));
652 void OneClickSigninHelper::SyncStarterWrapper::StartSigninOAuthHelper() {
653 std::string signin_scoped_device_id = GetSigninScopedDeviceId(args_.profile);
654 signin_oauth_helper_.reset(
655 new SigninOAuthHelper(args_.profile->GetRequestContext(),
657 signin_scoped_device_id,
662 OneClickSigninHelper::SyncStarterWrapper::StartOneClickSigninSyncStarter(
663 const std::string& email,
664 const std::string& refresh_token) {
665 // The starter deletes itself once it's done.
666 new OneClickSigninSyncStarter(args_.profile, args_.browser,
667 email, args_.password,
668 refresh_token, start_mode_,
670 args_.confirmation_required,
676 // OneClickSigninHelper -------------------------------------------------------
678 DEFINE_WEB_CONTENTS_USER_DATA_KEY(OneClickSigninHelper);
681 const int OneClickSigninHelper::kMaxNavigationsSince = 10;
683 OneClickSigninHelper::OneClickSigninHelper(
684 content::WebContents* web_contents,
685 password_manager::PasswordManager* password_manager)
686 : content::WebContentsObserver(web_contents),
687 showing_signin_(false),
688 auto_accept_(AUTO_ACCEPT_NONE),
689 source_(signin::SOURCE_UNKNOWN),
690 switched_to_advanced_(false),
691 untrusted_navigations_since_signin_visit_(0),
692 untrusted_confirmation_required_(false),
693 do_not_clear_pending_email_(false),
694 do_not_start_sync_for_testing_(false),
695 weak_pointer_factory_(this) {
696 // May be NULL during testing.
697 if (password_manager) {
698 password_manager->AddSubmissionCallback(
699 base::Bind(&OneClickSigninHelper::PasswordSubmitted,
700 weak_pointer_factory_.GetWeakPtr()));
704 OneClickSigninHelper::~OneClickSigninHelper() {}
707 void OneClickSigninHelper::LogHistogramValue(
708 signin::Source source, int action) {
710 case signin::SOURCE_START_PAGE:
711 UMA_HISTOGRAM_ENUMERATION("Signin.StartPageActions", action,
712 one_click_signin::HISTOGRAM_MAX);
714 case signin::SOURCE_NTP_LINK:
715 UMA_HISTOGRAM_ENUMERATION("Signin.NTPLinkActions", action,
716 one_click_signin::HISTOGRAM_MAX);
718 case signin::SOURCE_MENU:
719 UMA_HISTOGRAM_ENUMERATION("Signin.MenuActions", action,
720 one_click_signin::HISTOGRAM_MAX);
722 case signin::SOURCE_SETTINGS:
723 UMA_HISTOGRAM_ENUMERATION("Signin.SettingsActions", action,
724 one_click_signin::HISTOGRAM_MAX);
726 case signin::SOURCE_EXTENSION_INSTALL_BUBBLE:
727 UMA_HISTOGRAM_ENUMERATION("Signin.ExtensionInstallBubbleActions", action,
728 one_click_signin::HISTOGRAM_MAX);
730 case signin::SOURCE_WEBSTORE_INSTALL:
731 UMA_HISTOGRAM_ENUMERATION("Signin.WebstoreInstallActions", action,
732 one_click_signin::HISTOGRAM_MAX);
734 case signin::SOURCE_APP_LAUNCHER:
735 UMA_HISTOGRAM_ENUMERATION("Signin.AppLauncherActions", action,
736 one_click_signin::HISTOGRAM_MAX);
738 case signin::SOURCE_APPS_PAGE_LINK:
739 UMA_HISTOGRAM_ENUMERATION("Signin.AppsPageLinkActions", action,
740 one_click_signin::HISTOGRAM_MAX);
742 case signin::SOURCE_BOOKMARK_BUBBLE:
743 UMA_HISTOGRAM_ENUMERATION("Signin.BookmarkBubbleActions", action,
744 one_click_signin::HISTOGRAM_MAX);
746 case signin::SOURCE_AVATAR_BUBBLE_SIGN_IN:
747 UMA_HISTOGRAM_ENUMERATION("Signin.AvatarBubbleActions", action,
748 one_click_signin::HISTOGRAM_MAX);
750 case signin::SOURCE_AVATAR_BUBBLE_ADD_ACCOUNT:
751 UMA_HISTOGRAM_ENUMERATION("Signin.AvatarBubbleActions", action,
752 one_click_signin::HISTOGRAM_MAX);
754 case signin::SOURCE_DEVICES_PAGE:
755 UMA_HISTOGRAM_ENUMERATION("Signin.DevicesPageActions", action,
756 one_click_signin::HISTOGRAM_MAX);
758 case signin::SOURCE_REAUTH:
759 UMA_HISTOGRAM_ENUMERATION("Signin.ReauthActions", action,
760 one_click_signin::HISTOGRAM_MAX);
763 // This switch statement needs to be updated when the enum Source changes.
764 COMPILE_ASSERT(signin::SOURCE_UNKNOWN == 13,
765 kSourceEnumHasChangedButNotThisSwitchStatement);
766 UMA_HISTOGRAM_ENUMERATION("Signin.UnknownActions", action,
767 one_click_signin::HISTOGRAM_MAX);
769 UMA_HISTOGRAM_ENUMERATION("Signin.AllAccessPointActions", action,
770 one_click_signin::HISTOGRAM_MAX);
774 void OneClickSigninHelper::CreateForWebContentsWithPasswordManager(
775 content::WebContents* contents,
776 password_manager::PasswordManager* password_manager) {
777 if (!FromWebContents(contents)) {
778 contents->SetUserData(UserDataKey(),
779 new OneClickSigninHelper(contents, password_manager));
784 bool OneClickSigninHelper::CanOffer(content::WebContents* web_contents,
785 CanOfferFor can_offer_for,
786 const std::string& email,
787 std::string* error_message) {
788 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
789 VLOG(1) << "OneClickSigninHelper::CanOffer";
792 error_message->clear();
797 if (web_contents->GetBrowserContext()->IsOffTheRecord())
801 Profile::FromBrowserContext(web_contents->GetBrowserContext());
805 SigninManager* manager =
806 SigninManagerFactory::GetForProfile(profile);
807 if (manager && !manager->IsSigninAllowed())
810 if (can_offer_for == CAN_OFFER_FOR_INTERSTITAL_ONLY &&
811 !profile->GetPrefs()->GetBoolean(prefs::kReverseAutologinEnabled))
814 if (!ChromeSigninClient::ProfileAllowsSigninCookies(profile))
817 if (!email.empty()) {
821 // Make sure this username is not prohibited by policy.
822 if (!manager->IsAllowedUsername(email)) {
824 error_message->assign(
825 l10n_util::GetStringUTF8(IDS_SYNC_LOGIN_NAME_PROHIBITED));
830 if (can_offer_for != CAN_OFFER_FOR_SECONDARY_ACCOUNT) {
831 // If the signin manager already has an authenticated name, then this is a
832 // re-auth scenario. Make sure the email just signed in corresponds to
833 // the one sign in manager expects.
834 std::string current_email = manager->GetAuthenticatedUsername();
835 const bool same_email = gaia::AreEmailsSame(current_email, email);
836 if (!current_email.empty() && !same_email) {
837 UMA_HISTOGRAM_ENUMERATION("Signin.Reauth",
838 signin::HISTOGRAM_ACCOUNT_MISSMATCH,
839 signin::HISTOGRAM_MAX);
841 error_message->assign(
842 l10n_util::GetStringFUTF8(IDS_SYNC_WRONG_EMAIL,
843 base::UTF8ToUTF16(current_email)));
848 // If some profile, not just the current one, is already connected to this
849 // account, don't show the infobar.
850 if (g_browser_process && !same_email) {
851 ProfileManager* manager = g_browser_process->profile_manager();
853 ProfileInfoCache& cache = manager->GetProfileInfoCache();
854 for (size_t i = 0; i < cache.GetNumberOfProfiles(); ++i) {
855 std::string current_email =
856 base::UTF16ToUTF8(cache.GetUserNameOfProfileAtIndex(i));
857 if (gaia::AreEmailsSame(email, current_email)) {
859 error_message->assign(
860 l10n_util::GetStringUTF8(IDS_SYNC_USER_NAME_IN_USE_ERROR));
869 // If email was already rejected by this profile for one-click sign-in.
870 if (can_offer_for == CAN_OFFER_FOR_INTERSTITAL_ONLY) {
871 const base::ListValue* rejected_emails = profile->GetPrefs()->GetList(
872 prefs::kReverseAutologinRejectedEmailList);
873 if (!rejected_emails->empty()) {
874 base::ListValue::const_iterator iter = rejected_emails->Find(
875 base::StringValue(email));
876 if (iter != rejected_emails->end())
882 VLOG(1) << "OneClickSigninHelper::CanOffer: yes we can";
887 OneClickSigninHelper::Offer OneClickSigninHelper::CanOfferOnIOThread(
888 net::URLRequest* request,
889 ProfileIOData* io_data) {
890 return CanOfferOnIOThreadImpl(request->url(), request, io_data);
894 OneClickSigninHelper::Offer OneClickSigninHelper::CanOfferOnIOThreadImpl(
896 base::SupportsUserData* request,
897 ProfileIOData* io_data) {
898 if (!gaia::IsGaiaSignonRealm(url.GetOrigin()))
899 return IGNORE_REQUEST;
904 // Check for incognito before other parts of the io_data, since those
905 // members may not be initalized.
906 if (io_data->IsOffTheRecord())
909 if (!io_data->signin_allowed()->GetValue())
912 if (!io_data->reverse_autologin_enabled()->GetValue())
915 if (!io_data->google_services_username()->GetValue().empty())
918 if (!ChromeSigninClient::SettingsAllowSigninCookies(
919 io_data->GetCookieSettings()))
922 // The checks below depend on chrome already knowing what account the user
923 // signed in with. This happens only after receiving the response containing
924 // the Google-Accounts-SignIn header. Until then, if there is even a chance
925 // that we want to connect the profile, chrome needs to tell Gaia that
926 // it should offer the interstitial. Therefore missing one click data on
927 // the request means can offer is true.
928 const std::string& pending_email = io_data->reverse_autologin_pending_email();
929 if (!pending_email.empty()) {
930 if (!SigninManager::IsUsernameAllowedByPolicy(pending_email,
931 io_data->google_services_username_pattern()->GetValue())) {
935 std::vector<std::string> rejected_emails =
936 io_data->one_click_signin_rejected_email_list()->GetValue();
937 if (std::count_if(rejected_emails.begin(), rejected_emails.end(),
938 std::bind2nd(std::equal_to<std::string>(),
939 pending_email)) > 0) {
943 if (io_data->signin_names()->GetEmails().count(
944 base::UTF8ToUTF16(pending_email)) > 0) {
953 void OneClickSigninHelper::ShowInfoBarIfPossible(net::URLRequest* request,
954 ProfileIOData* io_data,
957 std::string google_chrome_signin_value;
958 std::string google_accounts_signin_value;
959 request->GetResponseHeaderByName("Google-Chrome-SignIn",
960 &google_chrome_signin_value);
961 request->GetResponseHeaderByName("Google-Accounts-SignIn",
962 &google_accounts_signin_value);
964 if (!google_accounts_signin_value.empty() ||
965 !google_chrome_signin_value.empty()) {
966 VLOG(1) << "OneClickSigninHelper::ShowInfoBarIfPossible:"
967 << " g-a-s='" << google_accounts_signin_value << "'"
968 << " g-c-s='" << google_chrome_signin_value << "'";
971 if (!gaia::IsGaiaSignonRealm(request->url().GetOrigin()))
974 // Parse Google-Accounts-SignIn.
975 std::vector<std::pair<std::string, std::string> > pairs;
976 base::SplitStringIntoKeyValuePairs(google_accounts_signin_value, '=', ',',
978 std::string session_index;
980 for (size_t i = 0; i < pairs.size(); ++i) {
981 const std::pair<std::string, std::string>& pair = pairs[i];
982 const std::string& key = pair.first;
983 const std::string& value = pair.second;
984 if (key == "email") {
985 base::TrimString(value, "\"", &email);
986 } else if (key == "sessionindex") {
987 session_index = value;
991 // Later in the chain of this request, we'll need to check the email address
992 // in the IO thread (see CanOfferOnIOThread). So save the email address as
993 // user data on the request (only for web-based flow).
995 io_data->set_reverse_autologin_pending_email(email);
997 if (!email.empty() || !session_index.empty()) {
998 VLOG(1) << "OneClickSigninHelper::ShowInfoBarIfPossible:"
999 << " email=" << email
1000 << " sessionindex=" << session_index;
1003 // Parse Google-Chrome-SignIn.
1004 AutoAccept auto_accept = AUTO_ACCEPT_NONE;
1005 signin::Source source = signin::SOURCE_UNKNOWN;
1007 std::vector<std::string> tokens;
1008 base::SplitString(google_chrome_signin_value, ',', &tokens);
1009 for (size_t i = 0; i < tokens.size(); ++i) {
1010 const std::string& token = tokens[i];
1011 if (token == "accepted") {
1012 auto_accept = AUTO_ACCEPT_ACCEPTED;
1013 } else if (token == "configure") {
1014 auto_accept = AUTO_ACCEPT_CONFIGURE;
1015 } else if (token == "rejected-for-profile") {
1016 auto_accept = AUTO_ACCEPT_REJECTED_FOR_PROFILE;
1020 // If this is an explicit sign in (i.e., first run, NTP, Apps page, menu,
1021 // settings) then force the auto accept type to explicit.
1022 source = GetSigninSource(request->url(), &continue_url);
1023 if (source != signin::SOURCE_UNKNOWN)
1024 auto_accept = AUTO_ACCEPT_EXPLICIT;
1026 if (auto_accept != AUTO_ACCEPT_NONE) {
1027 VLOG(1) << "OneClickSigninHelper::ShowInfoBarIfPossible:"
1028 << " auto_accept=" << auto_accept;
1031 // If |session_index|, |email|, |auto_accept|, and |continue_url| all have
1032 // their default value, don't bother posting a task to the UI thread.
1033 // It will be a noop anyway.
1035 // The two headers above may (but not always) come in different http requests
1036 // so a post to the UI thread is still needed if |auto_accept| is not its
1037 // default value, but |email| and |session_index| are.
1038 if (session_index.empty() && email.empty() &&
1039 auto_accept == AUTO_ACCEPT_NONE && !continue_url.is_valid()) {
1043 content::BrowserThread::PostTask(
1044 content::BrowserThread::UI, FROM_HERE,
1045 base::Bind(&OneClickSigninHelper::ShowInfoBarUIThread, session_index,
1046 email, auto_accept, source, continue_url, child_id, route_id));
1050 void OneClickSigninHelper::LogConfirmHistogramValue(int action) {
1051 UMA_HISTOGRAM_ENUMERATION("Signin.OneClickConfirmation", action,
1052 one_click_signin::HISTOGRAM_CONFIRM_MAX);
1055 void OneClickSigninHelper::ShowInfoBarUIThread(
1056 const std::string& session_index,
1057 const std::string& email,
1058 AutoAccept auto_accept,
1059 signin::Source source,
1060 const GURL& continue_url,
1063 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
1065 content::WebContents* web_contents = tab_util::GetWebContentsByID(child_id,
1070 // TODO(mathp): The appearance of this infobar should be tested using a
1072 OneClickSigninHelper* helper =
1073 OneClickSigninHelper::FromWebContents(web_contents);
1077 if (auto_accept != AUTO_ACCEPT_NONE)
1078 helper->auto_accept_ = auto_accept;
1080 if (source != signin::SOURCE_UNKNOWN &&
1081 helper->source_ == signin::SOURCE_UNKNOWN) {
1082 helper->source_ = source;
1085 // Save the email in the one-click signin manager. The manager may
1086 // not exist if the contents is incognito or if the profile is already
1087 // connected to a Google account.
1088 if (!session_index.empty())
1089 helper->session_index_ = session_index;
1092 helper->email_ = email;
1094 CanOfferFor can_offer_for =
1095 (auto_accept != AUTO_ACCEPT_EXPLICIT &&
1096 helper->auto_accept_ != AUTO_ACCEPT_EXPLICIT) ?
1097 CAN_OFFER_FOR_INTERSTITAL_ONLY : CAN_OFFER_FOR_ALL;
1099 std::string error_message;
1101 if (!web_contents || !CanOffer(web_contents, can_offer_for, email,
1103 VLOG(1) << "OneClickSigninHelper::ShowInfoBarUIThread: not offering";
1104 // TODO(rogerta): Can we just display our error now instead of keeping it
1105 // around and doing it later?
1106 if (helper && helper->error_message_.empty() && !error_message.empty())
1107 helper->error_message_ = error_message;
1112 // Only allow the dedicated signin process to sign the user into
1113 // Chrome without intervention, because it doesn't load any untrusted
1114 // pages. If at any point an untrusted page is detected, chrome will
1115 // show a modal dialog asking the user to confirm.
1117 Profile::FromBrowserContext(web_contents->GetBrowserContext());
1118 SigninClient* signin_client =
1119 profile ? ChromeSigninClientFactory::GetForProfile(profile) : NULL;
1120 helper->untrusted_confirmation_required_ |=
1121 (signin_client && !signin_client->IsSigninProcess(child_id));
1123 if (continue_url.is_valid()) {
1124 // Set |original_continue_url_| if it is currently empty. |continue_url|
1125 // could be modified by gaia pages, thus we need to record the original
1126 // continue url to navigate back to the right page when sync setup is
1128 if (helper->original_continue_url_.is_empty())
1129 helper->original_continue_url_ = continue_url;
1130 helper->continue_url_ = continue_url;
1135 void OneClickSigninHelper::RemoveSigninRedirectURLHistoryItem(
1136 content::WebContents* web_contents) {
1137 // Only actually remove the item if it's the blank.html continue url.
1138 if (signin::IsContinueUrlForWebBasedSigninFlow(
1139 web_contents->GetLastCommittedURL())) {
1140 new CurrentHistoryCleaner(web_contents); // will self-destruct when done
1145 bool OneClickSigninHelper::HandleCrossAccountError(
1147 const std::string& session_index,
1148 const std::string& email,
1149 const std::string& password,
1150 const std::string& refresh_token,
1151 OneClickSigninHelper::AutoAccept auto_accept,
1152 signin::Source source,
1153 OneClickSigninSyncStarter::StartSyncMode start_mode,
1154 OneClickSigninSyncStarter::Callback sync_callback) {
1155 std::string last_email =
1156 profile->GetPrefs()->GetString(prefs::kGoogleServicesLastUsername);
1158 if (!last_email.empty() && !gaia::AreEmailsSame(last_email, email)) {
1159 // If the new email address is different from the email address that
1160 // just signed in, show a confirmation dialog on top of the current active
1163 // No need to display a second confirmation so pass false below.
1164 // TODO(atwilson): Move this into OneClickSigninSyncStarter.
1165 // The tab modal dialog always executes its callback before |contents|
1167 Browser* browser = chrome::FindLastActiveWithProfile(
1168 profile, chrome::GetActiveDesktop());
1169 content::WebContents* contents =
1170 browser->tab_strip_model()->GetActiveWebContents();
1172 ConfirmEmailDialogDelegate::AskForConfirmation(
1178 StartSyncArgs(profile, browser, auto_accept,
1179 session_index, email, password,
1181 contents, false /* confirmation_required */, source,
1192 void OneClickSigninHelper::RedirectToNtpOrAppsPage(
1193 content::WebContents* contents, signin::Source source) {
1194 // Do nothing if a navigation is pending, since this call can be triggered
1195 // from DidStartLoading. This avoids deleting the pending entry while we are
1196 // still navigating to it. See crbug/346632.
1197 if (contents->GetController().GetPendingEntry())
1200 VLOG(1) << "RedirectToNtpOrAppsPage";
1201 // Redirect to NTP/Apps page and display a confirmation bubble
1202 GURL url(source == signin::SOURCE_APPS_PAGE_LINK ?
1203 chrome::kChromeUIAppsURL : chrome::kChromeUINewTabURL);
1204 content::OpenURLParams params(url,
1205 content::Referrer(),
1207 content::PAGE_TRANSITION_AUTO_TOPLEVEL,
1209 contents->OpenURL(params);
1213 void OneClickSigninHelper::RedirectToNtpOrAppsPageIfNecessary(
1214 content::WebContents* contents, signin::Source source) {
1215 if (source != signin::SOURCE_SETTINGS &&
1216 source != signin::SOURCE_WEBSTORE_INSTALL) {
1217 RedirectToNtpOrAppsPage(contents, source);
1221 void OneClickSigninHelper::RedirectToSignin() {
1222 VLOG(1) << "OneClickSigninHelper::RedirectToSignin";
1224 // Extract the existing sounce=X value. Default to "2" if missing.
1225 signin::Source source = signin::GetSourceForPromoURL(continue_url_);
1226 if (source == signin::SOURCE_UNKNOWN)
1227 source = signin::SOURCE_MENU;
1228 GURL page = signin::GetPromoURL(source, false);
1230 content::WebContents* contents = web_contents();
1231 contents->GetController().LoadURL(page,
1232 content::Referrer(),
1233 content::PAGE_TRANSITION_AUTO_TOPLEVEL,
1237 void OneClickSigninHelper::CleanTransientState() {
1238 VLOG(1) << "OneClickSigninHelper::CleanTransientState";
1239 showing_signin_ = false;
1242 auto_accept_ = AUTO_ACCEPT_NONE;
1243 source_ = signin::SOURCE_UNKNOWN;
1244 switched_to_advanced_ = false;
1245 continue_url_ = GURL();
1246 untrusted_navigations_since_signin_visit_ = 0;
1247 untrusted_confirmation_required_ = false;
1248 error_message_.clear();
1250 // Post to IO thread to clear pending email.
1251 if (!do_not_clear_pending_email_) {
1253 Profile::FromBrowserContext(web_contents()->GetBrowserContext());
1254 content::BrowserThread::PostTask(
1255 content::BrowserThread::IO, FROM_HERE,
1256 base::Bind(&ClearPendingEmailOnIOThread,
1257 base::Unretained(profile->GetResourceContext())));
1261 void OneClickSigninHelper::PasswordSubmitted(
1262 const autofill::PasswordForm& form) {
1263 // We only need to scrape the password for Gaia logins.
1264 if (gaia::IsGaiaSignonRealm(GURL(form.signon_realm))) {
1265 VLOG(1) << "OneClickSigninHelper::DidNavigateAnyFrame: got password";
1266 password_ = base::UTF16ToUTF8(form.password_value);
1270 void OneClickSigninHelper::SetDoNotClearPendingEmailForTesting() {
1271 do_not_clear_pending_email_ = true;
1274 void OneClickSigninHelper::set_do_not_start_sync_for_testing() {
1275 do_not_start_sync_for_testing_ = true;
1278 void OneClickSigninHelper::DidStartNavigationToPendingEntry(
1280 content::NavigationController::ReloadType reload_type) {
1281 VLOG(1) << "OneClickSigninHelper::DidStartNavigationToPendingEntry: url=" <<
1283 // If the tab navigates to a new page, and this page is not a valid Gaia
1284 // sign in redirect or reponse, or the expected continue URL, make sure to
1285 // clear the internal state. This is needed to detect navigations in the
1286 // middle of the sign in process that may redirect back to the sign in
1287 // process (see crbug.com/181163 for details).
1288 GURL::Replacements replacements;
1289 replacements.ClearQuery();
1291 if (!IsValidGaiaSigninRedirectOrResponseURL(url) &&
1292 continue_url_.is_valid() &&
1293 url.ReplaceComponents(replacements) !=
1294 continue_url_.ReplaceComponents(replacements)) {
1295 if (++untrusted_navigations_since_signin_visit_ > kMaxNavigationsSince)
1296 CleanTransientState();
1300 void OneClickSigninHelper::DidNavigateMainFrame(
1301 const content::LoadCommittedDetails& details,
1302 const content::FrameNavigateParams& params) {
1303 if (!SigninManager::IsWebBasedSigninFlowURL(params.url)) {
1304 // Make sure the renderer process is no longer considered the trusted
1305 // sign-in process when a navigation to a non-sign-in URL occurs.
1307 Profile::FromBrowserContext(web_contents()->GetBrowserContext());
1308 SigninClient* signin_client =
1309 profile ? ChromeSigninClientFactory::GetForProfile(profile) : NULL;
1310 int process_id = web_contents()->GetRenderProcessHost()->GetID();
1311 if (signin_client && signin_client->IsSigninProcess(process_id))
1312 signin_client->ClearSigninProcess();
1314 // If the navigation to a non-sign-in URL hasn't been triggered by the web
1315 // contents, the sign in flow has been aborted and the state must be
1316 // cleaned (crbug.com/269421).
1317 if (!content::PageTransitionIsWebTriggerable(params.transition) &&
1318 auto_accept_ != AUTO_ACCEPT_NONE) {
1319 CleanTransientState();
1324 void OneClickSigninHelper::DidStopLoading(
1325 content::RenderViewHost* render_view_host) {
1326 // If the user left the sign in process, clear all members.
1327 // TODO(rogerta): might need to allow some youtube URLs.
1328 content::WebContents* contents = web_contents();
1329 const GURL url = contents->GetLastCommittedURL();
1331 Profile::FromBrowserContext(contents->GetBrowserContext());
1332 VLOG(1) << "OneClickSigninHelper::DidStopLoading: url=" << url.spec();
1334 if (url.scheme() == content::kChromeUIScheme) {
1335 // Suppresses OneClickSigninHelper on webUI pages to avoid inteference with
1336 // inline signin flows.
1337 VLOG(1) << "OneClickSigninHelper::DidStopLoading: suppressed for url="
1339 CleanTransientState();
1343 // If an error has already occured during the sign in flow, make sure to
1344 // display it to the user and abort the process. Do this only for
1345 // explicit sign ins.
1346 // TODO(rogerta): Could we move this code back up to ShowInfoBarUIThread()?
1347 if (!error_message_.empty() && auto_accept_ == AUTO_ACCEPT_EXPLICIT) {
1348 VLOG(1) << "OneClickSigninHelper::DidStopLoading: error=" << error_message_;
1349 RemoveSigninRedirectURLHistoryItem(contents);
1350 // After we redirect to NTP, our browser pointer gets corrupted because the
1351 // WebContents have changed, so grab the browser pointer
1352 // before the navigation.
1353 Browser* browser = chrome::FindBrowserWithWebContents(contents);
1355 // Redirect to the landing page and display an error popup.
1356 RedirectToNtpOrAppsPage(web_contents(), source_);
1357 LoginUIServiceFactory::GetForProfile(profile)->
1358 DisplayLoginResult(browser, base::UTF8ToUTF16(error_message_));
1359 CleanTransientState();
1363 if (AreWeShowingSignin(url, source_, email_)) {
1364 if (!showing_signin_) {
1365 if (source_ == signin::SOURCE_UNKNOWN)
1366 LogOneClickHistogramValue(one_click_signin::HISTOGRAM_SHOWN);
1368 LogHistogramValue(source_, one_click_signin::HISTOGRAM_SHOWN);
1370 showing_signin_ = true;
1373 // When Gaia finally redirects to the continue URL, Gaia will add some
1374 // extra query parameters. So ignore the parameters when checking to see
1375 // if the user has continued. Sometimes locales will redirect to a country-
1376 // specific TLD so just make sure it's a valid domain instead of comparing
1377 // for an exact match.
1378 GURL::Replacements replacements;
1379 replacements.ClearQuery();
1380 bool google_domain_url = google_util::IsGoogleDomainUrl(
1382 google_util::ALLOW_SUBDOMAIN,
1383 google_util::DISALLOW_NON_STANDARD_PORTS);
1384 const bool continue_url_match =
1385 google_domain_url &&
1386 url.ReplaceComponents(replacements).path() ==
1387 continue_url_.ReplaceComponents(replacements).path();
1388 const bool original_continue_url_match =
1389 google_domain_url &&
1390 url.ReplaceComponents(replacements).path() ==
1391 original_continue_url_.ReplaceComponents(replacements).path();
1393 if (continue_url_match)
1394 RemoveSigninRedirectURLHistoryItem(contents);
1396 // If there is no valid email yet, there is nothing to do. As of M26, the
1397 // password is allowed to be empty, since its no longer required to setup
1399 if (email_.empty()) {
1400 VLOG(1) << "OneClickSigninHelper::DidStopLoading: nothing to do";
1401 // Original-url check done because some user actions cans get us to a page
1402 // via a POST instead of a GET (and thus to immediate "cuntinue url") but
1403 // we still want redirects from the "blank.html" landing page to work for
1404 // non-security related redirects like NTP.
1405 // https://code.google.com/p/chromium/issues/detail?id=321938
1406 if (original_continue_url_match) {
1407 if (auto_accept_ == AUTO_ACCEPT_EXPLICIT)
1409 std::string unused_value;
1410 if (net::GetValueForKeyInQuery(url, "ntp", &unused_value)) {
1411 signin::SetUserSkippedPromo(profile);
1412 RedirectToNtpOrAppsPage(web_contents(), source_);
1415 if (!IsValidGaiaSigninRedirectOrResponseURL(url) &&
1416 ++untrusted_navigations_since_signin_visit_ > kMaxNavigationsSince) {
1417 CleanTransientState();
1424 if (!continue_url_match && IsValidGaiaSigninRedirectOrResponseURL(url))
1427 // During an explicit sign in, if the user has not yet reached the final
1428 // continue URL, wait for it to arrive. Note that Gaia will add some extra
1429 // query parameters to the continue URL. Ignore them when checking to
1430 // see if the user has continued.
1432 // If this is not an explicit sign in, we don't need to check if we landed
1433 // on the right continue URL. This is important because the continue URL
1434 // may itself lead to a redirect, which means this function will never see
1435 // the continue URL go by.
1436 if (auto_accept_ == AUTO_ACCEPT_EXPLICIT) {
1437 DCHECK(source_ != signin::SOURCE_UNKNOWN);
1438 if (!continue_url_match) {
1439 VLOG(1) << "OneClickSigninHelper::DidStopLoading: invalid url='"
1441 << "' expected continue url=" << continue_url_;
1442 CleanTransientState();
1446 // In explicit sign ins, the user may have changed the box
1447 // "Let me choose what to sync". This is reflected as a change in the
1448 // source of the continue URL. Make one last check of the current URL
1449 // to see if there is a valid source. If so, it overrides the
1452 // If the source was changed to SOURCE_SETTINGS, we want
1453 // OneClickSigninSyncStarter to reuse the current tab to display the
1454 // advanced configuration.
1455 signin::Source source = signin::GetSourceForPromoURL(url);
1456 if (source != source_) {
1458 switched_to_advanced_ = source == signin::SOURCE_SETTINGS;
1462 Browser* browser = chrome::FindBrowserWithWebContents(contents);
1464 VLOG(1) << "OneClickSigninHelper::DidStopLoading: signin is go."
1465 << " auto_accept=" << auto_accept_
1466 << " source=" << source_;
1468 switch (auto_accept_) {
1469 case AUTO_ACCEPT_NONE:
1470 if (showing_signin_)
1471 LogOneClickHistogramValue(one_click_signin::HISTOGRAM_DISMISSED);
1473 case AUTO_ACCEPT_ACCEPTED:
1474 LogOneClickHistogramValue(one_click_signin::HISTOGRAM_ACCEPTED);
1475 LogOneClickHistogramValue(one_click_signin::HISTOGRAM_WITH_DEFAULTS);
1476 SigninManager::DisableOneClickSignIn(profile->GetPrefs());
1477 // Start syncing with the default settings - prompt the user to sign in
1479 if (!do_not_start_sync_for_testing_) {
1481 StartSyncArgs(profile, browser, auto_accept_,
1482 session_index_, email_, password_, "",
1483 NULL /* don't force sync setup in same tab */,
1484 true /* confirmation_required */, source_,
1485 CreateSyncStarterCallback()),
1486 OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS);
1489 case AUTO_ACCEPT_CONFIGURE:
1490 LogOneClickHistogramValue(one_click_signin::HISTOGRAM_ACCEPTED);
1491 LogOneClickHistogramValue(one_click_signin::HISTOGRAM_WITH_ADVANCED);
1492 SigninManager::DisableOneClickSignIn(profile->GetPrefs());
1493 // Display the extra confirmation (even in the SAML case) in case this
1494 // was an untrusted renderer.
1495 if (!do_not_start_sync_for_testing_) {
1497 StartSyncArgs(profile, browser, auto_accept_,
1498 session_index_, email_, password_, "",
1499 NULL /* don't force sync setup in same tab */,
1500 true /* confirmation_required */, source_,
1501 CreateSyncStarterCallback()),
1502 OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST);
1505 case AUTO_ACCEPT_EXPLICIT: {
1506 signin::Source original_source =
1507 signin::GetSourceForPromoURL(original_continue_url_);
1508 if (switched_to_advanced_) {
1509 LogHistogramValue(original_source,
1510 one_click_signin::HISTOGRAM_WITH_ADVANCED);
1511 LogHistogramValue(original_source,
1512 one_click_signin::HISTOGRAM_ACCEPTED);
1514 LogHistogramValue(source_, one_click_signin::HISTOGRAM_ACCEPTED);
1515 LogHistogramValue(source_, one_click_signin::HISTOGRAM_WITH_DEFAULTS);
1518 // - If sign in was initiated from the NTP or the hotdog menu, sync with
1519 // default settings.
1520 // - If sign in was initiated from the settings page for first time sync
1521 // set up, show the advanced sync settings dialog.
1522 // - If sign in was initiated from the settings page due to a re-auth when
1523 // sync was already setup, simply navigate back to the settings page.
1524 ProfileSyncService* sync_service =
1525 ProfileSyncServiceFactory::GetForProfile(profile);
1526 SigninErrorController* error_controller =
1527 ProfileOAuth2TokenServiceFactory::GetForProfile(profile)->
1528 signin_error_controller();
1530 OneClickSigninSyncStarter::StartSyncMode start_mode =
1531 source_ == signin::SOURCE_SETTINGS ?
1532 (error_controller->HasError() &&
1533 sync_service && sync_service->HasSyncSetupCompleted()) ?
1534 OneClickSigninSyncStarter::SHOW_SETTINGS_WITHOUT_CONFIGURE :
1535 OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST :
1536 OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS;
1538 if (!HandleCrossAccountError(profile, session_index_, email_, password_,
1539 "", auto_accept_, source_, start_mode,
1540 CreateSyncStarterCallback())) {
1541 if (!do_not_start_sync_for_testing_) {
1543 StartSyncArgs(profile, browser, auto_accept_,
1544 session_index_, email_, password_, "",
1546 untrusted_confirmation_required_, source_,
1547 CreateSyncStarterCallback()),
1551 // If this explicit sign in is not from settings page/webstore, show
1552 // the NTP/Apps page after sign in completes. In the case of the
1553 // settings page, it will get auto-closed after sync setup. In the case
1554 // of webstore, it will redirect back to webstore.
1555 RedirectToNtpOrAppsPageIfNecessary(web_contents(), source_);
1558 // Observe the sync service if the Webstore tab or the settings tab
1559 // requested a gaia sign in, so that when sign in and sync setup are
1560 // successful, we can redirect to the correct URL, or auto-close the gaia
1562 if (original_source == signin::SOURCE_SETTINGS ||
1563 (original_source == signin::SOURCE_WEBSTORE_INSTALL &&
1564 source_ == signin::SOURCE_SETTINGS)) {
1565 // The observer deletes itself once it's done.
1566 new OneClickSigninSyncObserver(contents, original_continue_url_);
1570 case AUTO_ACCEPT_REJECTED_FOR_PROFILE:
1571 AddEmailToOneClickRejectedList(profile, email_);
1572 LogOneClickHistogramValue(one_click_signin::HISTOGRAM_REJECTED);
1575 NOTREACHED() << "Invalid auto_accept=" << auto_accept_;
1579 CleanTransientState();
1582 OneClickSigninSyncStarter::Callback
1583 OneClickSigninHelper::CreateSyncStarterCallback() {
1584 // The callback will only be invoked if this object is still alive when sync
1585 // setup is completed. This is correct because this object is only deleted
1586 // when the web contents that potentially shows a blank page is deleted.
1587 return base::Bind(&OneClickSigninHelper::SyncSetupCompletedCallback,
1588 weak_pointer_factory_.GetWeakPtr());
1591 void OneClickSigninHelper::SyncSetupCompletedCallback(
1592 OneClickSigninSyncStarter::SyncSetupResult result) {
1593 if (result == OneClickSigninSyncStarter::SYNC_SETUP_FAILURE &&
1595 GURL current_url = web_contents()->GetVisibleURL();
1597 // If the web contents is showing a blank page and not about to be closed,
1598 // redirect to the NTP or apps page.
1599 if (signin::IsContinueUrlForWebBasedSigninFlow(current_url) &&
1600 !signin::IsAutoCloseEnabledInURL(original_continue_url_)) {
1601 RedirectToNtpOrAppsPage(
1603 signin::GetSourceForPromoURL(original_continue_url_));