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/google/google_util.h"
31 #include "chrome/browser/history/history_service.h"
32 #include "chrome/browser/history/history_service_factory.h"
33 #include "chrome/browser/profiles/profile.h"
34 #include "chrome/browser/profiles/profile_info_cache.h"
35 #include "chrome/browser/profiles/profile_io_data.h"
36 #include "chrome/browser/profiles/profile_manager.h"
37 #include "chrome/browser/search/search.h"
38 #include "chrome/browser/signin/chrome_signin_client.h"
39 #include "chrome/browser/signin/chrome_signin_client_factory.h"
40 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
41 #include "chrome/browser/signin/signin_manager_factory.h"
42 #include "chrome/browser/signin/signin_names_io_thread.h"
43 #include "chrome/browser/sync/profile_sync_service.h"
44 #include "chrome/browser/sync/profile_sync_service_factory.h"
45 #include "chrome/browser/tab_contents/tab_util.h"
46 #include "chrome/browser/ui/browser_finder.h"
47 #include "chrome/browser/ui/browser_list.h"
48 #include "chrome/browser/ui/browser_tabstrip.h"
49 #include "chrome/browser/ui/browser_window.h"
50 #include "chrome/browser/ui/chrome_pages.h"
51 #include "chrome/browser/ui/sync/one_click_signin_histogram.h"
52 #include "chrome/browser/ui/sync/one_click_signin_sync_observer.h"
53 #include "chrome/browser/ui/sync/one_click_signin_sync_starter.h"
54 #include "chrome/browser/ui/sync/signin_histogram.h"
55 #include "chrome/browser/ui/tab_modal_confirm_dialog.h"
56 #include "chrome/browser/ui/tab_modal_confirm_dialog_delegate.h"
57 #include "chrome/browser/ui/tabs/tab_strip_model.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/password_manager/core/browser/password_manager.h"
64 #include "components/signin/core/browser/profile_oauth2_token_service.h"
65 #include "components/signin/core/browser/signin_client.h"
66 #include "components/signin/core/browser/signin_error_controller.h"
67 #include "components/signin/core/browser/signin_manager.h"
68 #include "components/signin/core/browser/signin_manager_cookie_helper.h"
69 #include "components/signin/core/common/profile_management_switches.h"
70 #include "components/sync_driver/sync_prefs.h"
71 #include "content/public/browser/browser_thread.h"
72 #include "content/public/browser/navigation_entry.h"
73 #include "content/public/browser/page_navigator.h"
74 #include "content/public/browser/render_process_host.h"
75 #include "content/public/browser/web_contents.h"
76 #include "content/public/browser/web_contents_delegate.h"
77 #include "content/public/common/frame_navigate_params.h"
78 #include "content/public/common/page_transition_types.h"
79 #include "google_apis/gaia/gaia_auth_util.h"
80 #include "google_apis/gaia/gaia_urls.h"
81 #include "grit/chromium_strings.h"
82 #include "grit/generated_resources.h"
83 #include "grit/theme_resources.h"
84 #include "ipc/ipc_message_macros.h"
85 #include "net/base/url_util.h"
86 #include "net/cookies/cookie_monster.h"
87 #include "net/url_request/url_request.h"
88 #include "ui/base/l10n/l10n_util.h"
89 #include "ui/base/resource/resource_bundle.h"
95 // ConfirmEmailDialogDelegate -------------------------------------------------
97 class ConfirmEmailDialogDelegate : public TabModalConfirmDialogDelegate {
105 // Callback indicating action performed by the user.
106 typedef base::Callback<void(Action)> Callback;
108 // Ask the user for confirmation before starting to sync.
109 static void AskForConfirmation(content::WebContents* contents,
110 const std::string& last_email,
111 const std::string& email,
115 ConfirmEmailDialogDelegate(content::WebContents* contents,
116 const std::string& last_email,
117 const std::string& email,
119 virtual ~ConfirmEmailDialogDelegate();
121 // TabModalConfirmDialogDelegate:
122 virtual base::string16 GetTitle() OVERRIDE;
123 virtual base::string16 GetDialogMessage() OVERRIDE;
124 virtual base::string16 GetAcceptButtonTitle() OVERRIDE;
125 virtual base::string16 GetCancelButtonTitle() OVERRIDE;
126 virtual base::string16 GetLinkText() const OVERRIDE;
127 virtual void OnAccepted() OVERRIDE;
128 virtual void OnCanceled() OVERRIDE;
129 virtual void OnClosed() OVERRIDE;
130 virtual void OnLinkClicked(WindowOpenDisposition disposition) OVERRIDE;
132 std::string last_email_;
136 // Web contents from which the "Learn more" link should be opened.
137 content::WebContents* web_contents_;
139 DISALLOW_COPY_AND_ASSIGN(ConfirmEmailDialogDelegate);
143 void ConfirmEmailDialogDelegate::AskForConfirmation(
144 content::WebContents* contents,
145 const std::string& last_email,
146 const std::string& email,
148 TabModalConfirmDialog::Create(
149 new ConfirmEmailDialogDelegate(contents, last_email, email,
150 callback), contents);
153 ConfirmEmailDialogDelegate::ConfirmEmailDialogDelegate(
154 content::WebContents* contents,
155 const std::string& last_email,
156 const std::string& email,
158 : TabModalConfirmDialogDelegate(contents),
159 last_email_(last_email),
162 web_contents_(contents) {
165 ConfirmEmailDialogDelegate::~ConfirmEmailDialogDelegate() {
168 base::string16 ConfirmEmailDialogDelegate::GetTitle() {
169 return l10n_util::GetStringUTF16(
170 IDS_ONE_CLICK_SIGNIN_CONFIRM_EMAIL_DIALOG_TITLE);
173 base::string16 ConfirmEmailDialogDelegate::GetDialogMessage() {
174 return l10n_util::GetStringFUTF16(
175 IDS_ONE_CLICK_SIGNIN_CONFIRM_EMAIL_DIALOG_MESSAGE,
176 base::UTF8ToUTF16(last_email_), base::UTF8ToUTF16(email_));
179 base::string16 ConfirmEmailDialogDelegate::GetAcceptButtonTitle() {
180 return l10n_util::GetStringUTF16(
181 IDS_ONE_CLICK_SIGNIN_CONFIRM_EMAIL_DIALOG_OK_BUTTON);
184 base::string16 ConfirmEmailDialogDelegate::GetCancelButtonTitle() {
185 return l10n_util::GetStringUTF16(
186 IDS_ONE_CLICK_SIGNIN_CONFIRM_EMAIL_DIALOG_CANCEL_BUTTON);
189 base::string16 ConfirmEmailDialogDelegate::GetLinkText() const {
190 return l10n_util::GetStringUTF16(IDS_LEARN_MORE);
193 void ConfirmEmailDialogDelegate::OnAccepted() {
194 base::ResetAndReturn(&callback_).Run(CREATE_NEW_USER);
197 void ConfirmEmailDialogDelegate::OnCanceled() {
198 base::ResetAndReturn(&callback_).Run(START_SYNC);
201 void ConfirmEmailDialogDelegate::OnClosed() {
202 base::ResetAndReturn(&callback_).Run(CLOSE);
205 void ConfirmEmailDialogDelegate::OnLinkClicked(
206 WindowOpenDisposition disposition) {
207 content::OpenURLParams params(
208 GURL(chrome::kChromeSyncMergeTroubleshootingURL),
211 content::PAGE_TRANSITION_AUTO_TOPLEVEL,
213 // It is guaranteed that |web_contents_| is valid here because when it's
214 // deleted, the dialog is immediately closed and no further action can be
216 web_contents_->OpenURL(params);
220 // Helpers --------------------------------------------------------------------
222 // Add a specific email to the list of emails rejected for one-click
223 // sign-in, for this profile.
224 void AddEmailToOneClickRejectedList(Profile* profile,
225 const std::string& email) {
226 ListPrefUpdate updater(profile->GetPrefs(),
227 prefs::kReverseAutologinRejectedEmailList);
228 updater->AppendIfNotPresent(new base::StringValue(email));
231 void LogOneClickHistogramValue(int action) {
232 UMA_HISTOGRAM_ENUMERATION("Signin.OneClickActions", action,
233 one_click_signin::HISTOGRAM_MAX);
234 UMA_HISTOGRAM_ENUMERATION("Signin.AllAccessPointActions", action,
235 one_click_signin::HISTOGRAM_MAX);
238 void RedirectToNtpOrAppsPageWithIds(int child_id,
240 signin::Source source) {
241 content::WebContents* web_contents = tab_util::GetWebContentsByID(child_id,
246 OneClickSigninHelper::RedirectToNtpOrAppsPage(web_contents, source);
249 // Start syncing with the given user information.
250 void StartSync(const OneClickSigninHelper::StartSyncArgs& args,
251 OneClickSigninSyncStarter::StartSyncMode start_mode) {
252 if (start_mode == OneClickSigninSyncStarter::UNDO_SYNC) {
253 LogOneClickHistogramValue(one_click_signin::HISTOGRAM_UNDO);
257 // The wrapper deletes itself once it's done.
258 OneClickSigninHelper::SyncStarterWrapper* wrapper =
259 new OneClickSigninHelper::SyncStarterWrapper(args, start_mode);
262 int action = one_click_signin::HISTOGRAM_MAX;
263 switch (args.auto_accept) {
264 case OneClickSigninHelper::AUTO_ACCEPT_EXPLICIT:
266 case OneClickSigninHelper::AUTO_ACCEPT_ACCEPTED:
268 start_mode == OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS ?
269 one_click_signin::HISTOGRAM_AUTO_WITH_DEFAULTS :
270 one_click_signin::HISTOGRAM_AUTO_WITH_ADVANCED;
272 case OneClickSigninHelper::AUTO_ACCEPT_CONFIGURE:
273 DCHECK(start_mode == OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST);
274 action = one_click_signin::HISTOGRAM_AUTO_WITH_ADVANCED;
277 NOTREACHED() << "Invalid auto_accept: " << args.auto_accept;
280 if (action != one_click_signin::HISTOGRAM_MAX)
281 LogOneClickHistogramValue(action);
284 void StartExplicitSync(const OneClickSigninHelper::StartSyncArgs& args,
285 content::WebContents* contents,
286 OneClickSigninSyncStarter::StartSyncMode start_mode,
287 ConfirmEmailDialogDelegate::Action action) {
288 bool enable_inline = !switches::IsEnableWebBasedSignin();
289 if (action == ConfirmEmailDialogDelegate::START_SYNC) {
290 StartSync(args, start_mode);
291 if (!enable_inline) {
292 // Redirect/tab closing for inline flow is handled by the sync callback.
293 OneClickSigninHelper::RedirectToNtpOrAppsPageIfNecessary(
294 contents, args.source);
297 // Perform a redirection to the NTP/Apps page to hide the blank page when
298 // the action is CLOSE or CREATE_NEW_USER. The redirection is useful when
299 // the action is CREATE_NEW_USER because the "Create new user" page might
300 // be opened in a different tab that is already showing settings.
302 // Redirect/tab closing for inline flow is handled by the sync callback.
303 args.callback.Run(OneClickSigninSyncStarter::SYNC_SETUP_FAILURE);
305 // Don't redirect when the visible URL is not a blank page: if the
306 // source is SOURCE_WEBSTORE_INSTALL, |contents| might be showing an app
307 // page that shouldn't be hidden.
309 // If redirecting, don't do so immediately, otherwise there may be 2
310 // nested navigations and a crash would occur (crbug.com/293261). Post
311 // the task to the current thread instead.
312 if (signin::IsContinueUrlForWebBasedSigninFlow(
313 contents->GetVisibleURL())) {
314 base::MessageLoopProxy::current()->PostNonNestableTask(
316 base::Bind(RedirectToNtpOrAppsPageWithIds,
317 contents->GetRenderProcessHost()->GetID(),
318 contents->GetRoutingID(),
322 if (action == ConfirmEmailDialogDelegate::CREATE_NEW_USER) {
323 chrome::ShowSettingsSubPage(args.browser,
324 std::string(chrome::kCreateProfileSubPage));
329 void ClearPendingEmailOnIOThread(content::ResourceContext* context) {
330 ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
332 io_data->set_reverse_autologin_pending_email(std::string());
335 // Determines the source of the sign in and the continue URL. It's either one
336 // of the known sign-in access points (first run, NTP, Apps page, menu, or
337 // settings) or it's an implicit sign in via another Google property. In the
338 // former case, "service" is also checked to make sure its "chromiumsync".
339 signin::Source GetSigninSource(const GURL& url, GURL* continue_url) {
340 DCHECK(url.is_valid());
342 net::GetValueForKeyInQuery(url, "service", &value);
343 bool possibly_an_explicit_signin = value == "chromiumsync";
345 // Find the final continue URL for this sign in. In some cases, Gaia can
346 // continue to itself, with the original continue URL buried under a couple
347 // of layers of indirection. Peel those layers away. The final destination
348 // can also be "IsGaiaSignonRealm" so stop if we get to the end (but be sure
349 // we always extract at least one "continue" value).
350 GURL local_continue_url = signin::GetNextPageURLForPromoURL(url);
351 while (gaia::IsGaiaSignonRealm(local_continue_url.GetOrigin())) {
352 GURL next_continue_url =
353 signin::GetNextPageURLForPromoURL(local_continue_url);
354 if (!next_continue_url.is_valid())
356 local_continue_url = next_continue_url;
359 if (continue_url && local_continue_url.is_valid()) {
360 DCHECK(!continue_url->is_valid() || *continue_url == local_continue_url);
361 *continue_url = local_continue_url;
364 return possibly_an_explicit_signin ?
365 signin::GetSourceForPromoURL(local_continue_url) :
366 signin::SOURCE_UNKNOWN;
369 // Returns true if |url| is a valid URL that can occur during the sign in
370 // process. Valid URLs are of the form:
372 // https://accounts.google.{TLD}/...
373 // https://accounts.youtube.com/...
374 // https://accounts.blogger.com/...
376 // All special headers used by one click sign in occur on
377 // https://accounts.google.com URLs. However, the sign in process may redirect
378 // to intermediate Gaia URLs that do not end with .com. For example, an account
379 // that uses SMS 2-factor outside the US may redirect to country specific URLs.
381 // The sign in process may also redirect to youtube and blogger account URLs
382 // so that Gaia acts as a single signon service.
383 bool IsValidGaiaSigninRedirectOrResponseURL(const GURL& url) {
384 std::string hostname = url.host();
385 if (google_util::IsGoogleHostname(hostname, google_util::ALLOW_SUBDOMAIN)) {
386 // Also using IsGaiaSignonRealm() to handle overriding with command line.
387 return gaia::IsGaiaSignonRealm(url.GetOrigin()) ||
388 StartsWithASCII(hostname, "accounts.", false);
391 GURL origin = url.GetOrigin();
392 if (origin == GURL("https://accounts.youtube.com") ||
393 origin == GURL("https://accounts.blogger.com"))
399 // Tells when we are in the process of showing either the signin to chrome page
400 // or the one click sign in to chrome page.
401 // NOTE: This should only be used for logging purposes since it relies on hard
402 // coded URLs that could change.
403 bool AreWeShowingSignin(GURL url, signin::Source source, std::string email) {
404 GURL::Replacements replacements;
405 replacements.ClearQuery();
406 GURL clean_login_url =
407 GaiaUrls::GetInstance()->service_login_url().ReplaceComponents(
410 return (url.ReplaceComponents(replacements) == clean_login_url &&
411 source != signin::SOURCE_UNKNOWN) ||
412 (IsValidGaiaSigninRedirectOrResponseURL(url) &&
413 url.spec().find("ChromeLoginPrompt") != std::string::npos &&
417 // CurrentHistoryCleaner ------------------------------------------------------
419 // Watch a webcontents and remove URL from the history once loading is complete.
420 // We have to delay the cleaning until the new URL has finished loading because
421 // we're not allowed to remove the last-loaded URL from the history. Objects
422 // of this type automatically self-destruct once they're finished their work.
423 class CurrentHistoryCleaner : public content::WebContentsObserver {
425 explicit CurrentHistoryCleaner(content::WebContents* contents);
426 virtual ~CurrentHistoryCleaner();
428 // content::WebContentsObserver:
429 virtual void WebContentsDestroyed() OVERRIDE;
430 virtual void DidCommitProvisionalLoadForFrame(
432 const base::string16& frame_unique_name,
435 content::PageTransition transition_type,
436 content::RenderViewHost* render_view_host) OVERRIDE;
439 scoped_ptr<content::WebContents> contents_;
440 int history_index_to_remove_;
442 DISALLOW_COPY_AND_ASSIGN(CurrentHistoryCleaner);
445 CurrentHistoryCleaner::CurrentHistoryCleaner(content::WebContents* contents)
446 : WebContentsObserver(contents) {
447 history_index_to_remove_ =
448 web_contents()->GetController().GetLastCommittedEntryIndex();
451 CurrentHistoryCleaner::~CurrentHistoryCleaner() {
454 void CurrentHistoryCleaner::DidCommitProvisionalLoadForFrame(
456 const base::string16& frame_unique_name,
459 content::PageTransition transition_type,
460 content::RenderViewHost* render_view_host) {
461 // Return early if this is not top-level navigation.
465 content::NavigationController* nc = &web_contents()->GetController();
466 HistoryService* hs = HistoryServiceFactory::GetForProfile(
467 Profile::FromBrowserContext(web_contents()->GetBrowserContext()),
468 Profile::IMPLICIT_ACCESS);
470 // Have to wait until something else gets added to history before removal.
471 if (history_index_to_remove_ < nc->GetLastCommittedEntryIndex()) {
472 content::NavigationEntry* entry =
473 nc->GetEntryAtIndex(history_index_to_remove_);
474 if (signin::IsContinueUrlForWebBasedSigninFlow(entry->GetURL())) {
475 hs->DeleteURL(entry->GetURL());
476 nc->RemoveEntryAtIndex(history_index_to_remove_);
477 delete this; // Success.
482 void CurrentHistoryCleaner::WebContentsDestroyed() {
483 delete this; // Failure.
489 // StartSyncArgs --------------------------------------------------------------
491 OneClickSigninHelper::StartSyncArgs::StartSyncArgs()
494 auto_accept(AUTO_ACCEPT_NONE),
496 confirmation_required(OneClickSigninSyncStarter::NO_CONFIRMATION),
497 source(signin::SOURCE_UNKNOWN) {}
499 OneClickSigninHelper::StartSyncArgs::StartSyncArgs(
502 OneClickSigninHelper::AutoAccept auto_accept,
503 const std::string& session_index,
504 const std::string& email,
505 const std::string& password,
506 const std::string& refresh_token,
507 content::WebContents* web_contents,
508 bool untrusted_confirmation_required,
509 signin::Source source,
510 OneClickSigninSyncStarter::Callback callback)
513 auto_accept(auto_accept),
514 session_index(session_index),
517 refresh_token(refresh_token),
518 web_contents(web_contents),
521 DCHECK(session_index.empty() != refresh_token.empty());
522 if (untrusted_confirmation_required) {
523 confirmation_required = OneClickSigninSyncStarter::CONFIRM_UNTRUSTED_SIGNIN;
524 } else if (source == signin::SOURCE_SETTINGS ||
525 source == signin::SOURCE_WEBSTORE_INSTALL) {
526 // Do not display a status confirmation for webstore installs or re-auth.
527 confirmation_required = OneClickSigninSyncStarter::NO_CONFIRMATION;
529 confirmation_required = OneClickSigninSyncStarter::CONFIRM_AFTER_SIGNIN;
533 OneClickSigninHelper::StartSyncArgs::~StartSyncArgs() {}
535 // SyncStarterWrapper ---------------------------------------------------------
537 OneClickSigninHelper::SyncStarterWrapper::SyncStarterWrapper(
538 const OneClickSigninHelper::StartSyncArgs& args,
539 OneClickSigninSyncStarter::StartSyncMode start_mode)
540 : args_(args), start_mode_(start_mode), weak_pointer_factory_(this) {
541 BrowserList::AddObserver(this);
543 // Cache the parent desktop for the browser, so we can reuse that same
544 // desktop for any UI we want to display.
545 desktop_type_ = args_.browser ? args_.browser->host_desktop_type()
546 : chrome::GetActiveDesktop();
549 OneClickSigninHelper::SyncStarterWrapper::~SyncStarterWrapper() {
550 BrowserList::RemoveObserver(this);
553 void OneClickSigninHelper::SyncStarterWrapper::Start() {
554 if (args_.refresh_token.empty()) {
555 if (args_.password.empty()) {
556 VerifyGaiaCookiesBeforeSignIn();
558 StartSigninOAuthHelper();
561 OnSigninOAuthInformationAvailable(args_.email, args_.email,
562 args_.refresh_token);
567 OneClickSigninHelper::SyncStarterWrapper::OnSigninOAuthInformationAvailable(
568 const std::string& email,
569 const std::string& display_email,
570 const std::string& refresh_token) {
571 if (!gaia::AreEmailsSame(display_email, args_.email)) {
573 GoogleServiceAuthError(
574 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS).ToString());
576 StartOneClickSigninSyncStarter(email, refresh_token);
579 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
582 void OneClickSigninHelper::SyncStarterWrapper::OnSigninOAuthInformationFailure(
583 const GoogleServiceAuthError& error) {
584 DisplayErrorBubble(error.ToString());
585 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
588 void OneClickSigninHelper::SyncStarterWrapper::OnBrowserRemoved(
590 if (args_.browser == browser)
591 args_.browser = NULL;
594 void OneClickSigninHelper::SyncStarterWrapper::VerifyGaiaCookiesBeforeSignIn() {
595 scoped_refptr<SigninManagerCookieHelper> cookie_helper(
596 new SigninManagerCookieHelper(
597 args_.profile->GetRequestContext(),
598 content::BrowserThread::GetMessageLoopProxyForThread(
599 content::BrowserThread::UI),
600 content::BrowserThread::GetMessageLoopProxyForThread(
601 content::BrowserThread::IO)));
602 cookie_helper->StartFetchingGaiaCookiesOnUIThread(
603 base::Bind(&SyncStarterWrapper::OnGaiaCookiesFetched,
604 weak_pointer_factory_.GetWeakPtr(),
605 args_.session_index));
608 void OneClickSigninHelper::SyncStarterWrapper::OnGaiaCookiesFetched(
609 const std::string session_index, const net::CookieList& cookie_list) {
610 net::CookieList::const_iterator it;
611 bool success = false;
612 for (it = cookie_list.begin(); it != cookie_list.end(); ++it) {
613 // Make sure the LSID cookie is set on the GAIA host, instead of a super-
615 if (it->Name() == "LSID") {
616 if (it->IsHostCookie() && it->IsHttpOnly() && it->IsSecure()) {
617 // Found a valid LSID cookie. Continue loop to make sure we don't have
618 // invalid LSID cookies on any super-domain.
628 StartSigninOAuthHelper();
631 GoogleServiceAuthError(
632 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS).ToString());
633 base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
637 void OneClickSigninHelper::SyncStarterWrapper::DisplayErrorBubble(
638 const std::string& error_message) {
639 args_.browser = OneClickSigninSyncStarter::EnsureBrowser(
640 args_.browser, args_.profile, desktop_type_);
641 args_.browser->window()->ShowOneClickSigninBubble(
642 BrowserWindow::ONE_CLICK_SIGNIN_BUBBLE_TYPE_BUBBLE,
643 base::string16(), // No email required - this is not a SAML confirmation.
644 base::UTF8ToUTF16(error_message),
645 // Callback is ignored.
646 BrowserWindow::StartSyncCallback());
649 void OneClickSigninHelper::SyncStarterWrapper::StartSigninOAuthHelper() {
650 signin_oauth_helper_.reset(
651 new SigninOAuthHelper(args_.profile->GetRequestContext(),
652 args_.session_index, this));
656 OneClickSigninHelper::SyncStarterWrapper::StartOneClickSigninSyncStarter(
657 const std::string& email,
658 const std::string& refresh_token) {
659 // The starter deletes itself once it's done.
660 new OneClickSigninSyncStarter(args_.profile, args_.browser,
661 email, args_.password,
662 refresh_token, start_mode_,
664 args_.confirmation_required,
670 // OneClickSigninHelper -------------------------------------------------------
672 DEFINE_WEB_CONTENTS_USER_DATA_KEY(OneClickSigninHelper);
675 const int OneClickSigninHelper::kMaxNavigationsSince = 10;
677 OneClickSigninHelper::OneClickSigninHelper(
678 content::WebContents* web_contents,
679 password_manager::PasswordManager* password_manager)
680 : content::WebContentsObserver(web_contents),
681 showing_signin_(false),
682 auto_accept_(AUTO_ACCEPT_NONE),
683 source_(signin::SOURCE_UNKNOWN),
684 switched_to_advanced_(false),
685 untrusted_navigations_since_signin_visit_(0),
686 untrusted_confirmation_required_(false),
687 do_not_clear_pending_email_(false),
688 do_not_start_sync_for_testing_(false),
689 weak_pointer_factory_(this) {
690 // May be NULL during testing.
691 if (password_manager) {
692 password_manager->AddSubmissionCallback(
693 base::Bind(&OneClickSigninHelper::PasswordSubmitted,
694 weak_pointer_factory_.GetWeakPtr()));
698 OneClickSigninHelper::~OneClickSigninHelper() {}
701 void OneClickSigninHelper::LogHistogramValue(
702 signin::Source source, int action) {
704 case signin::SOURCE_START_PAGE:
705 UMA_HISTOGRAM_ENUMERATION("Signin.StartPageActions", action,
706 one_click_signin::HISTOGRAM_MAX);
708 case signin::SOURCE_NTP_LINK:
709 UMA_HISTOGRAM_ENUMERATION("Signin.NTPLinkActions", action,
710 one_click_signin::HISTOGRAM_MAX);
712 case signin::SOURCE_MENU:
713 UMA_HISTOGRAM_ENUMERATION("Signin.MenuActions", action,
714 one_click_signin::HISTOGRAM_MAX);
716 case signin::SOURCE_SETTINGS:
717 UMA_HISTOGRAM_ENUMERATION("Signin.SettingsActions", action,
718 one_click_signin::HISTOGRAM_MAX);
720 case signin::SOURCE_EXTENSION_INSTALL_BUBBLE:
721 UMA_HISTOGRAM_ENUMERATION("Signin.ExtensionInstallBubbleActions", action,
722 one_click_signin::HISTOGRAM_MAX);
724 case signin::SOURCE_WEBSTORE_INSTALL:
725 UMA_HISTOGRAM_ENUMERATION("Signin.WebstoreInstallActions", action,
726 one_click_signin::HISTOGRAM_MAX);
728 case signin::SOURCE_APP_LAUNCHER:
729 UMA_HISTOGRAM_ENUMERATION("Signin.AppLauncherActions", action,
730 one_click_signin::HISTOGRAM_MAX);
732 case signin::SOURCE_APPS_PAGE_LINK:
733 UMA_HISTOGRAM_ENUMERATION("Signin.AppsPageLinkActions", action,
734 one_click_signin::HISTOGRAM_MAX);
736 case signin::SOURCE_BOOKMARK_BUBBLE:
737 UMA_HISTOGRAM_ENUMERATION("Signin.BookmarkBubbleActions", action,
738 one_click_signin::HISTOGRAM_MAX);
740 case signin::SOURCE_AVATAR_BUBBLE_SIGN_IN:
741 UMA_HISTOGRAM_ENUMERATION("Signin.AvatarBubbleActions", action,
742 one_click_signin::HISTOGRAM_MAX);
744 case signin::SOURCE_AVATAR_BUBBLE_ADD_ACCOUNT:
745 UMA_HISTOGRAM_ENUMERATION("Signin.AvatarBubbleActions", action,
746 one_click_signin::HISTOGRAM_MAX);
748 case signin::SOURCE_DEVICES_PAGE:
749 UMA_HISTOGRAM_ENUMERATION("Signin.DevicesPageActions", action,
750 one_click_signin::HISTOGRAM_MAX);
753 // This switch statement needs to be updated when the enum Source changes.
754 COMPILE_ASSERT(signin::SOURCE_UNKNOWN == 12,
755 kSourceEnumHasChangedButNotThisSwitchStatement);
759 UMA_HISTOGRAM_ENUMERATION("Signin.AllAccessPointActions", action,
760 one_click_signin::HISTOGRAM_MAX);
764 void OneClickSigninHelper::CreateForWebContentsWithPasswordManager(
765 content::WebContents* contents,
766 password_manager::PasswordManager* password_manager) {
767 if (!FromWebContents(contents)) {
768 contents->SetUserData(UserDataKey(),
769 new OneClickSigninHelper(contents, password_manager));
774 bool OneClickSigninHelper::CanOffer(content::WebContents* web_contents,
775 CanOfferFor can_offer_for,
776 const std::string& email,
777 std::string* error_message) {
778 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
779 VLOG(1) << "OneClickSigninHelper::CanOffer";
782 error_message->clear();
787 if (web_contents->GetBrowserContext()->IsOffTheRecord())
791 Profile::FromBrowserContext(web_contents->GetBrowserContext());
795 SigninManager* manager =
796 SigninManagerFactory::GetForProfile(profile);
797 if (manager && !manager->IsSigninAllowed())
800 if (can_offer_for == CAN_OFFER_FOR_INTERSTITAL_ONLY &&
801 !profile->GetPrefs()->GetBoolean(prefs::kReverseAutologinEnabled))
804 if (!ChromeSigninClient::ProfileAllowsSigninCookies(profile))
807 if (!email.empty()) {
811 // Make sure this username is not prohibited by policy.
812 if (!manager->IsAllowedUsername(email)) {
814 error_message->assign(
815 l10n_util::GetStringUTF8(IDS_SYNC_LOGIN_NAME_PROHIBITED));
820 if (can_offer_for != CAN_OFFER_FOR_SECONDARY_ACCOUNT) {
821 // If the signin manager already has an authenticated name, then this is a
822 // re-auth scenario. Make sure the email just signed in corresponds to
823 // the one sign in manager expects.
824 std::string current_email = manager->GetAuthenticatedUsername();
825 const bool same_email = gaia::AreEmailsSame(current_email, email);
826 if (!current_email.empty() && !same_email) {
827 UMA_HISTOGRAM_ENUMERATION("Signin.Reauth",
828 signin::HISTOGRAM_ACCOUNT_MISSMATCH,
829 signin::HISTOGRAM_MAX);
831 error_message->assign(
832 l10n_util::GetStringFUTF8(IDS_SYNC_WRONG_EMAIL,
833 base::UTF8ToUTF16(current_email)));
838 // If some profile, not just the current one, is already connected to this
839 // account, don't show the infobar.
840 if (g_browser_process && !same_email) {
841 ProfileManager* manager = g_browser_process->profile_manager();
843 ProfileInfoCache& cache = manager->GetProfileInfoCache();
844 for (size_t i = 0; i < cache.GetNumberOfProfiles(); ++i) {
845 std::string current_email =
846 base::UTF16ToUTF8(cache.GetUserNameOfProfileAtIndex(i));
847 if (gaia::AreEmailsSame(email, current_email)) {
849 error_message->assign(
850 l10n_util::GetStringUTF8(IDS_SYNC_USER_NAME_IN_USE_ERROR));
859 // If email was already rejected by this profile for one-click sign-in.
860 if (can_offer_for == CAN_OFFER_FOR_INTERSTITAL_ONLY) {
861 const base::ListValue* rejected_emails = profile->GetPrefs()->GetList(
862 prefs::kReverseAutologinRejectedEmailList);
863 if (!rejected_emails->empty()) {
864 base::ListValue::const_iterator iter = rejected_emails->Find(
865 base::StringValue(email));
866 if (iter != rejected_emails->end())
872 VLOG(1) << "OneClickSigninHelper::CanOffer: yes we can";
877 OneClickSigninHelper::Offer OneClickSigninHelper::CanOfferOnIOThread(
878 net::URLRequest* request,
879 ProfileIOData* io_data) {
880 return CanOfferOnIOThreadImpl(request->url(), request, io_data);
884 OneClickSigninHelper::Offer OneClickSigninHelper::CanOfferOnIOThreadImpl(
886 base::SupportsUserData* request,
887 ProfileIOData* io_data) {
888 if (!gaia::IsGaiaSignonRealm(url.GetOrigin()))
889 return IGNORE_REQUEST;
894 // Check for incognito before other parts of the io_data, since those
895 // members may not be initalized.
896 if (io_data->IsOffTheRecord())
899 if (!io_data->signin_allowed()->GetValue())
902 if (!io_data->reverse_autologin_enabled()->GetValue())
905 if (!io_data->google_services_username()->GetValue().empty())
908 if (!ChromeSigninClient::SettingsAllowSigninCookies(
909 io_data->GetCookieSettings()))
912 // The checks below depend on chrome already knowing what account the user
913 // signed in with. This happens only after receiving the response containing
914 // the Google-Accounts-SignIn header. Until then, if there is even a chance
915 // that we want to connect the profile, chrome needs to tell Gaia that
916 // it should offer the interstitial. Therefore missing one click data on
917 // the request means can offer is true.
918 const std::string& pending_email = io_data->reverse_autologin_pending_email();
919 if (!pending_email.empty()) {
920 if (!SigninManager::IsUsernameAllowedByPolicy(pending_email,
921 io_data->google_services_username_pattern()->GetValue())) {
925 std::vector<std::string> rejected_emails =
926 io_data->one_click_signin_rejected_email_list()->GetValue();
927 if (std::count_if(rejected_emails.begin(), rejected_emails.end(),
928 std::bind2nd(std::equal_to<std::string>(),
929 pending_email)) > 0) {
933 if (io_data->signin_names()->GetEmails().count(
934 base::UTF8ToUTF16(pending_email)) > 0) {
943 void OneClickSigninHelper::ShowInfoBarIfPossible(net::URLRequest* request,
944 ProfileIOData* io_data,
947 std::string google_chrome_signin_value;
948 std::string google_accounts_signin_value;
949 request->GetResponseHeaderByName("Google-Chrome-SignIn",
950 &google_chrome_signin_value);
951 request->GetResponseHeaderByName("Google-Accounts-SignIn",
952 &google_accounts_signin_value);
954 if (!google_accounts_signin_value.empty() ||
955 !google_chrome_signin_value.empty()) {
956 VLOG(1) << "OneClickSigninHelper::ShowInfoBarIfPossible:"
957 << " g-a-s='" << google_accounts_signin_value << "'"
958 << " g-c-s='" << google_chrome_signin_value << "'";
961 if (!gaia::IsGaiaSignonRealm(request->url().GetOrigin()))
964 // Parse Google-Accounts-SignIn.
965 std::vector<std::pair<std::string, std::string> > pairs;
966 base::SplitStringIntoKeyValuePairs(google_accounts_signin_value, '=', ',',
968 std::string session_index;
970 for (size_t i = 0; i < pairs.size(); ++i) {
971 const std::pair<std::string, std::string>& pair = pairs[i];
972 const std::string& key = pair.first;
973 const std::string& value = pair.second;
974 if (key == "email") {
975 base::TrimString(value, "\"", &email);
976 } else if (key == "sessionindex") {
977 session_index = value;
981 // Later in the chain of this request, we'll need to check the email address
982 // in the IO thread (see CanOfferOnIOThread). So save the email address as
983 // user data on the request (only for web-based flow).
985 io_data->set_reverse_autologin_pending_email(email);
987 if (!email.empty() || !session_index.empty()) {
988 VLOG(1) << "OneClickSigninHelper::ShowInfoBarIfPossible:"
989 << " email=" << email
990 << " sessionindex=" << session_index;
993 // Parse Google-Chrome-SignIn.
994 AutoAccept auto_accept = AUTO_ACCEPT_NONE;
995 signin::Source source = signin::SOURCE_UNKNOWN;
997 std::vector<std::string> tokens;
998 base::SplitString(google_chrome_signin_value, ',', &tokens);
999 for (size_t i = 0; i < tokens.size(); ++i) {
1000 const std::string& token = tokens[i];
1001 if (token == "accepted") {
1002 auto_accept = AUTO_ACCEPT_ACCEPTED;
1003 } else if (token == "configure") {
1004 auto_accept = AUTO_ACCEPT_CONFIGURE;
1005 } else if (token == "rejected-for-profile") {
1006 auto_accept = AUTO_ACCEPT_REJECTED_FOR_PROFILE;
1010 // If this is an explicit sign in (i.e., first run, NTP, Apps page, menu,
1011 // settings) then force the auto accept type to explicit.
1012 source = GetSigninSource(request->url(), &continue_url);
1013 if (source != signin::SOURCE_UNKNOWN)
1014 auto_accept = AUTO_ACCEPT_EXPLICIT;
1016 if (auto_accept != AUTO_ACCEPT_NONE) {
1017 VLOG(1) << "OneClickSigninHelper::ShowInfoBarIfPossible:"
1018 << " auto_accept=" << auto_accept;
1021 // If |session_index|, |email|, |auto_accept|, and |continue_url| all have
1022 // their default value, don't bother posting a task to the UI thread.
1023 // It will be a noop anyway.
1025 // The two headers above may (but not always) come in different http requests
1026 // so a post to the UI thread is still needed if |auto_accept| is not its
1027 // default value, but |email| and |session_index| are.
1028 if (session_index.empty() && email.empty() &&
1029 auto_accept == AUTO_ACCEPT_NONE && !continue_url.is_valid()) {
1033 content::BrowserThread::PostTask(
1034 content::BrowserThread::UI, FROM_HERE,
1035 base::Bind(&OneClickSigninHelper::ShowInfoBarUIThread, session_index,
1036 email, auto_accept, source, continue_url, child_id, route_id));
1040 void OneClickSigninHelper::LogConfirmHistogramValue(int action) {
1041 UMA_HISTOGRAM_ENUMERATION("Signin.OneClickConfirmation", action,
1042 one_click_signin::HISTOGRAM_CONFIRM_MAX);
1045 void OneClickSigninHelper::ShowInfoBarUIThread(
1046 const std::string& session_index,
1047 const std::string& email,
1048 AutoAccept auto_accept,
1049 signin::Source source,
1050 const GURL& continue_url,
1053 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
1055 content::WebContents* web_contents = tab_util::GetWebContentsByID(child_id,
1060 // TODO(mathp): The appearance of this infobar should be tested using a
1062 OneClickSigninHelper* helper =
1063 OneClickSigninHelper::FromWebContents(web_contents);
1067 if (auto_accept != AUTO_ACCEPT_NONE)
1068 helper->auto_accept_ = auto_accept;
1070 if (source != signin::SOURCE_UNKNOWN &&
1071 helper->source_ == signin::SOURCE_UNKNOWN) {
1072 helper->source_ = source;
1075 // Save the email in the one-click signin manager. The manager may
1076 // not exist if the contents is incognito or if the profile is already
1077 // connected to a Google account.
1078 if (!session_index.empty())
1079 helper->session_index_ = session_index;
1082 helper->email_ = email;
1084 CanOfferFor can_offer_for =
1085 (auto_accept != AUTO_ACCEPT_EXPLICIT &&
1086 helper->auto_accept_ != AUTO_ACCEPT_EXPLICIT) ?
1087 CAN_OFFER_FOR_INTERSTITAL_ONLY : CAN_OFFER_FOR_ALL;
1089 std::string error_message;
1091 if (!web_contents || !CanOffer(web_contents, can_offer_for, email,
1093 VLOG(1) << "OneClickSigninHelper::ShowInfoBarUIThread: not offering";
1094 // TODO(rogerta): Can we just display our error now instead of keeping it
1095 // around and doing it later?
1096 if (helper && helper->error_message_.empty() && !error_message.empty())
1097 helper->error_message_ = error_message;
1102 // Only allow the dedicated signin process to sign the user into
1103 // Chrome without intervention, because it doesn't load any untrusted
1104 // pages. If at any point an untrusted page is detected, chrome will
1105 // show a modal dialog asking the user to confirm.
1107 Profile::FromBrowserContext(web_contents->GetBrowserContext());
1108 ChromeSigninClient* signin_client =
1109 profile ? ChromeSigninClientFactory::GetForProfile(profile) : NULL;
1110 helper->untrusted_confirmation_required_ |=
1111 (signin_client && !signin_client->IsSigninProcess(child_id));
1113 if (continue_url.is_valid()) {
1114 // Set |original_continue_url_| if it is currently empty. |continue_url|
1115 // could be modified by gaia pages, thus we need to record the original
1116 // continue url to navigate back to the right page when sync setup is
1118 if (helper->original_continue_url_.is_empty())
1119 helper->original_continue_url_ = continue_url;
1120 helper->continue_url_ = continue_url;
1125 void OneClickSigninHelper::RemoveSigninRedirectURLHistoryItem(
1126 content::WebContents* web_contents) {
1127 // Only actually remove the item if it's the blank.html continue url.
1128 if (signin::IsContinueUrlForWebBasedSigninFlow(
1129 web_contents->GetLastCommittedURL())) {
1130 new CurrentHistoryCleaner(web_contents); // will self-destruct when done
1135 void OneClickSigninHelper::ShowSigninErrorBubble(Browser* browser,
1136 const std::string& error) {
1137 DCHECK(!error.empty());
1139 browser->window()->ShowOneClickSigninBubble(
1140 BrowserWindow::ONE_CLICK_SIGNIN_BUBBLE_TYPE_BUBBLE,
1141 base::string16(), /* no SAML email */
1142 base::UTF8ToUTF16(error),
1143 // This callback is never invoked.
1144 // TODO(rogerta): Separate out the bubble API so we don't have to pass
1145 // ignored |email| and |callback| params.
1146 BrowserWindow::StartSyncCallback());
1150 bool OneClickSigninHelper::HandleCrossAccountError(
1151 content::WebContents* contents,
1152 const std::string& session_index,
1153 const std::string& email,
1154 const std::string& password,
1155 const std::string& refresh_token,
1156 OneClickSigninHelper::AutoAccept auto_accept,
1157 signin::Source source,
1158 OneClickSigninSyncStarter::StartSyncMode start_mode,
1159 OneClickSigninSyncStarter::Callback sync_callback) {
1161 Profile::FromBrowserContext(contents->GetBrowserContext());
1162 std::string last_email =
1163 profile->GetPrefs()->GetString(prefs::kGoogleServicesLastUsername);
1165 if (!last_email.empty() && !gaia::AreEmailsSame(last_email, email)) {
1166 // If the new email address is different from the email address that
1167 // just signed in, show a confirmation dialog.
1169 // No need to display a second confirmation so pass false below.
1170 // TODO(atwilson): Move this into OneClickSigninSyncStarter.
1171 // The tab modal dialog always executes its callback before |contents|
1173 Browser* browser = chrome::FindBrowserWithWebContents(contents);
1174 ConfirmEmailDialogDelegate::AskForConfirmation(
1180 StartSyncArgs(profile, browser, auto_accept,
1181 session_index, email, password, refresh_token,
1182 contents, false /* confirmation_required */, source,
1193 void OneClickSigninHelper::RedirectToNtpOrAppsPage(
1194 content::WebContents* contents, signin::Source source) {
1195 // Do nothing if a navigation is pending, since this call can be triggered
1196 // from DidStartLoading. This avoids deleting the pending entry while we are
1197 // still navigating to it. See crbug/346632.
1198 if (contents->GetController().GetPendingEntry())
1201 VLOG(1) << "RedirectToNtpOrAppsPage";
1202 // Redirect to NTP/Apps page and display a confirmation bubble
1203 GURL url(source == signin::SOURCE_APPS_PAGE_LINK ?
1204 chrome::kChromeUIAppsURL : chrome::kChromeUINewTabURL);
1205 content::OpenURLParams params(url,
1206 content::Referrer(),
1208 content::PAGE_TRANSITION_AUTO_TOPLEVEL,
1210 contents->OpenURL(params);
1214 void OneClickSigninHelper::RedirectToNtpOrAppsPageIfNecessary(
1215 content::WebContents* contents, signin::Source source) {
1216 if (source != signin::SOURCE_SETTINGS &&
1217 source != signin::SOURCE_WEBSTORE_INSTALL) {
1218 RedirectToNtpOrAppsPage(contents, source);
1222 void OneClickSigninHelper::RedirectToSignin() {
1223 VLOG(1) << "OneClickSigninHelper::RedirectToSignin";
1225 // Extract the existing sounce=X value. Default to "2" if missing.
1226 signin::Source source = signin::GetSourceForPromoURL(continue_url_);
1227 if (source == signin::SOURCE_UNKNOWN)
1228 source = signin::SOURCE_MENU;
1229 GURL page = signin::GetPromoURL(source, false);
1231 content::WebContents* contents = web_contents();
1232 contents->GetController().LoadURL(page,
1233 content::Referrer(),
1234 content::PAGE_TRANSITION_AUTO_TOPLEVEL,
1238 void OneClickSigninHelper::CleanTransientState() {
1239 VLOG(1) << "OneClickSigninHelper::CleanTransientState";
1240 showing_signin_ = false;
1243 auto_accept_ = AUTO_ACCEPT_NONE;
1244 source_ = signin::SOURCE_UNKNOWN;
1245 switched_to_advanced_ = false;
1246 continue_url_ = GURL();
1247 untrusted_navigations_since_signin_visit_ = 0;
1248 untrusted_confirmation_required_ = false;
1249 error_message_.clear();
1251 // Post to IO thread to clear pending email.
1252 if (!do_not_clear_pending_email_) {
1254 Profile::FromBrowserContext(web_contents()->GetBrowserContext());
1255 content::BrowserThread::PostTask(
1256 content::BrowserThread::IO, FROM_HERE,
1257 base::Bind(&ClearPendingEmailOnIOThread,
1258 base::Unretained(profile->GetResourceContext())));
1262 void OneClickSigninHelper::PasswordSubmitted(
1263 const autofill::PasswordForm& form) {
1264 // We only need to scrape the password for Gaia logins.
1265 if (gaia::IsGaiaSignonRealm(GURL(form.signon_realm))) {
1266 VLOG(1) << "OneClickSigninHelper::DidNavigateAnyFrame: got password";
1267 password_ = base::UTF16ToUTF8(form.password_value);
1271 void OneClickSigninHelper::SetDoNotClearPendingEmailForTesting() {
1272 do_not_clear_pending_email_ = true;
1275 void OneClickSigninHelper::set_do_not_start_sync_for_testing() {
1276 do_not_start_sync_for_testing_ = true;
1279 void OneClickSigninHelper::DidStartNavigationToPendingEntry(
1281 content::NavigationController::ReloadType reload_type) {
1282 VLOG(1) << "OneClickSigninHelper::DidStartNavigationToPendingEntry: url=" <<
1284 // If the tab navigates to a new page, and this page is not a valid Gaia
1285 // sign in redirect or reponse, or the expected continue URL, make sure to
1286 // clear the internal state. This is needed to detect navigations in the
1287 // middle of the sign in process that may redirect back to the sign in
1288 // process (see crbug.com/181163 for details).
1289 GURL::Replacements replacements;
1290 replacements.ClearQuery();
1292 if (!IsValidGaiaSigninRedirectOrResponseURL(url) &&
1293 continue_url_.is_valid() &&
1294 url.ReplaceComponents(replacements) !=
1295 continue_url_.ReplaceComponents(replacements)) {
1296 if (++untrusted_navigations_since_signin_visit_ > kMaxNavigationsSince)
1297 CleanTransientState();
1301 void OneClickSigninHelper::DidNavigateMainFrame(
1302 const content::LoadCommittedDetails& details,
1303 const content::FrameNavigateParams& params) {
1304 if (!SigninManager::IsWebBasedSigninFlowURL(params.url)) {
1305 // Make sure the renderer process is no longer considered the trusted
1306 // sign-in process when a navigation to a non-sign-in URL occurs.
1308 Profile::FromBrowserContext(web_contents()->GetBrowserContext());
1309 ChromeSigninClient* signin_client =
1310 profile ? ChromeSigninClientFactory::GetForProfile(profile) : NULL;
1311 int process_id = web_contents()->GetRenderProcessHost()->GetID();
1312 if (signin_client && signin_client->IsSigninProcess(process_id))
1313 signin_client->ClearSigninProcess();
1315 // If the navigation to a non-sign-in URL hasn't been triggered by the web
1316 // contents, the sign in flow has been aborted and the state must be
1317 // cleaned (crbug.com/269421).
1318 if (!content::PageTransitionIsWebTriggerable(params.transition) &&
1319 auto_accept_ != AUTO_ACCEPT_NONE) {
1320 CleanTransientState();
1325 void OneClickSigninHelper::DidStopLoading(
1326 content::RenderViewHost* render_view_host) {
1327 // If the user left the sign in process, clear all members.
1328 // TODO(rogerta): might need to allow some youtube URLs.
1329 content::WebContents* contents = web_contents();
1330 const GURL url = contents->GetLastCommittedURL();
1332 Profile::FromBrowserContext(contents->GetBrowserContext());
1333 VLOG(1) << "OneClickSigninHelper::DidStopLoading: url=" << url.spec();
1335 if (url.scheme() == content::kChromeUIScheme) {
1336 // Suppresses OneClickSigninHelper on webUI pages to avoid inteference with
1337 // inline signin flows.
1338 VLOG(1) << "OneClickSigninHelper::DidStopLoading: suppressed for url="
1340 CleanTransientState();
1344 // If an error has already occured during the sign in flow, make sure to
1345 // display it to the user and abort the process. Do this only for
1346 // explicit sign ins.
1347 // TODO(rogerta): Could we move this code back up to ShowInfoBarUIThread()?
1348 if (!error_message_.empty() && auto_accept_ == AUTO_ACCEPT_EXPLICIT) {
1349 VLOG(1) << "OneClickSigninHelper::DidStopLoading: error=" << error_message_;
1350 RemoveSigninRedirectURLHistoryItem(contents);
1351 // After we redirect to NTP, our browser pointer gets corrupted because the
1352 // WebContents have changed, so grab the browser pointer
1353 // before the navigation.
1354 Browser* browser = chrome::FindBrowserWithWebContents(contents);
1356 // Redirect to the landing page and display an error popup.
1357 RedirectToNtpOrAppsPage(web_contents(), source_);
1358 ShowSigninErrorBubble(browser, 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(contents, 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_));