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/chromeos/login/login_utils.h"
11 #include "base/bind.h"
12 #include "base/command_line.h"
13 #include "base/compiler_specific.h"
14 #include "base/file_util.h"
15 #include "base/files/file_path.h"
16 #include "base/location.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/memory/singleton.h"
20 #include "base/memory/weak_ptr.h"
21 #include "base/path_service.h"
22 #include "base/prefs/pref_member.h"
23 #include "base/prefs/pref_registry_simple.h"
24 #include "base/prefs/pref_service.h"
25 #include "base/strings/string_util.h"
26 #include "base/strings/utf_string_conversions.h"
27 #include "base/synchronization/lock.h"
28 #include "base/sys_info.h"
29 #include "base/task_runner_util.h"
30 #include "base/threading/worker_pool.h"
31 #include "base/time/time.h"
32 #include "chrome/browser/about_flags.h"
33 #include "chrome/browser/app_mode/app_mode_utils.h"
34 #include "chrome/browser/browser_process.h"
35 #include "chrome/browser/browser_shutdown.h"
36 #include "chrome/browser/chrome_notification_types.h"
37 #include "chrome/browser/chromeos/boot_times_loader.h"
38 #include "chrome/browser/chromeos/input_method/input_method_util.h"
39 #include "chrome/browser/chromeos/login/chrome_restart_request.h"
40 #include "chrome/browser/chromeos/login/demo_mode/demo_app_launcher.h"
41 #include "chrome/browser/chromeos/login/input_events_blocker.h"
42 #include "chrome/browser/chromeos/login/login_display_host.h"
43 #include "chrome/browser/chromeos/login/oauth2_login_manager.h"
44 #include "chrome/browser/chromeos/login/oauth2_login_manager_factory.h"
45 #include "chrome/browser/chromeos/login/parallel_authenticator.h"
46 #include "chrome/browser/chromeos/login/profile_auth_data.h"
47 #include "chrome/browser/chromeos/login/saml/saml_offline_signin_limiter.h"
48 #include "chrome/browser/chromeos/login/saml/saml_offline_signin_limiter_factory.h"
49 #include "chrome/browser/chromeos/login/screen_locker.h"
50 #include "chrome/browser/chromeos/login/supervised_user_manager.h"
51 #include "chrome/browser/chromeos/login/user.h"
52 #include "chrome/browser/chromeos/login/user_manager.h"
53 #include "chrome/browser/chromeos/settings/cros_settings.h"
54 #include "chrome/browser/extensions/extension_service.h"
55 #include "chrome/browser/first_run/first_run.h"
56 #include "chrome/browser/google/google_util_chromeos.h"
57 #include "chrome/browser/lifetime/application_lifetime.h"
58 #include "chrome/browser/pref_service_flags_storage.h"
59 #include "chrome/browser/profiles/profile.h"
60 #include "chrome/browser/profiles/profile_manager.h"
61 #include "chrome/browser/rlz/rlz.h"
62 #include "chrome/browser/sync/profile_sync_service.h"
63 #include "chrome/browser/sync/profile_sync_service_factory.h"
64 #include "chrome/browser/ui/app_list/start_page_service.h"
65 #include "chrome/browser/ui/startup/startup_browser_creator.h"
66 #include "chrome/common/chrome_paths.h"
67 #include "chrome/common/chrome_switches.h"
68 #include "chrome/common/logging_chrome.h"
69 #include "chrome/common/pref_names.h"
70 #include "chromeos/chromeos_switches.h"
71 #include "chromeos/cryptohome/cryptohome_util.h"
72 #include "chromeos/dbus/cryptohome_client.h"
73 #include "chromeos/dbus/dbus_method_call_status.h"
74 #include "chromeos/dbus/dbus_thread_manager.h"
75 #include "chromeos/dbus/session_manager_client.h"
76 #include "chromeos/ime/input_method_manager.h"
77 #include "chromeos/settings/cros_settings_names.h"
78 #include "content/public/browser/browser_thread.h"
79 #include "content/public/browser/notification_service.h"
80 #include "google_apis/gaia/gaia_auth_consumer.h"
81 #include "net/base/network_change_notifier.h"
82 #include "net/url_request/url_request_context.h"
83 #include "net/url_request/url_request_context_getter.h"
86 using content::BrowserThread;
92 #if defined(ENABLE_RLZ)
93 // Flag file that disables RLZ tracking, when present.
94 const base::FilePath::CharType kRLZDisabledFlagName[] =
95 FILE_PATH_LITERAL(".rlz_disabled");
97 base::FilePath GetRlzDisabledFlagPath() {
98 return base::GetHomeDir().Append(kRLZDisabledFlagName);
104 struct DoBrowserLaunchOnLocaleLoadedData;
108 public OAuth2LoginManager::Observer,
109 public net::NetworkChangeNotifier::ConnectionTypeObserver,
110 public base::SupportsWeakPtr<LoginUtilsImpl> {
113 : has_web_auth_cookies_(false),
115 exit_after_session_restore_(false),
116 session_restore_strategy_(
117 OAuth2LoginManager::RESTORE_FROM_SAVED_OAUTH2_REFRESH_TOKEN) {
118 net::NetworkChangeNotifier::AddConnectionTypeObserver(this);
121 virtual ~LoginUtilsImpl() {
122 net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
125 // LoginUtils implementation:
126 virtual void DoBrowserLaunch(Profile* profile,
127 LoginDisplayHost* login_host) OVERRIDE;
128 virtual void PrepareProfile(
129 const UserContext& user_context,
130 const std::string& display_email,
132 bool has_active_session,
133 LoginUtils::Delegate* delegate) OVERRIDE;
134 virtual void DelegateDeleted(LoginUtils::Delegate* delegate) OVERRIDE;
135 virtual void CompleteOffTheRecordLogin(const GURL& start_url) OVERRIDE;
136 virtual void SetFirstLoginPrefs(PrefService* prefs) OVERRIDE;
137 virtual scoped_refptr<Authenticator> CreateAuthenticator(
138 LoginStatusConsumer* consumer) OVERRIDE;
139 virtual void RestoreAuthenticationSession(Profile* profile) OVERRIDE;
140 virtual void InitRlzDelayed(Profile* user_profile) OVERRIDE;
142 // OAuth2LoginManager::Observer overrides.
143 virtual void OnSessionRestoreStateChanged(
144 Profile* user_profile,
145 OAuth2LoginManager::SessionRestoreState state) OVERRIDE;
146 virtual void OnNewRefreshTokenAvaiable(Profile* user_profile) OVERRIDE;
148 // net::NetworkChangeNotifier::ConnectionTypeObserver overrides.
149 virtual void OnConnectionTypeChanged(
150 net::NetworkChangeNotifier::ConnectionType type) OVERRIDE;
153 typedef std::set<std::string> SessionRestoreStateSet;
155 // DoBrowserLaunch is split into two parts.
156 // This one is called after anynchronous locale switch.
157 void DoBrowserLaunchOnLocaleLoadedImpl(Profile* profile,
158 LoginDisplayHost* login_host);
160 // Callback for locale_util::SwitchLanguage().
161 static void DoBrowserLaunchOnLocaleLoaded(
162 scoped_ptr<DoBrowserLaunchOnLocaleLoadedData> context,
163 const std::string& locale,
164 const std::string& loaded_locale,
167 // Restarts OAuth session authentication check.
168 void KickStartAuthentication(Profile* profile);
170 // Callback for Profile::CREATE_STATUS_CREATED profile state.
171 // Initializes basic preferences for newly created profile. Any other
172 // early profile initialization that needs to happen before
173 // ProfileManager::DoFinalInit() gets called is done here.
174 void InitProfilePreferences(Profile* user_profile,
175 const std::string& email);
177 // Callback for asynchronous profile creation.
178 void OnProfileCreated(const std::string& email,
180 Profile::CreateStatus status);
182 // Callback for asynchronous off the record profile creation.
183 void OnOTRProfileCreated(const std::string& email,
185 Profile::CreateStatus status);
187 // Callback for Profile::CREATE_STATUS_INITIALIZED profile state.
188 // Profile is created, extensions and promo resources are initialized.
189 void UserProfileInitialized(Profile* user_profile);
191 // Callback for Profile::CREATE_STATUS_INITIALIZED profile state for an OTR
193 void OTRProfileInitialized(Profile* user_profile);
195 // Callback to resume profile creation after transferring auth data from
196 // the authentication profile.
197 void CompleteProfileCreate(Profile* user_profile);
199 // Finalized profile preparation.
200 void FinalizePrepareProfile(Profile* user_profile);
202 // Initializes member variables needed for session restore process via
203 // OAuthLoginManager.
204 void InitSessionRestoreStrategy();
206 // Restores GAIA auth cookies for the created user profile from OAuth2 token.
207 void RestoreAuthSession(Profile* user_profile,
208 bool restore_from_auth_cookies);
210 // Initializes RLZ. If |disabled| is true, RLZ pings are disabled.
211 void InitRlz(Profile* user_profile, bool disabled);
213 // Attempts restarting the browser process and esures that this does
214 // not happen while we are still fetching new OAuth refresh tokens.
215 void AttemptRestart(Profile* profile);
217 UserContext user_context_;
219 // True if the authentication profile's cookie jar should contain
220 // authentication cookies from the authentication extension log in flow.
221 bool has_web_auth_cookies_;
222 // Has to be scoped_refptr, see comment for CreateAuthenticator(...).
223 scoped_refptr<Authenticator> authenticator_;
225 // Delegate to be fired when the profile will be prepared.
226 LoginUtils::Delegate* delegate_;
228 // Set of user_id for those users that we should restore authentication
229 // session when notified about online state change.
230 SessionRestoreStateSet pending_restore_sessions_;
232 // True if we should restart chrome right after session restore.
233 bool exit_after_session_restore_;
235 // Sesion restore strategy.
236 OAuth2LoginManager::SessionRestoreStrategy session_restore_strategy_;
237 // OAuth2 refresh token for session restore.
238 std::string oauth2_refresh_token_;
240 DISALLOW_COPY_AND_ASSIGN(LoginUtilsImpl);
243 class LoginUtilsWrapper {
245 static LoginUtilsWrapper* GetInstance() {
246 return Singleton<LoginUtilsWrapper>::get();
250 base::AutoLock create(create_lock_);
252 reset(new LoginUtilsImpl);
256 void reset(LoginUtils* ptr) {
261 friend struct DefaultSingletonTraits<LoginUtilsWrapper>;
263 LoginUtilsWrapper() {}
265 base::Lock create_lock_;
266 scoped_ptr<LoginUtils> ptr_;
268 DISALLOW_COPY_AND_ASSIGN(LoginUtilsWrapper);
271 struct DoBrowserLaunchOnLocaleLoadedData {
272 DoBrowserLaunchOnLocaleLoadedData(LoginUtilsImpl* login_utils_impl,
274 LoginDisplayHost* display_host)
275 : login_utils_impl(login_utils_impl),
277 display_host(display_host) {}
279 LoginUtilsImpl* login_utils_impl;
281 chromeos::LoginDisplayHost* display_host;
283 // Block UI events untill ResourceBundle is reloaded.
284 InputEventsBlocker input_events_blocker;
288 void LoginUtilsImpl::DoBrowserLaunchOnLocaleLoaded(
289 scoped_ptr<DoBrowserLaunchOnLocaleLoadedData> context,
290 const std::string& /* locale */,
291 const std::string& /* loaded_locale */,
292 const bool /* success */) {
293 context->login_utils_impl->DoBrowserLaunchOnLocaleLoadedImpl(
294 context->profile, context->display_host);
297 // Called from DoBrowserLaunch() or from
298 // DoBrowserLaunchOnLocaleLoaded() depending on
299 // if locale switch was needed.
300 void LoginUtilsImpl::DoBrowserLaunchOnLocaleLoadedImpl(
302 LoginDisplayHost* login_host) {
303 if (!UserManager::Get()->GetCurrentUserFlow()->ShouldLaunchBrowser()) {
304 UserManager::Get()->GetCurrentUserFlow()->LaunchExtraSteps(profile);
308 CommandLine user_flags(CommandLine::NO_PROGRAM);
309 about_flags::PrefServiceFlagsStorage flags_storage_(profile->GetPrefs());
310 about_flags::ConvertFlagsToSwitches(&flags_storage_, &user_flags,
311 about_flags::kAddSentinels);
312 // Only restart if needed and if not going into managed mode.
313 // Don't restart browser if it is not first profile in session.
314 if (UserManager::Get()->GetLoggedInUsers().size() == 1 &&
315 !UserManager::Get()->IsLoggedInAsLocallyManagedUser() &&
316 !about_flags::AreSwitchesIdenticalToCurrentCommandLine(
317 user_flags, *CommandLine::ForCurrentProcess())) {
318 CommandLine::StringVector flags;
319 // argv[0] is the program name |CommandLine::NO_PROGRAM|.
320 flags.assign(user_flags.argv().begin() + 1, user_flags.argv().end());
321 VLOG(1) << "Restarting to apply per-session flags...";
322 DBusThreadManager::Get()->GetSessionManagerClient()->SetFlagsForUser(
323 UserManager::Get()->GetActiveUser()->email(), flags);
324 AttemptRestart(profile);
329 login_host->SetStatusAreaVisible(true);
330 login_host->BeforeSessionStart();
333 BootTimesLoader::Get()->AddLoginTimeMarker("BrowserLaunched", false);
335 VLOG(1) << "Launching browser...";
336 StartupBrowserCreator browser_creator;
338 chrome::startup::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
339 chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;
341 browser_creator.LaunchBrowser(*CommandLine::ForCurrentProcess(),
344 chrome::startup::IS_PROCESS_STARTUP,
348 // Triggers app launcher start page service to load start page web contents.
349 app_list::StartPageService::Get(profile);
351 // Mark login host for deletion after browser starts. This
352 // guarantees that the message loop will be referenced by the
353 // browser before it is dereferenced by the login host.
355 login_host->Finalize();
356 UserManager::Get()->SessionStarted();
359 void LoginUtilsImpl::DoBrowserLaunch(Profile* profile,
360 LoginDisplayHost* login_host) {
361 if (browser_shutdown::IsTryingToQuit())
364 User* const user = UserManager::Get()->GetUserByProfile(profile);
365 scoped_ptr<DoBrowserLaunchOnLocaleLoadedData> data(
366 new DoBrowserLaunchOnLocaleLoadedData(this, profile, login_host));
368 scoped_ptr<locale_util::SwitchLanguageCallback> callback(
369 new locale_util::SwitchLanguageCallback(
370 base::Bind(&LoginUtilsImpl::DoBrowserLaunchOnLocaleLoaded,
371 base::Passed(data.Pass()))));
372 if (!UserManager::Get()->
373 RespectLocalePreference(profile, user, callback.Pass())) {
374 DoBrowserLaunchOnLocaleLoadedImpl(profile, login_host);
378 void LoginUtilsImpl::PrepareProfile(
379 const UserContext& user_context,
380 const std::string& display_email,
382 bool has_active_session,
383 LoginUtils::Delegate* delegate) {
384 BootTimesLoader* btl = BootTimesLoader::Get();
386 VLOG(1) << "Completing login for " << user_context.username;
388 if (!has_active_session) {
389 btl->AddLoginTimeMarker("StartSession-Start", false);
390 DBusThreadManager::Get()->GetSessionManagerClient()->StartSession(
391 user_context.username);
392 btl->AddLoginTimeMarker("StartSession-End", false);
395 btl->AddLoginTimeMarker("UserLoggedIn-Start", false);
396 UserManager* user_manager = UserManager::Get();
397 user_manager->UserLoggedIn(user_context.username,
398 user_context.username_hash,
400 btl->AddLoginTimeMarker("UserLoggedIn-End", false);
402 // Switch log file as soon as possible.
403 if (base::SysInfo::IsRunningOnChromeOS())
404 logging::RedirectChromeLogging(*(CommandLine::ForCurrentProcess()));
406 // Update user's displayed email.
407 if (!display_email.empty())
408 user_manager->SaveUserDisplayEmail(user_context.username, display_email);
410 user_context_ = user_context;
412 has_web_auth_cookies_ = has_cookies;
413 delegate_ = delegate;
414 InitSessionRestoreStrategy();
416 base::FilePath profile_dir;
417 if (DemoAppLauncher::IsDemoAppSession(user_context.username)) {
418 g_browser_process->profile_manager()->CreateProfileAsync(
419 ProfileManager::GetGuestProfilePath(),
420 base::Bind(&LoginUtilsImpl::OnOTRProfileCreated, AsWeakPtr(),
421 user_context.username),
422 base::string16(), base::string16(), std::string());
424 // Can't use display_email because it is empty when existing user logs in
425 // using sing-in pod on login screen (i.e. user didn't type email).
426 g_browser_process->profile_manager()->CreateProfileAsync(
427 user_manager->GetUserProfileDir(user_context.username),
428 base::Bind(&LoginUtilsImpl::OnProfileCreated, AsWeakPtr(),
429 user_context.username),
430 base::string16(), base::string16(), std::string());
434 void LoginUtilsImpl::DelegateDeleted(LoginUtils::Delegate* delegate) {
435 if (delegate_ == delegate)
439 void LoginUtilsImpl::InitProfilePreferences(Profile* user_profile,
440 const std::string& user_id) {
441 if (UserManager::Get()->IsCurrentUserNew())
442 SetFirstLoginPrefs(user_profile->GetPrefs());
444 if (UserManager::Get()->IsLoggedInAsLocallyManagedUser()) {
445 User* active_user = UserManager::Get()->GetActiveUser();
446 std::string managed_user_sync_id =
447 UserManager::Get()->GetSupervisedUserManager()->
448 GetUserSyncId(active_user->email());
450 // TODO(ibraaaa): Remove that when 97% of our users are using M31.
451 // http://crbug.com/276163
452 if (managed_user_sync_id.empty())
453 managed_user_sync_id = "DUMMY_ID";
455 user_profile->GetPrefs()->SetString(prefs::kManagedUserId,
456 managed_user_sync_id);
458 // Make sure that the google service username is properly set (we do this
459 // on every sign in, not just the first login, to deal with existing
460 // profiles that might not have it set yet).
461 StringPrefMember google_services_username;
462 google_services_username.Init(prefs::kGoogleServicesUsername,
463 user_profile->GetPrefs());
464 google_services_username.SetValue(user_id);
468 void LoginUtilsImpl::InitSessionRestoreStrategy() {
469 CommandLine* command_line = CommandLine::ForCurrentProcess();
470 bool in_app_mode = chrome::IsRunningInForcedAppMode();
472 // Are we in kiosk app mode?
474 if (command_line->HasSwitch(::switches::kAppModeOAuth2Token)) {
475 oauth2_refresh_token_ = command_line->GetSwitchValueASCII(
476 ::switches::kAppModeOAuth2Token);
479 if (command_line->HasSwitch(::switches::kAppModeAuthCode)) {
480 user_context_.auth_code = command_line->GetSwitchValueASCII(
481 ::switches::kAppModeAuthCode);
484 DCHECK(!has_web_auth_cookies_);
485 if (!user_context_.auth_code.empty()) {
486 session_restore_strategy_ = OAuth2LoginManager::RESTORE_FROM_AUTH_CODE;
487 } else if (!oauth2_refresh_token_.empty()) {
488 session_restore_strategy_ =
489 OAuth2LoginManager::RESTORE_FROM_PASSED_OAUTH2_REFRESH_TOKEN;
491 session_restore_strategy_ =
492 OAuth2LoginManager::RESTORE_FROM_SAVED_OAUTH2_REFRESH_TOKEN;
497 if (has_web_auth_cookies_) {
498 session_restore_strategy_ = OAuth2LoginManager::RESTORE_FROM_COOKIE_JAR;
499 } else if (!user_context_.auth_code.empty()) {
500 session_restore_strategy_ = OAuth2LoginManager::RESTORE_FROM_AUTH_CODE;
502 session_restore_strategy_ =
503 OAuth2LoginManager::RESTORE_FROM_SAVED_OAUTH2_REFRESH_TOKEN;
508 void LoginUtilsImpl::OnProfileCreated(
509 const std::string& user_id,
510 Profile* user_profile,
511 Profile::CreateStatus status) {
515 case Profile::CREATE_STATUS_CREATED:
516 InitProfilePreferences(user_profile, user_id);
518 case Profile::CREATE_STATUS_INITIALIZED:
519 UserProfileInitialized(user_profile);
521 case Profile::CREATE_STATUS_LOCAL_FAIL:
522 case Profile::CREATE_STATUS_REMOTE_FAIL:
523 case Profile::CREATE_STATUS_CANCELED:
524 case Profile::MAX_CREATE_STATUS:
530 void LoginUtilsImpl::OnOTRProfileCreated(
531 const std::string& user_id,
532 Profile* user_profile,
533 Profile::CreateStatus status) {
537 case Profile::CREATE_STATUS_CREATED:
538 InitProfilePreferences(user_profile, user_id);
540 case Profile::CREATE_STATUS_INITIALIZED:
541 OTRProfileInitialized(user_profile);
543 case Profile::CREATE_STATUS_LOCAL_FAIL:
544 case Profile::CREATE_STATUS_REMOTE_FAIL:
545 case Profile::CREATE_STATUS_CANCELED:
546 case Profile::MAX_CREATE_STATUS:
552 void LoginUtilsImpl::UserProfileInitialized(Profile* user_profile) {
553 BootTimesLoader* btl = BootTimesLoader::Get();
554 btl->AddLoginTimeMarker("UserProfileGotten", false);
556 if (user_context_.using_oauth) {
557 // Transfer proxy authentication cache, cookies (optionally) and server
558 // bound certs from the profile that was used for authentication. This
559 // profile contains cookies that auth extension should have already put in
560 // place that will ensure that the newly created session is authenticated
561 // for the websites that work with the used authentication schema.
562 ProfileAuthData::Transfer(authenticator_->authentication_profile(),
564 has_web_auth_cookies_, // transfer_cookies
566 &LoginUtilsImpl::CompleteProfileCreate,
572 FinalizePrepareProfile(user_profile);
575 void LoginUtilsImpl::OTRProfileInitialized(Profile* user_profile) {
576 user_profile->OnLogin();
577 // Send the notification before creating the browser so additional objects
578 // that need the profile (e.g. the launcher) can be created first.
579 content::NotificationService::current()->Notify(
580 chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED,
581 content::NotificationService::AllSources(),
582 content::Details<Profile>(user_profile));
585 delegate_->OnProfilePrepared(user_profile);
588 void LoginUtilsImpl::CompleteProfileCreate(Profile* user_profile) {
589 RestoreAuthSession(user_profile, has_web_auth_cookies_);
590 FinalizePrepareProfile(user_profile);
593 void LoginUtilsImpl::RestoreAuthSession(Profile* user_profile,
594 bool restore_from_auth_cookies) {
595 CHECK((authenticator_.get() && authenticator_->authentication_profile()) ||
596 !restore_from_auth_cookies);
598 if (chrome::IsRunningInForcedAppMode() ||
599 CommandLine::ForCurrentProcess()->HasSwitch(
600 chromeos::switches::kOobeSkipPostLogin)) {
604 exit_after_session_restore_ = false;
605 // Remove legacy OAuth1 token if we have one. If it's valid, we should already
606 // have OAuth2 refresh token in OAuth2TokenService that could be used to
607 // retrieve all other tokens and user_context.
608 OAuth2LoginManager* login_manager =
609 OAuth2LoginManagerFactory::GetInstance()->GetForProfile(user_profile);
610 login_manager->AddObserver(this);
611 login_manager->RestoreSession(
612 authenticator_.get() && authenticator_->authentication_profile()
613 ? authenticator_->authentication_profile()->GetRequestContext()
615 session_restore_strategy_,
616 oauth2_refresh_token_,
617 user_context_.auth_code);
620 void LoginUtilsImpl::FinalizePrepareProfile(Profile* user_profile) {
621 BootTimesLoader* btl = BootTimesLoader::Get();
622 // Own TPM device if, for any reason, it has not been done in EULA
624 CryptohomeClient* client = DBusThreadManager::Get()->GetCryptohomeClient();
625 btl->AddLoginTimeMarker("TPMOwn-Start", false);
626 if (cryptohome_util::TpmIsEnabled() && !cryptohome_util::TpmIsBeingOwned()) {
627 if (cryptohome_util::TpmIsOwned()) {
628 client->CallTpmClearStoredPasswordAndBlock();
630 client->TpmCanAttemptOwnership(EmptyVoidDBusMethodCallback());
633 btl->AddLoginTimeMarker("TPMOwn-End", false);
635 if (UserManager::Get()->IsLoggedInAsRegularUser()) {
636 SAMLOfflineSigninLimiter* saml_offline_signin_limiter =
637 SAMLOfflineSigninLimiterFactory::GetForProfile(user_profile);
638 if (saml_offline_signin_limiter)
639 saml_offline_signin_limiter->SignedIn(user_context_.auth_flow);
642 user_profile->OnLogin();
644 // Send the notification before creating the browser so additional objects
645 // that need the profile (e.g. the launcher) can be created first.
646 content::NotificationService::current()->Notify(
647 chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED,
648 content::NotificationService::AllSources(),
649 content::Details<Profile>(user_profile));
651 // Initialize RLZ only for primary user.
652 if (UserManager::Get()->GetPrimaryUser() ==
653 UserManager::Get()->GetUserByProfile(user_profile)) {
654 InitRlzDelayed(user_profile);
656 // TODO(altimofeev): This pointer should probably never be NULL, but it looks
657 // like LoginUtilsImpl::OnProfileCreated() may be getting called before
658 // LoginUtilsImpl::PrepareProfile() has set |delegate_| when Chrome is killed
659 // during shutdown in tests -- see http://crosbug.com/18269. Replace this
660 // 'if' statement with a CHECK(delegate_) once the underlying issue is
663 delegate_->OnProfilePrepared(user_profile);
666 void LoginUtilsImpl::InitRlzDelayed(Profile* user_profile) {
667 #if defined(ENABLE_RLZ)
668 if (!g_browser_process->local_state()->HasPrefPath(prefs::kRLZBrand)) {
669 // Read brand code asynchronously from an OEM file and repost ourselves.
670 google_util::chromeos::SetBrandFromFile(
671 base::Bind(&LoginUtilsImpl::InitRlzDelayed, AsWeakPtr(), user_profile));
674 base::PostTaskAndReplyWithResult(
675 base::WorkerPool::GetTaskRunner(false),
677 base::Bind(&base::PathExists, GetRlzDisabledFlagPath()),
678 base::Bind(&LoginUtilsImpl::InitRlz, AsWeakPtr(), user_profile));
682 void LoginUtilsImpl::InitRlz(Profile* user_profile, bool disabled) {
683 #if defined(ENABLE_RLZ)
684 PrefService* local_state = g_browser_process->local_state();
686 // Empty brand code means an organic install (no RLZ pings are sent).
687 google_util::chromeos::ClearBrandForCurrentSession();
689 if (disabled != local_state->GetBoolean(prefs::kRLZDisabled)) {
690 // When switching to RLZ enabled/disabled state, clear all recorded events.
691 RLZTracker::ClearRlzState();
692 local_state->SetBoolean(prefs::kRLZDisabled, disabled);
694 // Init the RLZ library.
695 int ping_delay = user_profile->GetPrefs()->GetInteger(
696 first_run::GetPingDelayPrefName().c_str());
697 // Negative ping delay means to send ping immediately after a first search is
699 RLZTracker::InitRlzFromProfileDelayed(
700 user_profile, UserManager::Get()->IsCurrentUserNew(),
701 ping_delay < 0, base::TimeDelta::FromMilliseconds(abs(ping_delay)));
703 delegate_->OnRlzInitialized(user_profile);
707 void LoginUtilsImpl::CompleteOffTheRecordLogin(const GURL& start_url) {
708 VLOG(1) << "Completing incognito login";
710 // For guest session we ask session manager to restart Chrome with --bwsi
711 // flag. We keep only some of the arguments of this process.
712 const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
713 CommandLine command_line(browser_command_line.GetProgram());
714 std::string cmd_line_str = GetOffTheRecordCommandLine(start_url,
715 browser_command_line,
718 RestartChrome(cmd_line_str);
721 void LoginUtilsImpl::SetFirstLoginPrefs(PrefService* prefs) {
722 VLOG(1) << "Setting first login prefs";
723 BootTimesLoader* btl = BootTimesLoader::Get();
724 std::string locale = g_browser_process->GetApplicationLocale();
726 // First, we'll set kLanguagePreloadEngines.
727 input_method::InputMethodManager* manager =
728 input_method::InputMethodManager::Get();
729 std::vector<std::string> input_method_ids;
730 manager->GetInputMethodUtil()->GetFirstLoginInputMethodIds(
731 locale, manager->GetCurrentInputMethod(), &input_method_ids);
732 // Save the input methods in the user's preferences.
733 StringPrefMember language_preload_engines;
734 language_preload_engines.Init(prefs::kLanguagePreloadEngines,
736 language_preload_engines.SetValue(JoinString(input_method_ids, ','));
737 btl->AddLoginTimeMarker("IMEStarted", false);
739 // Second, we'll set kLanguagePreferredLanguages.
740 std::vector<std::string> language_codes;
741 // The current locale should be on the top.
742 language_codes.push_back(locale);
744 // Add input method IDs based on the input methods, as there may be
745 // input methods that are unrelated to the current locale. Example: the
746 // hardware keyboard layout xkb:us::eng is used for logging in, but the
747 // UI language is set to French. In this case, we should set "fr,en"
748 // to the preferred languages preference.
749 std::vector<std::string> candidates;
750 manager->GetInputMethodUtil()->GetLanguageCodesFromInputMethodIds(
751 input_method_ids, &candidates);
752 for (size_t i = 0; i < candidates.size(); ++i) {
753 const std::string& candidate = candidates[i];
754 // Skip if it's already in language_codes.
755 if (std::count(language_codes.begin(), language_codes.end(),
757 language_codes.push_back(candidate);
760 // Save the preferred languages in the user's preferences.
761 StringPrefMember language_preferred_languages;
762 language_preferred_languages.Init(prefs::kLanguagePreferredLanguages,
764 language_preferred_languages.SetValue(JoinString(language_codes, ','));
767 scoped_refptr<Authenticator> LoginUtilsImpl::CreateAuthenticator(
768 LoginStatusConsumer* consumer) {
769 // Screen locker needs new Authenticator instance each time.
770 if (ScreenLocker::default_screen_locker()) {
771 if (authenticator_.get())
772 authenticator_->SetConsumer(NULL);
773 authenticator_ = NULL;
776 if (authenticator_.get() == NULL) {
777 authenticator_ = new ParallelAuthenticator(consumer);
779 // TODO(nkostylev): Fix this hack by improving Authenticator dependencies.
780 authenticator_->SetConsumer(consumer);
782 return authenticator_;
785 void LoginUtilsImpl::RestoreAuthenticationSession(Profile* user_profile) {
786 UserManager* user_manager = UserManager::Get();
787 // We don't need to restore session for demo/guest/stub/public account users.
788 if (!user_manager->IsUserLoggedIn() ||
789 user_manager->IsLoggedInAsGuest() ||
790 user_manager->IsLoggedInAsPublicAccount() ||
791 user_manager->IsLoggedInAsDemoUser() ||
792 user_manager->IsLoggedInAsStub()) {
796 User* user = user_manager->GetUserByProfile(user_profile);
798 if (!net::NetworkChangeNotifier::IsOffline()) {
799 pending_restore_sessions_.erase(user->email());
800 RestoreAuthSession(user_profile, false);
802 // Even if we're online we should wait till initial
803 // OnConnectionTypeChanged() call. Otherwise starting fetchers too early may
804 // end up canceling all request when initial network connection type is
805 // processed. See http://crbug.com/121643.
806 pending_restore_sessions_.insert(user->email());
810 void LoginUtilsImpl::OnSessionRestoreStateChanged(
811 Profile* user_profile,
812 OAuth2LoginManager::SessionRestoreState state) {
813 User::OAuthTokenStatus user_status = User::OAUTH_TOKEN_STATUS_UNKNOWN;
814 OAuth2LoginManager* login_manager =
815 OAuth2LoginManagerFactory::GetInstance()->GetForProfile(user_profile);
817 bool connection_error = false;
819 case OAuth2LoginManager::SESSION_RESTORE_DONE:
820 user_status = User::OAUTH2_TOKEN_STATUS_VALID;
822 case OAuth2LoginManager::SESSION_RESTORE_FAILED:
823 user_status = User::OAUTH2_TOKEN_STATUS_INVALID;
825 case OAuth2LoginManager::SESSION_RESTORE_CONNECTION_FAILED:
826 connection_error = true;
828 case OAuth2LoginManager::SESSION_RESTORE_NOT_STARTED:
829 case OAuth2LoginManager::SESSION_RESTORE_PREPARING:
830 case OAuth2LoginManager::SESSION_RESTORE_IN_PROGRESS:
834 // We should not be clearing existing token state if that was a connection
835 // error. http://crbug.com/295245
836 if (!connection_error) {
837 // We are in one of "done" states here.
838 UserManager::Get()->SaveUserOAuthStatus(
839 UserManager::Get()->GetLoggedInUser()->email(),
843 login_manager->RemoveObserver(this);
846 void LoginUtilsImpl::OnNewRefreshTokenAvaiable(Profile* user_profile) {
847 // Check if we were waiting to restart chrome.
848 if (!exit_after_session_restore_)
851 OAuth2LoginManager* login_manager =
852 OAuth2LoginManagerFactory::GetInstance()->GetForProfile(user_profile);
853 login_manager->RemoveObserver(this);
855 // Mark user auth token status as valid.
856 UserManager::Get()->SaveUserOAuthStatus(
857 UserManager::Get()->GetLoggedInUser()->email(),
858 User::OAUTH2_TOKEN_STATUS_VALID);
860 LOG(WARNING) << "Exiting after new refresh token fetched";
861 // We need to restart cleanly in this case to make sure OAuth2 RT is actually
863 chrome::AttemptRestart();
866 void LoginUtilsImpl::OnConnectionTypeChanged(
867 net::NetworkChangeNotifier::ConnectionType type) {
868 UserManager* user_manager = UserManager::Get();
869 if (type == net::NetworkChangeNotifier::CONNECTION_NONE ||
870 user_manager->IsLoggedInAsGuest() || !user_manager->IsUserLoggedIn()) {
874 // Need to iterate over all users and their OAuth2 session state.
875 const UserList& users = user_manager->GetLoggedInUsers();
876 for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) {
877 Profile* user_profile = user_manager->GetProfileByUser(*it);
878 bool should_restore_session =
879 pending_restore_sessions_.find((*it)->email()) !=
880 pending_restore_sessions_.end();
881 OAuth2LoginManager* login_manager =
882 OAuth2LoginManagerFactory::GetInstance()->GetForProfile(user_profile);
883 if (login_manager->state() ==
884 OAuth2LoginManager::SESSION_RESTORE_IN_PROGRESS) {
885 // If we come online for the first time after successful offline login,
886 // we need to kick off OAuth token verification process again.
887 login_manager->ContinueSessionRestore();
888 } else if (should_restore_session) {
889 pending_restore_sessions_.erase((*it)->email());
890 RestoreAuthSession(user_profile, has_web_auth_cookies_);
895 void LoginUtilsImpl::AttemptRestart(Profile* profile) {
896 if (session_restore_strategy_ !=
897 OAuth2LoginManager::RESTORE_FROM_COOKIE_JAR) {
898 chrome::AttemptRestart();
902 // We can't really quit if the session restore process that mints new
903 // refresh token is still in progress.
904 OAuth2LoginManager* login_manager =
905 OAuth2LoginManagerFactory::GetInstance()->GetForProfile(profile);
906 if (login_manager->state() !=
907 OAuth2LoginManager::SESSION_RESTORE_PREPARING &&
908 login_manager->state() !=
909 OAuth2LoginManager::SESSION_RESTORE_IN_PROGRESS) {
910 chrome::AttemptRestart();
914 LOG(WARNING) << "Attempting browser restart during session restore.";
915 exit_after_session_restore_ = true;
919 void LoginUtils::RegisterPrefs(PrefRegistrySimple* registry) {
920 registry->RegisterBooleanPref(prefs::kFactoryResetRequested, false);
921 registry->RegisterStringPref(prefs::kRLZBrand, std::string());
922 registry->RegisterBooleanPref(prefs::kRLZDisabled, false);
926 LoginUtils* LoginUtils::Get() {
927 return LoginUtilsWrapper::GetInstance()->get();
931 void LoginUtils::Set(LoginUtils* mock) {
932 LoginUtilsWrapper::GetInstance()->reset(mock);
936 bool LoginUtils::IsWhitelisted(const std::string& username,
937 bool* wildcard_match) {
938 // Skip whitelist check for tests.
939 if (CommandLine::ForCurrentProcess()->HasSwitch(
940 chromeos::switches::kOobeSkipPostLogin)) {
944 CrosSettings* cros_settings = CrosSettings::Get();
945 bool allow_new_user = false;
946 cros_settings->GetBoolean(kAccountsPrefAllowNewUser, &allow_new_user);
949 return cros_settings->FindEmailInList(
950 kAccountsPrefUsers, username, wildcard_match);
953 } // namespace chromeos