summaryrefslogtreecommitdiffstats
path: root/chromium/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc
blob: 2b8e201ce88550c5d2136bec986c654a0f7aeb13 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/webui/signin/inline_login_handler_impl.h"

#include <stddef.h>

#include <string>
#include <utility>
#include <vector>

#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/user_metrics.h"
#include "base/metrics/user_metrics_action.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/password_manager/password_store_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_attributes_entry.h"
#include "chrome/browser/profiles/profile_attributes_storage.h"
#include "chrome/browser/profiles/profile_window.h"
#include "chrome/browser/signin/about_signin_internals_factory.h"
#include "chrome/browser/signin/account_consistency_mode_manager.h"
#include "chrome/browser/signin/chrome_device_id_helper.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/signin/local_auth.h"
#include "chrome/browser/signin/signin_promo.h"
#include "chrome/browser/signin/signin_util.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/chrome_pages.h"
#include "chrome/browser/ui/tab_modal_confirm_dialog.h"
#include "chrome/browser/ui/tab_modal_confirm_dialog_delegate.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/user_manager.h"
#include "chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.h"
#include "chrome/browser/ui/webui/signin/dice_turn_sync_on_helper_delegate_impl.h"
#include "chrome/browser/ui/webui/signin/login_ui_service.h"
#include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
#include "chrome/browser/ui/webui/signin/signin_utils.h"
#include "chrome/browser/ui/webui/signin/signin_utils_desktop.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/chromium_strings.h"
#include "components/password_manager/core/browser/password_manager_metrics_util.h"
#include "components/password_manager/core/browser/password_store.h"
#include "components/prefs/pref_service.h"
#include "components/signin/core/browser/about_signin_internals.h"
#include "components/signin/public/base/signin_metrics.h"
#include "components/signin/public/base/signin_pref_names.h"
#include "components/signin/public/identity_manager/accounts_cookie_mutator.h"
#include "components/signin/public/identity_manager/accounts_mutator.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/signin/public/identity_manager/primary_account_mutator.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_ui.h"
#include "google_apis/gaia/gaia_auth_fetcher.h"
#include "google_apis/gaia/gaia_auth_util.h"
#include "google_apis/gaia/gaia_urls.h"
#include "net/base/url_util.h"
#include "ui/base/l10n/l10n_util.h"

#if defined(OS_WIN)
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "chrome/credential_provider/common/gcp_strings.h"
#endif  // defined(OS_WIN)

namespace {

// Subset of signin_metrics::Reason that is supported by the
// InlineLoginHandlerImpl.
enum class HandlerSigninReason {
  FORCED_SIGNIN_PRIMARY_ACCOUNT,
  UNLOCK,
  FETCH_LST_ONLY
};

// Decodes the signin reason from the URL parameter.
HandlerSigninReason GetHandlerSigninReason(const GURL& url) {
  signin_metrics::Reason reason =
      signin::GetSigninReasonForEmbeddedPromoURL(url);
  switch (reason) {
    case signin_metrics::Reason::REASON_FORCED_SIGNIN_PRIMARY_ACCOUNT:
      return HandlerSigninReason::FORCED_SIGNIN_PRIMARY_ACCOUNT;
    case signin_metrics::Reason::REASON_UNLOCK:
      return HandlerSigninReason::UNLOCK;
    case signin_metrics::Reason::REASON_FETCH_LST_ONLY:
      return HandlerSigninReason::FETCH_LST_ONLY;
    default:
      NOTREACHED() << "Unexpected signin reason: " << static_cast<int>(reason);
      return HandlerSigninReason::FORCED_SIGNIN_PRIMARY_ACCOUNT;
  }
}

// Converts from HandlerSigninReason to signin_metrics::Reason.
signin_metrics::Reason GetSigninReasonFromHandlerSigninReason(
    HandlerSigninReason r) {
  switch (r) {
    case HandlerSigninReason::FORCED_SIGNIN_PRIMARY_ACCOUNT:
      return signin_metrics::Reason::REASON_FORCED_SIGNIN_PRIMARY_ACCOUNT;
    case HandlerSigninReason::UNLOCK:
      return signin_metrics::Reason::REASON_UNLOCK;
    case HandlerSigninReason::FETCH_LST_ONLY:
      return signin_metrics::Reason::REASON_FETCH_LST_ONLY;
  }
}

// Specific implementation of DiceTurnSyncOnHelper::Delegate for forced
// signin flows. Some confirmation prompts are skipped.
class ForcedSigninDiceTurnSyncOnHelperDelegate
    : public DiceTurnSyncOnHelperDelegateImpl {
 public:
  explicit ForcedSigninDiceTurnSyncOnHelperDelegate(Browser* browser)
      : DiceTurnSyncOnHelperDelegateImpl(browser) {}

 private:
  void ShowMergeSyncDataConfirmation(
      const std::string& previous_email,
      const std::string& new_email,
      DiceTurnSyncOnHelper::SigninChoiceCallback callback) override {
    NOTREACHED();
  }

  void ShowEnterpriseAccountConfirmation(
      const std::string& email,
      DiceTurnSyncOnHelper::SigninChoiceCallback callback) override {
    std::move(callback).Run(
        DiceTurnSyncOnHelper ::SigninChoice::SIGNIN_CHOICE_CONTINUE);
  }
};

#if defined(OS_WIN)

// Returns a list of valid signin domains that were passed in
// |email_domains_parameter| as an argument to the gcpw signin dialog.

std::vector<std::string> GetEmailDomainsFromParameter(
    const std::string& email_domains_parameter) {
  return base::SplitString(base::ToLowerASCII(email_domains_parameter),
                           credential_provider::kEmailDomainsSeparator,
                           base::WhitespaceHandling::TRIM_WHITESPACE,
                           base::SplitResult::SPLIT_WANT_NONEMPTY);
}

// Validates that the |signin_gaia_id| that the user signed in with matches
// the |gaia_id_parameter| passed to the gcpw signin dialog. Also ensures
// that the |signin_email| is in a domain listed in |email_domains_parameter|.
// Returns kUiecSuccess on success.
// Returns the appropriate error code on failure.
credential_provider::UiExitCodes ValidateSigninEmail(
    const std::string& gaia_id_parameter,
    const std::string& email_domains_parameter,
    const std::string& signin_email,
    const std::string& signin_gaia_id) {
  if (!gaia_id_parameter.empty() &&
      !base::LowerCaseEqualsASCII(gaia_id_parameter, signin_gaia_id)) {
    return credential_provider::kUiecEMailMissmatch;
  }

  if (email_domains_parameter.empty())
    return credential_provider::kUiecSuccess;

  std::vector<std::string> all_email_domains =
      GetEmailDomainsFromParameter(email_domains_parameter);
  std::string email_domain = gaia::ExtractDomainName(signin_email);

  return std::find(all_email_domains.begin(), all_email_domains.end(),
                   email_domain) != all_email_domains.end()
             ? credential_provider::kUiecSuccess
             : credential_provider::kUiecInvalidEmailDomain;
}

#endif

void LogHistogramValue(signin_metrics::AccessPointAction action) {
  UMA_HISTOGRAM_ENUMERATION("Signin.AllAccessPointActions", action,
                            signin_metrics::HISTOGRAM_MAX);
}

// Returns true if |profile| is a system profile or created from one.
bool IsSystemProfile(Profile* profile) {
  return profile->GetOriginalProfile()->IsSystemProfile();
}

void RedirectToNtpOrAppsPage(content::WebContents* contents,
                             signin_metrics::AccessPoint access_point) {
  // Do nothing if a navigation is pending, since this call can be triggered
  // from DidStartLoading. This avoids deleting the pending entry while we are
  // still navigating to it. See crbug/346632.
  if (contents->GetController().GetPendingEntry())
    return;

  VLOG(1) << "RedirectToNtpOrAppsPage";
  // Redirect to NTP/Apps page and display a confirmation bubble
  GURL url(access_point ==
                   signin_metrics::AccessPoint::ACCESS_POINT_APPS_PAGE_LINK
               ? chrome::kChromeUIAppsURL
               : chrome::kChromeUINewTabURL);
  content::OpenURLParams params(url, content::Referrer(),
                                WindowOpenDisposition::CURRENT_TAB,
                                ui::PAGE_TRANSITION_AUTO_TOPLEVEL, false);
  contents->OpenURL(params);
}

void SetProfileLocked(const base::FilePath profile_path, bool locked) {
  if (!profile_path.empty()) {
    ProfileManager* profile_manager = g_browser_process->profile_manager();
    if (profile_manager) {
      ProfileAttributesEntry* entry;
      if (profile_manager->GetProfileAttributesStorage()
              .GetProfileAttributesWithPath(profile_path, &entry)) {
        if (locked)
          entry->LockForceSigninProfile(true);
        else
          entry->SetIsSigninRequired(false);
      }
    }
  }
}

void UnlockProfileAndHideLoginUI(const base::FilePath profile_path,
                                 InlineLoginHandlerImpl* handler) {
  SetProfileLocked(profile_path, false);
  handler->CloseDialogFromJavascript();
  UserManager::Hide();
}

void LockProfileAndShowUserManager(const base::FilePath& profile_path) {
  SetProfileLocked(profile_path, true);
  UserManager::Show(profile_path,
                    profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION);
}

// Callback for DiceTurnOnSyncHelper.
void OnSyncSetupComplete(Profile* profile,
                         const std::string& username,
                         const std::string& password) {
  DCHECK(signin_util::IsForceSigninEnabled());
  signin::IdentityManager* identity_manager =
      IdentityManagerFactory::GetForProfile(profile);
  bool has_primary_account = identity_manager->HasPrimaryAccount();
  if (has_primary_account && !password.empty()) {
    scoped_refptr<password_manager::PasswordStore> password_store =
        PasswordStoreFactory::GetForProfile(profile,
                                            ServiceAccessType::EXPLICIT_ACCESS);
    password_store->SaveGaiaPasswordHash(
        username, base::UTF8ToUTF16(password),
        password_manager::metrics_util::GaiaPasswordHashChange::
            SAVED_ON_CHROME_SIGNIN);

    if (profiles::IsLockAvailable(profile))
      LocalAuth::SetLocalAuthCredentials(profile, password);
  }

  if (!has_primary_account) {
    BrowserList::CloseAllBrowsersWithProfile(
        profile, base::Bind(&LockProfileAndShowUserManager),
        // Cannot be called because skip_beforeunload is true.
        BrowserList::CloseCallback(),
        /*skip_beforeunload=*/true);
  }
}

}  // namespace

InlineSigninHelper::InlineSigninHelper(
    base::WeakPtr<InlineLoginHandlerImpl> handler,
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
    Profile* profile,
    Profile::CreateStatus create_status,
    const GURL& current_url,
    const std::string& email,
    const std::string& gaia_id,
    const std::string& password,
    const std::string& auth_code,
    const std::string& signin_scoped_device_id,
    bool confirm_untrusted_signin,
    bool is_force_sign_in_with_usermanager)
    : gaia_auth_fetcher_(this, gaia::GaiaSource::kChrome, url_loader_factory),
      handler_(handler),
      profile_(profile),
      create_status_(create_status),
      current_url_(current_url),
      email_(email),
      gaia_id_(gaia_id),
      password_(password),
      auth_code_(auth_code),
      confirm_untrusted_signin_(confirm_untrusted_signin),
      is_force_sign_in_with_usermanager_(is_force_sign_in_with_usermanager) {
  DCHECK(profile_);
  DCHECK(!email_.empty());
  DCHECK(!auth_code_.empty());
  DCHECK(handler);

  gaia_auth_fetcher_.StartAuthCodeForOAuth2TokenExchangeWithDeviceId(
      auth_code_, signin_scoped_device_id);
}

InlineSigninHelper::~InlineSigninHelper() {}

void InlineSigninHelper::OnClientOAuthSuccess(const ClientOAuthResult& result) {
  if (is_force_sign_in_with_usermanager_) {
    // If user sign in in UserManager with force sign in enabled, the browser
    // window won't be opened until now.
    UnlockProfileAndHideLoginUI(profile_->GetPath(), handler_.get());
    profiles::OpenBrowserWindowForProfile(
        base::Bind(&InlineSigninHelper::OnClientOAuthSuccessAndBrowserOpened,
                   base::Unretained(this), result),
        true, false, true, profile_, create_status_);
  } else {
    OnClientOAuthSuccessAndBrowserOpened(result, profile_, create_status_);
  }
}

void InlineSigninHelper::OnClientOAuthSuccessAndBrowserOpened(
    const ClientOAuthResult& result,
    Profile* /*profile*/,
    Profile::CreateStatus /*status*/) {
  HandlerSigninReason reason = GetHandlerSigninReason(current_url_);
  if (reason == HandlerSigninReason::FETCH_LST_ONLY) {
    // Constants are only available on Windows for the Google Credential
    // Provider for Windows.
#if defined(OS_WIN)
    std::string json_retval;
    base::Value args(base::Value::Type::DICTIONARY);
    args.SetKey(credential_provider::kKeyEmail, base::Value(email_));
    args.SetKey(credential_provider::kKeyPassword, base::Value(password_));
    args.SetKey(credential_provider::kKeyId, base::Value(gaia_id_));
    args.SetKey(credential_provider::kKeyRefreshToken,
                base::Value(result.refresh_token));
    args.SetKey(credential_provider::kKeyAccessToken,
                base::Value(result.access_token));

    handler_->SendLSTFetchResultsMessage(args);
#else
    NOTREACHED() << "Google Credential Provider is only available on Windows";
#endif  // defined(OS_WIN)
    base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this);
    return;
  }

  AboutSigninInternals* about_signin_internals =
      AboutSigninInternalsFactory::GetForProfile(profile_);
  about_signin_internals->OnRefreshTokenReceived("Successful");

  signin::IdentityManager* identity_manager =
      IdentityManagerFactory::GetForProfile(profile_);

  std::string primary_email = identity_manager->GetPrimaryAccountInfo().email;
  if (gaia::AreEmailsSame(email_, primary_email) &&
      reason == HandlerSigninReason::UNLOCK && !password_.empty() &&
      profiles::IsLockAvailable(profile_)) {
    LocalAuth::SetLocalAuthCredentials(profile_, password_);
  }

#if defined(SYNC_PASSWORD_REUSE_DETECTION_ENABLED)
  if (!password_.empty()) {
    scoped_refptr<password_manager::PasswordStore> password_store =
        PasswordStoreFactory::GetForProfile(profile_,
                                            ServiceAccessType::EXPLICIT_ACCESS);
    if (password_store && !primary_email.empty()) {
      password_store->SaveGaiaPasswordHash(
          primary_email, base::UTF8ToUTF16(password_),
          password_manager::metrics_util::GaiaPasswordHashChange::
              SAVED_ON_CHROME_SIGNIN);
    }
  }
#endif

  if (reason == HandlerSigninReason::UNLOCK) {
    identity_manager->GetAccountsMutator()->AddOrUpdateAccount(
        gaia_id_, email_, result.refresh_token,
        result.is_under_advanced_protection,
        signin_metrics::SourceForRefreshTokenOperation::
            kInlineLoginHandler_Signin);

    if (signin::IsAutoCloseEnabledInEmbeddedURL(current_url_)) {
      // Close the gaia sign in tab via a task to make sure we aren't in the
      // middle of any webui handler code.
      base::ThreadTaskRunnerHandle::Get()->PostTask(
          FROM_HERE,
          base::BindOnce(&InlineLoginHandlerImpl::CloseTab, handler_));
    }

    if (identity_manager->HasPrimaryAccount()) {
      identity_manager->GetAccountsCookieMutator()->AddAccountToCookie(
          identity_manager->GetPrimaryAccountId(),
          gaia::GaiaSource::kPrimaryAccountManager, {});
    }

    signin_metrics::LogSigninReason(
        GetSigninReasonFromHandlerSigninReason(reason));
  } else {
    if (confirm_untrusted_signin_) {
      // Display a confirmation dialog to the user.
      base::RecordAction(
          base::UserMetricsAction("Signin_Show_UntrustedSigninPrompt"));
      Browser* browser = chrome::FindLastActiveWithProfile(profile_);
      browser->window()->ShowOneClickSigninConfirmation(
          base::UTF8ToUTF16(email_),
          base::BindOnce(&InlineSigninHelper::UntrustedSigninConfirmed,
                         base::Unretained(this), result.refresh_token));
      return;
    }
    CreateSyncStarter(result.refresh_token);
  }
  base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this);
}

void InlineSigninHelper::UntrustedSigninConfirmed(
    const std::string& refresh_token,
    bool confirmed) {
  DCHECK(signin_util::IsForceSigninEnabled());
  base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this);
  if (confirmed) {
    CreateSyncStarter(refresh_token);
    return;
  }

  base::RecordAction(base::UserMetricsAction("Signin_Undo_Signin"));
  BrowserList::CloseAllBrowsersWithProfile(
      profile_, base::Bind(&LockProfileAndShowUserManager),
      // Cannot be called because  skip_beforeunload is true.
      BrowserList::CloseCallback(),
      /*skip_beforeunload=*/true);
}

void InlineSigninHelper::CreateSyncStarter(const std::string& refresh_token) {
  DCHECK(signin_util::IsForceSigninEnabled());
  signin::IdentityManager* identity_manager =
      IdentityManagerFactory::GetForProfile(profile_);
  if (identity_manager->HasPrimaryAccount()) {
    // Already signed in, nothing to do.
    return;
  }

  Browser* browser = chrome::FindLastActiveWithProfile(profile_);
  CoreAccountId account_id =
      identity_manager->GetAccountsMutator()->AddOrUpdateAccount(
          gaia_id_, email_, refresh_token,
          /*is_under_advanced_protection=*/false,
          signin_metrics::SourceForRefreshTokenOperation::
              kInlineLoginHandler_Signin);

  std::unique_ptr<DiceTurnSyncOnHelper::Delegate> delegate =
      std::make_unique<ForcedSigninDiceTurnSyncOnHelperDelegate>(browser);

  new DiceTurnSyncOnHelper(
      profile_, signin::GetAccessPointForEmbeddedPromoURL(current_url_),
      signin_metrics::PromoAction::PROMO_ACTION_NO_SIGNIN_PROMO,
      signin::GetSigninReasonForEmbeddedPromoURL(current_url_), account_id,
      DiceTurnSyncOnHelper::SigninAbortedMode::REMOVE_ACCOUNT,
      std::move(delegate),
      base::BindOnce(&OnSyncSetupComplete, profile_, email_, password_));
}

void InlineSigninHelper::OnClientOAuthFailure(
    const GoogleServiceAuthError& error) {
  if (handler_)
    handler_->HandleLoginError(error.ToString(), base::string16());

  HandlerSigninReason reason = GetHandlerSigninReason(current_url_);
  if (reason != HandlerSigninReason::FETCH_LST_ONLY) {
    AboutSigninInternals* about_signin_internals =
        AboutSigninInternalsFactory::GetForProfile(profile_);
    about_signin_internals->OnRefreshTokenReceived("Failure");
  }

  base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this);
}

InlineLoginHandlerImpl::InlineLoginHandlerImpl()
    : confirm_untrusted_signin_(false) {}

InlineLoginHandlerImpl::~InlineLoginHandlerImpl() {}

// static
void InlineLoginHandlerImpl::SetExtraInitParams(base::DictionaryValue& params) {
  params.SetString("service", "chromiumsync");

  // If this was called from the user manager to reauthenticate the profile,
  // make sure the webui is aware.
  Profile* profile = Profile::FromWebUI(web_ui());
  if (IsSystemProfile(profile))
    params.SetBoolean("dontResizeNonEmbeddedPages", true);

  content::WebContents* contents = web_ui()->GetWebContents();
  const GURL& current_url = contents->GetURL();
  HandlerSigninReason reason = GetHandlerSigninReason(current_url);

  const GURL& url = GaiaUrls::GetInstance()->embedded_signin_url();
  params.SetString("clientId",
                   GaiaUrls::GetInstance()->oauth2_chrome_client_id());
  params.SetString("gaiaPath", url.path().substr(1));

#if defined(OS_WIN)
  if (reason == HandlerSigninReason::FETCH_LST_ONLY) {
    std::string email_domains;
    if (net::GetValueForKeyInQuery(
            current_url, credential_provider::kEmailDomainsSigninPromoParameter,
            &email_domains)) {
      std::vector<std::string> all_email_domains =
          GetEmailDomainsFromParameter(email_domains);
      if (all_email_domains.size() == 1)
        params.SetString("emailDomain", all_email_domains[0]);
    }

    // Prevent opening a new window if the embedded page fails to load.
    // This will keep the user from being able to access a fully functional
    // Chrome window in incognito mode.
    params.SetBoolean("dontResizeNonEmbeddedPages", true);

    // Scrape the SAML password if possible.
    params.SetBoolean("extractSamlPasswordAttributes", true);

    GURL windows_url = GaiaUrls::GetInstance()->embedded_setup_windows_url();
    // Redirect to specified gaia endpoint path for GCPW:
    std::string windows_endpoint_path = windows_url.path().substr(1);
    // Redirect to specified gaia endpoint path for GCPW:
    std::string gcpw_endpoint_path;
    if (net::GetValueForKeyInQuery(
            current_url, credential_provider::kGcpwEndpointPathPromoParameter,
            &gcpw_endpoint_path)) {
      windows_endpoint_path = gcpw_endpoint_path;
    }
    params.SetString("gaiaPath", windows_endpoint_path);
  }
#endif

  std::string flow;
  switch (reason) {
    case HandlerSigninReason::UNLOCK:
      flow = "reauth";
      break;
    case HandlerSigninReason::FORCED_SIGNIN_PRIMARY_ACCOUNT:
      flow = "enterprisefsi";
      break;
    case HandlerSigninReason::FETCH_LST_ONLY: {
#if defined(OS_WIN)
      // Treat a sign in request that specifies a gaia id that must be validated
      // as a reauth request. We only get a gaia id from GCPW when trying to
      // reauth an existing user on the system.
      std::string validate_gaia_id;
      net::GetValueForKeyInQuery(
          current_url, credential_provider::kValidateGaiaIdSigninPromoParameter,
          &validate_gaia_id);
      if (validate_gaia_id.empty()) {
        flow = "signin";
      } else {
        flow = "reauth";
      }
#else
      flow = "signin";
#endif
    } break;
  }
  params.SetString("flow", flow);

  LogHistogramValue(signin_metrics::HISTOGRAM_SHOWN);
}

void InlineLoginHandlerImpl::CompleteLogin(const std::string& email,
                                           const std::string& password,
                                           const std::string& gaia_id,
                                           const std::string& auth_code,
                                           bool skip_for_now,
                                           bool trusted,
                                           bool trusted_found,
                                           bool choose_what_to_sync) {
  content::WebContents* contents = web_ui()->GetWebContents();
  const GURL& current_url = contents->GetURL();

  if (skip_for_now) {
    SyncSetupFailed();
    return;
  }

  // This value exists only for webview sign in.
  if (trusted_found)
    confirm_untrusted_signin_ = !trusted;

  DCHECK(!email.empty());
  DCHECK(!gaia_id.empty());
  DCHECK(!auth_code.empty());

  content::StoragePartition* partition =
      content::BrowserContext::GetStoragePartitionForSite(
          contents->GetBrowserContext(), signin::GetSigninPartitionURL());

  // If this was called from the user manager to reauthenticate the profile,
  // the current profile is the system profile.  In this case, use the email to
  // find the right profile to reauthenticate.  Otherwise the profile can be
  // taken from web_ui().
  HandlerSigninReason reason = GetHandlerSigninReason(current_url);

  Profile* profile = Profile::FromWebUI(web_ui());
  if (reason == HandlerSigninReason::FETCH_LST_ONLY ||
      !IsSystemProfile(profile)) {
    FinishCompleteLogin(FinishCompleteLoginParams(
                            this, partition, current_url, base::FilePath(),
                            confirm_untrusted_signin_, email, gaia_id, password,
                            auth_code, choose_what_to_sync, false),
                        profile, Profile::CREATE_STATUS_CREATED);
    return;
  }

  DCHECK(reason == HandlerSigninReason::FORCED_SIGNIN_PRIMARY_ACCOUNT ||
         reason == HandlerSigninReason::UNLOCK);
  DCHECK(signin_util::IsForceSigninEnabled());

  ProfileManager* manager = g_browser_process->profile_manager();
  base::FilePath path = profiles::GetPathOfProfileWithEmail(manager, email);
  if (path.empty())
    path = UserManager::GetSigninProfilePath();
  if (path.empty())
    return;

  // Switch to the profile and finish the login. Pass the profile path so it can
  // be marked as unlocked.
  FinishCompleteLoginParams params(
      this, partition, current_url, path, confirm_untrusted_signin_, email,
      gaia_id, password, auth_code, choose_what_to_sync, true);
  ProfileManager::CreateCallback callback =
      base::BindRepeating(&InlineLoginHandlerImpl::FinishCompleteLogin, params);
  // Browser window will be opened after ClientOAuthSuccess.
  profiles::LoadProfileAsync(path, callback);
}

InlineLoginHandlerImpl::FinishCompleteLoginParams::FinishCompleteLoginParams(
    InlineLoginHandlerImpl* handler,
    content::StoragePartition* partition,
    const GURL& url,
    const base::FilePath& profile_path,
    bool confirm_untrusted_signin,
    const std::string& email,
    const std::string& gaia_id,
    const std::string& password,
    const std::string& auth_code,
    bool choose_what_to_sync,
    bool is_force_sign_in_with_usermanager)
    : handler(handler),
      partition(partition),
      url(url),
      profile_path(profile_path),
      confirm_untrusted_signin(confirm_untrusted_signin),
      email(email),
      gaia_id(gaia_id),
      password(password),
      auth_code(auth_code),
      choose_what_to_sync(choose_what_to_sync),
      is_force_sign_in_with_usermanager(is_force_sign_in_with_usermanager) {}

InlineLoginHandlerImpl::FinishCompleteLoginParams::FinishCompleteLoginParams(
    const FinishCompleteLoginParams& other) = default;

InlineLoginHandlerImpl::FinishCompleteLoginParams::
    ~FinishCompleteLoginParams() {}

// static
void InlineLoginHandlerImpl::FinishCompleteLogin(
    const FinishCompleteLoginParams& params,
    Profile* profile,
    Profile::CreateStatus status) {
  DCHECK(params.handler);
  HandlerSigninReason reason = GetHandlerSigninReason(params.url);

  std::string default_email;
  net::GetValueForKeyInQuery(params.url, "email", &default_email);
  std::string validate_email;
  net::GetValueForKeyInQuery(params.url, "validateEmail", &validate_email);

#if defined(OS_WIN)
  if (reason == HandlerSigninReason::FETCH_LST_ONLY) {
    std::string validate_gaia_id;
    net::GetValueForKeyInQuery(
        params.url, credential_provider::kValidateGaiaIdSigninPromoParameter,
        &validate_gaia_id);
    std::string email_domains;
    net::GetValueForKeyInQuery(
        params.url, credential_provider::kEmailDomainsSigninPromoParameter,
        &email_domains);
    credential_provider::UiExitCodes exit_code = ValidateSigninEmail(
        validate_gaia_id, email_domains, params.email, params.gaia_id);
    if (exit_code != credential_provider::kUiecSuccess) {
      params.handler->HandleLoginError(base::NumberToString((int)exit_code),
                                       base::UTF8ToUTF16(params.email));
      return;
    } else {
      // Validation has already been done for GCPW, so clear the validate
      // argument so it doesn't validate again. GCPW validation allows the
      // signin email to not match the email given in the request url if the
      // gaia id of the signin email matches the one given in the request url.
      validate_email.clear();
    }
  }
#endif

  // When doing a SAML sign in, this email check may result in a false positive.
  // This happens when the user types one email address in the gaia sign in
  // page, but signs in to a different account in the SAML sign in page.
  if (validate_email == "1" && !default_email.empty()) {
    if (!gaia::AreEmailsSame(params.email, default_email)) {
      params.handler->HandleLoginError(
          l10n_util::GetStringFUTF8(IDS_SYNC_WRONG_EMAIL,
                                    base::UTF8ToUTF16(default_email)),
          base::UTF8ToUTF16(params.email));
      return;
    }
  }

  signin_metrics::AccessPoint access_point =
      signin::GetAccessPointForEmbeddedPromoURL(params.url);
  LogHistogramValue(signin_metrics::HISTOGRAM_ACCEPTED);
  bool switch_to_advanced =
      params.choose_what_to_sync &&
      (access_point != signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS);
  LogHistogramValue(switch_to_advanced
                        ? signin_metrics::HISTOGRAM_WITH_ADVANCED
                        : signin_metrics::HISTOGRAM_WITH_DEFAULTS);

  CanOfferSigninType can_offer_for = CAN_OFFER_SIGNIN_FOR_ALL_ACCOUNTS;
  if (reason == HandlerSigninReason::UNLOCK) {
    std::string primary_username =
        IdentityManagerFactory::GetForProfile(profile)
            ->GetPrimaryAccountInfo()
            .email;
    if (!gaia::AreEmailsSame(default_email, primary_username))
      can_offer_for = CAN_OFFER_SIGNIN_FOR_SECONDARY_ACCOUNT;
  }

  std::string error_msg;
  bool can_offer = reason == HandlerSigninReason::FETCH_LST_ONLY ||
                   CanOfferSignin(profile, can_offer_for, params.gaia_id,
                                  params.email, &error_msg);
  if (!can_offer) {
    params.handler->HandleLoginError(error_msg,
                                     base::UTF8ToUTF16(params.email));
    return;
  }

  AboutSigninInternals* about_signin_internals =
      AboutSigninInternalsFactory::GetForProfile(profile);
  if (about_signin_internals)
    about_signin_internals->OnAuthenticationResultReceived("Successful");

  std::string signin_scoped_device_id =
      GetSigninScopedDeviceIdForProfile(profile);

  // InlineSigninHelper will delete itself.
  new InlineSigninHelper(
      params.handler->GetWeakPtr(),
      params.partition->GetURLLoaderFactoryForBrowserProcess(), profile, status,
      params.url, params.email, params.gaia_id, params.password,
      params.auth_code, signin_scoped_device_id,
      params.confirm_untrusted_signin,
      params.is_force_sign_in_with_usermanager);

  // If opened from user manager to unlock a profile, make sure the user manager
  // is closed and that the profile is marked as unlocked.
  if (reason != HandlerSigninReason::FETCH_LST_ONLY &&
      !params.is_force_sign_in_with_usermanager) {
    UnlockProfileAndHideLoginUI(params.profile_path, params.handler);
  }
}

void InlineLoginHandlerImpl::HandleLoginError(const std::string& error_msg,
                                              const base::string16& email) {
  content::WebContents* contents = web_ui()->GetWebContents();
  const GURL& current_url = contents->GetURL();
  HandlerSigninReason reason = GetHandlerSigninReason(current_url);

  if (reason == HandlerSigninReason::FETCH_LST_ONLY) {
    base::Value error_value(base::Value::Type::DICTIONARY);
#if defined(OS_WIN)
    // If the message is an integer error code, send it as part of the result.
    int exit_code = 0;
    if (base::StringToInt(error_msg, &exit_code)) {
      error_value.SetKey(credential_provider::kKeyExitCode,
                         base::Value(exit_code));
    }
#endif
    SendLSTFetchResultsMessage(error_value);
    return;
  }
  SyncSetupFailed();
  Browser* browser = GetDesktopBrowser();
  Profile* profile = Profile::FromWebUI(web_ui());

  if (IsSystemProfile(profile))
    profile = g_browser_process->profile_manager()->GetProfileByPath(
        UserManager::GetSigninProfilePath());
  if (!error_msg.empty()) {
    LoginUIServiceFactory::GetForProfile(profile)->DisplayLoginResult(
        browser, base::UTF8ToUTF16(error_msg), email);
  }
}

void InlineLoginHandlerImpl::SendLSTFetchResultsMessage(
    const base::Value& arg) {
  if (IsJavascriptAllowed())
    CallJavascriptFunction("inline.login.sendLSTFetchResults", arg);
}

Browser* InlineLoginHandlerImpl::GetDesktopBrowser() {
  Browser* browser =
      chrome::FindBrowserWithWebContents(web_ui()->GetWebContents());
  if (!browser)
    browser = chrome::FindLastActiveWithProfile(Profile::FromWebUI(web_ui()));
  return browser;
}

void InlineLoginHandlerImpl::SyncSetupFailed() {
  content::WebContents* contents = web_ui()->GetWebContents();

  if (contents->GetController().GetPendingEntry()) {
    // Do nothing if a navigation is pending, since this call can be triggered
    // from DidStartLoading. This avoids deleting the pending entry while we are
    // still navigating to it. See crbug/346632.
    return;
  }

  const GURL& current_url = contents->GetLastCommittedURL();
  signin_metrics::AccessPoint access_point =
      signin::GetAccessPointForEmbeddedPromoURL(current_url);
  RedirectToNtpOrAppsPage(contents, access_point);
}

void InlineLoginHandlerImpl::CloseTab() {
  content::WebContents* tab = web_ui()->GetWebContents();
  Browser* browser = chrome::FindBrowserWithWebContents(tab);
  if (browser) {
    TabStripModel* tab_strip_model = browser->tab_strip_model();
    if (tab_strip_model) {
      int index = tab_strip_model->GetIndexOfWebContents(tab);
      if (index != TabStripModel::kNoTab) {
        tab_strip_model->ExecuteContextMenuCommand(
            index, TabStripModel::CommandCloseTab);
      }
    }
  }
}