Disable view source for Developer Tools.
[chromium-blink-merge.git] / chrome / browser / chromeos / login / login_utils.cc
blobb0b104b5082b76f7b39d82c9318c53b228ad231c
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"
7 #include <algorithm>
8 #include <set>
9 #include <vector>
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/input_events_blocker.h"
41 #include "chrome/browser/chromeos/login/login_display_host.h"
42 #include "chrome/browser/chromeos/login/oauth2_login_manager.h"
43 #include "chrome/browser/chromeos/login/oauth2_login_manager_factory.h"
44 #include "chrome/browser/chromeos/login/parallel_authenticator.h"
45 #include "chrome/browser/chromeos/login/profile_auth_data.h"
46 #include "chrome/browser/chromeos/login/screen_locker.h"
47 #include "chrome/browser/chromeos/login/supervised_user_manager.h"
48 #include "chrome/browser/chromeos/login/user_manager.h"
49 #include "chrome/browser/chromeos/settings/cros_settings.h"
50 #include "chrome/browser/extensions/extension_service.h"
51 #include "chrome/browser/first_run/first_run.h"
52 #include "chrome/browser/google/google_util_chromeos.h"
53 #include "chrome/browser/lifetime/application_lifetime.h"
54 #include "chrome/browser/pref_service_flags_storage.h"
55 #include "chrome/browser/profiles/profile.h"
56 #include "chrome/browser/profiles/profile_manager.h"
57 #include "chrome/browser/rlz/rlz.h"
58 #include "chrome/browser/sync/profile_sync_service.h"
59 #include "chrome/browser/sync/profile_sync_service_factory.h"
60 #include "chrome/browser/ui/app_list/start_page_service.h"
61 #include "chrome/browser/ui/startup/startup_browser_creator.h"
62 #include "chrome/common/chrome_paths.h"
63 #include "chrome/common/chrome_switches.h"
64 #include "chrome/common/logging_chrome.h"
65 #include "chrome/common/pref_names.h"
66 #include "chromeos/chromeos_switches.h"
67 #include "chromeos/cryptohome/cryptohome_util.h"
68 #include "chromeos/dbus/cryptohome_client.h"
69 #include "chromeos/dbus/dbus_method_call_status.h"
70 #include "chromeos/dbus/dbus_thread_manager.h"
71 #include "chromeos/dbus/session_manager_client.h"
72 #include "chromeos/ime/input_method_manager.h"
73 #include "chromeos/settings/cros_settings_names.h"
74 #include "content/public/browser/browser_thread.h"
75 #include "content/public/browser/notification_service.h"
76 #include "google_apis/gaia/gaia_auth_consumer.h"
77 #include "net/base/network_change_notifier.h"
78 #include "net/url_request/url_request_context.h"
79 #include "net/url_request/url_request_context_getter.h"
80 #include "url/gurl.h"
82 using content::BrowserThread;
84 namespace chromeos {
86 namespace {
88 #if defined(ENABLE_RLZ)
89 // Flag file that disables RLZ tracking, when present.
90 const base::FilePath::CharType kRLZDisabledFlagName[] =
91 FILE_PATH_LITERAL(".rlz_disabled");
93 base::FilePath GetRlzDisabledFlagPath() {
94 return base::GetHomeDir().Append(kRLZDisabledFlagName);
96 #endif
98 } // namespace
100 struct DoBrowserLaunchOnLocaleLoadedData;
102 class LoginUtilsImpl
103 : public LoginUtils,
104 public OAuth2LoginManager::Observer,
105 public net::NetworkChangeNotifier::ConnectionTypeObserver,
106 public base::SupportsWeakPtr<LoginUtilsImpl> {
107 public:
108 LoginUtilsImpl()
109 : has_web_auth_cookies_(false),
110 delegate_(NULL),
111 exit_after_session_restore_(false),
112 session_restore_strategy_(
113 OAuth2LoginManager::RESTORE_FROM_SAVED_OAUTH2_REFRESH_TOKEN) {
114 net::NetworkChangeNotifier::AddConnectionTypeObserver(this);
117 virtual ~LoginUtilsImpl() {
118 net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
121 // LoginUtils implementation:
122 virtual void DoBrowserLaunch(Profile* profile,
123 LoginDisplayHost* login_host) OVERRIDE;
124 virtual void PrepareProfile(
125 const UserContext& user_context,
126 const std::string& display_email,
127 bool has_cookies,
128 bool has_active_session,
129 LoginUtils::Delegate* delegate) OVERRIDE;
130 virtual void DelegateDeleted(LoginUtils::Delegate* delegate) OVERRIDE;
131 virtual void CompleteOffTheRecordLogin(const GURL& start_url) OVERRIDE;
132 virtual void SetFirstLoginPrefs(PrefService* prefs) OVERRIDE;
133 virtual scoped_refptr<Authenticator> CreateAuthenticator(
134 LoginStatusConsumer* consumer) OVERRIDE;
135 virtual void RestoreAuthenticationSession(Profile* profile) OVERRIDE;
136 virtual void InitRlzDelayed(Profile* user_profile) OVERRIDE;
138 // OAuth2LoginManager::Observer overrides.
139 virtual void OnSessionRestoreStateChanged(
140 Profile* user_profile,
141 OAuth2LoginManager::SessionRestoreState state) OVERRIDE;
142 virtual void OnNewRefreshTokenAvaiable(Profile* user_profile) OVERRIDE;
144 // net::NetworkChangeNotifier::ConnectionTypeObserver overrides.
145 virtual void OnConnectionTypeChanged(
146 net::NetworkChangeNotifier::ConnectionType type) OVERRIDE;
148 private:
149 typedef std::set<std::string> SessionRestoreStateSet;
151 // DoBrowserLaunch is split into two parts.
152 // This one is called after anynchronous locale switch.
153 void DoBrowserLaunchOnLocaleLoadedImpl(Profile* profile,
154 LoginDisplayHost* login_host);
156 // Callback for locale_util::SwitchLanguage().
157 static void DoBrowserLaunchOnLocaleLoaded(
158 scoped_ptr<DoBrowserLaunchOnLocaleLoadedData> context,
159 const std::string& locale,
160 const std::string& loaded_locale,
161 const bool success);
163 // Restarts OAuth session authentication check.
164 void KickStartAuthentication(Profile* profile);
166 // Callback for Profile::CREATE_STATUS_CREATED profile state.
167 // Initializes basic preferences for newly created profile. Any other
168 // early profile initialization that needs to happen before
169 // ProfileManager::DoFinalInit() gets called is done here.
170 void InitProfilePreferences(Profile* user_profile,
171 const std::string& email);
173 // Callback for asynchronous profile creation.
174 void OnProfileCreated(const std::string& email,
175 Profile* profile,
176 Profile::CreateStatus status);
178 // Callback for Profile::CREATE_STATUS_INITIALIZED profile state.
179 // Profile is created, extensions and promo resources are initialized.
180 void UserProfileInitialized(Profile* user_profile);
182 // Callback to resume profile creation after transferring auth data from
183 // the authentication profile.
184 void CompleteProfileCreate(Profile* user_profile);
186 // Finalized profile preparation.
187 void FinalizePrepareProfile(Profile* user_profile);
189 // Initializes member variables needed for session restore process via
190 // OAuthLoginManager.
191 void InitSessionRestoreStrategy();
193 // Restores GAIA auth cookies for the created user profile from OAuth2 token.
194 void RestoreAuthSession(Profile* user_profile,
195 bool restore_from_auth_cookies);
197 // Initializes RLZ. If |disabled| is true, RLZ pings are disabled.
198 void InitRlz(Profile* user_profile, bool disabled);
200 // Attempts exiting browser process and esures this does not happen
201 // while we are still fetching new OAuth refresh tokens.
202 void AttemptExit(Profile* profile);
204 UserContext user_context_;
206 // True if the authentication profile's cookie jar should contain
207 // authentication cookies from the authentication extension log in flow.
208 bool has_web_auth_cookies_;
209 // Has to be scoped_refptr, see comment for CreateAuthenticator(...).
210 scoped_refptr<Authenticator> authenticator_;
212 // Delegate to be fired when the profile will be prepared.
213 LoginUtils::Delegate* delegate_;
215 // Set of user_id for those users that we should restore authentication
216 // session when notified about online state change.
217 SessionRestoreStateSet pending_restore_sessions_;
219 // True if we should restart chrome right after session restore.
220 bool exit_after_session_restore_;
222 // Sesion restore strategy.
223 OAuth2LoginManager::SessionRestoreStrategy session_restore_strategy_;
224 // OAuth2 refresh token for session restore.
225 std::string oauth2_refresh_token_;
227 DISALLOW_COPY_AND_ASSIGN(LoginUtilsImpl);
230 class LoginUtilsWrapper {
231 public:
232 static LoginUtilsWrapper* GetInstance() {
233 return Singleton<LoginUtilsWrapper>::get();
236 LoginUtils* get() {
237 base::AutoLock create(create_lock_);
238 if (!ptr_.get())
239 reset(new LoginUtilsImpl);
240 return ptr_.get();
243 void reset(LoginUtils* ptr) {
244 ptr_.reset(ptr);
247 private:
248 friend struct DefaultSingletonTraits<LoginUtilsWrapper>;
250 LoginUtilsWrapper() {}
252 base::Lock create_lock_;
253 scoped_ptr<LoginUtils> ptr_;
255 DISALLOW_COPY_AND_ASSIGN(LoginUtilsWrapper);
258 struct DoBrowserLaunchOnLocaleLoadedData {
259 DoBrowserLaunchOnLocaleLoadedData(LoginUtilsImpl* login_utils_impl,
260 Profile* profile,
261 LoginDisplayHost* display_host)
262 : login_utils_impl(login_utils_impl),
263 profile(profile),
264 display_host(display_host) {}
266 LoginUtilsImpl* login_utils_impl;
267 Profile* profile;
268 chromeos::LoginDisplayHost* display_host;
270 // Block UI events untill ResourceBundle is reloaded.
271 InputEventsBlocker input_events_blocker;
274 // static
275 void LoginUtilsImpl::DoBrowserLaunchOnLocaleLoaded(
276 scoped_ptr<DoBrowserLaunchOnLocaleLoadedData> context,
277 const std::string& /* locale */,
278 const std::string& /* loaded_locale */,
279 const bool /* success */) {
280 context->login_utils_impl->DoBrowserLaunchOnLocaleLoadedImpl(
281 context->profile, context->display_host);
284 // Called from DoBrowserLaunch() or from
285 // DoBrowserLaunchOnLocaleLoaded() depending on
286 // if locale switch was needed.
287 void LoginUtilsImpl::DoBrowserLaunchOnLocaleLoadedImpl(
288 Profile* profile,
289 LoginDisplayHost* login_host) {
290 if (!UserManager::Get()->GetCurrentUserFlow()->ShouldLaunchBrowser()) {
291 UserManager::Get()->GetCurrentUserFlow()->LaunchExtraSteps(profile);
292 return;
295 CommandLine user_flags(CommandLine::NO_PROGRAM);
296 about_flags::PrefServiceFlagsStorage flags_storage_(profile->GetPrefs());
297 about_flags::ConvertFlagsToSwitches(&flags_storage_, &user_flags,
298 about_flags::kAddSentinels);
299 // Only restart if needed and if not going into managed mode.
300 // Don't restart browser if it is not first profile in session.
301 if (UserManager::Get()->GetLoggedInUsers().size() == 1 &&
302 !UserManager::Get()->IsLoggedInAsLocallyManagedUser() &&
303 !about_flags::AreSwitchesIdenticalToCurrentCommandLine(
304 user_flags, *CommandLine::ForCurrentProcess())) {
305 CommandLine::StringVector flags;
306 // argv[0] is the program name |CommandLine::NO_PROGRAM|.
307 flags.assign(user_flags.argv().begin() + 1, user_flags.argv().end());
308 VLOG(1) << "Restarting to apply per-session flags...";
309 DBusThreadManager::Get()->GetSessionManagerClient()->SetFlagsForUser(
310 UserManager::Get()->GetActiveUser()->email(), flags);
311 AttemptExit(profile);
312 return;
315 if (login_host) {
316 login_host->SetStatusAreaVisible(true);
317 login_host->BeforeSessionStart();
320 BootTimesLoader::Get()->AddLoginTimeMarker("BrowserLaunched", false);
322 VLOG(1) << "Launching browser...";
323 StartupBrowserCreator browser_creator;
324 int return_code;
325 chrome::startup::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
326 chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;
328 browser_creator.LaunchBrowser(*CommandLine::ForCurrentProcess(),
329 profile,
330 base::FilePath(),
331 chrome::startup::IS_PROCESS_STARTUP,
332 first_run,
333 &return_code);
335 // Triggers app launcher start page service to load start page web contents.
336 app_list::StartPageService::Get(profile);
338 // Mark login host for deletion after browser starts. This
339 // guarantees that the message loop will be referenced by the
340 // browser before it is dereferenced by the login host.
341 if (login_host)
342 login_host->Finalize();
343 UserManager::Get()->SessionStarted();
346 void LoginUtilsImpl::DoBrowserLaunch(Profile* profile,
347 LoginDisplayHost* login_host) {
348 if (browser_shutdown::IsTryingToQuit())
349 return;
351 User* const user = UserManager::Get()->GetUserByProfile(profile);
352 scoped_ptr<DoBrowserLaunchOnLocaleLoadedData> data(
353 new DoBrowserLaunchOnLocaleLoadedData(this, profile, login_host));
355 scoped_ptr<locale_util::SwitchLanguageCallback> callback(
356 new locale_util::SwitchLanguageCallback(
357 base::Bind(&LoginUtilsImpl::DoBrowserLaunchOnLocaleLoaded,
358 base::Passed(data.Pass()))));
359 if (!UserManager::Get()->
360 RespectLocalePreference(profile, user, callback.Pass())) {
361 DoBrowserLaunchOnLocaleLoadedImpl(profile, login_host);
365 void LoginUtilsImpl::PrepareProfile(
366 const UserContext& user_context,
367 const std::string& display_email,
368 bool has_cookies,
369 bool has_active_session,
370 LoginUtils::Delegate* delegate) {
371 BootTimesLoader* btl = BootTimesLoader::Get();
373 VLOG(1) << "Completing login for " << user_context.username;
375 if (!has_active_session) {
376 btl->AddLoginTimeMarker("StartSession-Start", false);
377 DBusThreadManager::Get()->GetSessionManagerClient()->StartSession(
378 user_context.username);
379 btl->AddLoginTimeMarker("StartSession-End", false);
382 btl->AddLoginTimeMarker("UserLoggedIn-Start", false);
383 UserManager* user_manager = UserManager::Get();
384 user_manager->UserLoggedIn(user_context.username,
385 user_context.username_hash,
386 false);
387 btl->AddLoginTimeMarker("UserLoggedIn-End", false);
389 // Switch log file as soon as possible.
390 if (base::SysInfo::IsRunningOnChromeOS())
391 logging::RedirectChromeLogging(*(CommandLine::ForCurrentProcess()));
393 // Update user's displayed email.
394 if (!display_email.empty())
395 user_manager->SaveUserDisplayEmail(user_context.username, display_email);
397 user_context_ = user_context;
399 has_web_auth_cookies_ = has_cookies;
400 delegate_ = delegate;
401 InitSessionRestoreStrategy();
403 // Can't use display_email because it is empty when existing user logs in
404 // using sing-in pod on login screen (i.e. user didn't type email).
405 g_browser_process->profile_manager()->CreateProfileAsync(
406 user_manager->GetUserProfileDir(user_context.username),
407 base::Bind(&LoginUtilsImpl::OnProfileCreated, AsWeakPtr(),
408 user_context.username),
409 base::string16(), base::string16(), std::string());
412 void LoginUtilsImpl::DelegateDeleted(LoginUtils::Delegate* delegate) {
413 if (delegate_ == delegate)
414 delegate_ = NULL;
417 void LoginUtilsImpl::InitProfilePreferences(Profile* user_profile,
418 const std::string& user_id) {
419 if (UserManager::Get()->IsCurrentUserNew())
420 SetFirstLoginPrefs(user_profile->GetPrefs());
422 if (UserManager::Get()->IsLoggedInAsLocallyManagedUser()) {
423 User* active_user = UserManager::Get()->GetActiveUser();
424 std::string managed_user_sync_id =
425 UserManager::Get()->GetSupervisedUserManager()->
426 GetUserSyncId(active_user->email());
428 // TODO(ibraaaa): Remove that when 97% of our users are using M31.
429 // http://crbug.com/276163
430 if (managed_user_sync_id.empty())
431 managed_user_sync_id = "DUMMY_ID";
433 user_profile->GetPrefs()->SetString(prefs::kManagedUserId,
434 managed_user_sync_id);
435 } else {
436 // Make sure that the google service username is properly set (we do this
437 // on every sign in, not just the first login, to deal with existing
438 // profiles that might not have it set yet).
439 StringPrefMember google_services_username;
440 google_services_username.Init(prefs::kGoogleServicesUsername,
441 user_profile->GetPrefs());
442 google_services_username.SetValue(user_id);
446 void LoginUtilsImpl::InitSessionRestoreStrategy() {
447 CommandLine* command_line = CommandLine::ForCurrentProcess();
448 bool in_app_mode = chrome::IsRunningInForcedAppMode();
450 // Are we in kiosk app mode?
451 if (in_app_mode) {
452 if (command_line->HasSwitch(::switches::kAppModeOAuth2Token)) {
453 oauth2_refresh_token_ = command_line->GetSwitchValueASCII(
454 ::switches::kAppModeOAuth2Token);
457 if (command_line->HasSwitch(::switches::kAppModeAuthCode)) {
458 user_context_.auth_code = command_line->GetSwitchValueASCII(
459 ::switches::kAppModeAuthCode);
462 DCHECK(!has_web_auth_cookies_);
463 if (!user_context_.auth_code.empty()) {
464 session_restore_strategy_ = OAuth2LoginManager::RESTORE_FROM_AUTH_CODE;
465 } else if (!oauth2_refresh_token_.empty()) {
466 session_restore_strategy_ =
467 OAuth2LoginManager::RESTORE_FROM_PASSED_OAUTH2_REFRESH_TOKEN;
468 } else {
469 session_restore_strategy_ =
470 OAuth2LoginManager::RESTORE_FROM_SAVED_OAUTH2_REFRESH_TOKEN;
472 return;
475 if (has_web_auth_cookies_) {
476 session_restore_strategy_ = OAuth2LoginManager::RESTORE_FROM_COOKIE_JAR;
477 } else if (!user_context_.auth_code.empty()) {
478 session_restore_strategy_ = OAuth2LoginManager::RESTORE_FROM_AUTH_CODE;
479 } else {
480 session_restore_strategy_ =
481 OAuth2LoginManager::RESTORE_FROM_SAVED_OAUTH2_REFRESH_TOKEN;
486 void LoginUtilsImpl::OnProfileCreated(
487 const std::string& user_id,
488 Profile* user_profile,
489 Profile::CreateStatus status) {
490 CHECK(user_profile);
492 switch (status) {
493 case Profile::CREATE_STATUS_CREATED:
494 InitProfilePreferences(user_profile, user_id);
495 break;
496 case Profile::CREATE_STATUS_INITIALIZED:
497 UserProfileInitialized(user_profile);
498 break;
499 case Profile::CREATE_STATUS_LOCAL_FAIL:
500 case Profile::CREATE_STATUS_REMOTE_FAIL:
501 case Profile::CREATE_STATUS_CANCELED:
502 case Profile::MAX_CREATE_STATUS:
503 NOTREACHED();
504 break;
508 void LoginUtilsImpl::UserProfileInitialized(Profile* user_profile) {
509 BootTimesLoader* btl = BootTimesLoader::Get();
510 btl->AddLoginTimeMarker("UserProfileGotten", false);
512 if (user_context_.using_oauth) {
513 // Transfer proxy authentication cache, cookies (optionally) and server
514 // bound certs from the profile that was used for authentication. This
515 // profile contains cookies that auth extension should have already put in
516 // place that will ensure that the newly created session is authenticated
517 // for the websites that work with the used authentication schema.
518 ProfileAuthData::Transfer(authenticator_->authentication_profile(),
519 user_profile,
520 has_web_auth_cookies_, // transfer_cookies
521 base::Bind(
522 &LoginUtilsImpl::CompleteProfileCreate,
523 AsWeakPtr(),
524 user_profile));
525 return;
528 FinalizePrepareProfile(user_profile);
531 void LoginUtilsImpl::CompleteProfileCreate(Profile* user_profile) {
532 RestoreAuthSession(user_profile, has_web_auth_cookies_);
533 FinalizePrepareProfile(user_profile);
536 void LoginUtilsImpl::RestoreAuthSession(Profile* user_profile,
537 bool restore_from_auth_cookies) {
538 CHECK((authenticator_.get() && authenticator_->authentication_profile()) ||
539 !restore_from_auth_cookies);
541 if (chrome::IsRunningInForcedAppMode() ||
542 CommandLine::ForCurrentProcess()->HasSwitch(
543 chromeos::switches::kOobeSkipPostLogin)) {
544 return;
547 exit_after_session_restore_ = false;
548 // Remove legacy OAuth1 token if we have one. If it's valid, we should already
549 // have OAuth2 refresh token in OAuth2TokenService that could be used to
550 // retrieve all other tokens and user_context.
551 OAuth2LoginManager* login_manager =
552 OAuth2LoginManagerFactory::GetInstance()->GetForProfile(user_profile);
553 login_manager->AddObserver(this);
554 login_manager->RestoreSession(
555 authenticator_.get() && authenticator_->authentication_profile()
556 ? authenticator_->authentication_profile()->GetRequestContext()
557 : NULL,
558 session_restore_strategy_,
559 oauth2_refresh_token_,
560 user_context_.auth_code);
563 void LoginUtilsImpl::FinalizePrepareProfile(Profile* user_profile) {
564 BootTimesLoader* btl = BootTimesLoader::Get();
565 // Own TPM device if, for any reason, it has not been done in EULA
566 // wizard screen.
567 CryptohomeClient* client = DBusThreadManager::Get()->GetCryptohomeClient();
568 btl->AddLoginTimeMarker("TPMOwn-Start", false);
569 if (cryptohome_util::TpmIsEnabled() && !cryptohome_util::TpmIsBeingOwned()) {
570 if (cryptohome_util::TpmIsOwned()) {
571 client->CallTpmClearStoredPasswordAndBlock();
572 } else {
573 client->TpmCanAttemptOwnership(EmptyVoidDBusMethodCallback());
576 btl->AddLoginTimeMarker("TPMOwn-End", false);
578 user_profile->OnLogin();
580 // Send the notification before creating the browser so additional objects
581 // that need the profile (e.g. the launcher) can be created first.
582 content::NotificationService::current()->Notify(
583 chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED,
584 content::NotificationService::AllSources(),
585 content::Details<Profile>(user_profile));
587 // Initialize RLZ only for primary user.
588 if (UserManager::Get()->GetPrimaryUser() ==
589 UserManager::Get()->GetUserByProfile(user_profile)) {
590 InitRlzDelayed(user_profile);
592 // TODO(altimofeev): This pointer should probably never be NULL, but it looks
593 // like LoginUtilsImpl::OnProfileCreated() may be getting called before
594 // LoginUtilsImpl::PrepareProfile() has set |delegate_| when Chrome is killed
595 // during shutdown in tests -- see http://crosbug.com/18269. Replace this
596 // 'if' statement with a CHECK(delegate_) once the underlying issue is
597 // resolved.
598 if (delegate_)
599 delegate_->OnProfilePrepared(user_profile);
602 void LoginUtilsImpl::InitRlzDelayed(Profile* user_profile) {
603 #if defined(ENABLE_RLZ)
604 if (!g_browser_process->local_state()->HasPrefPath(prefs::kRLZBrand)) {
605 // Read brand code asynchronously from an OEM file and repost ourselves.
606 google_util::chromeos::SetBrandFromFile(
607 base::Bind(&LoginUtilsImpl::InitRlzDelayed, AsWeakPtr(), user_profile));
608 return;
610 base::PostTaskAndReplyWithResult(
611 base::WorkerPool::GetTaskRunner(false),
612 FROM_HERE,
613 base::Bind(&base::PathExists, GetRlzDisabledFlagPath()),
614 base::Bind(&LoginUtilsImpl::InitRlz, AsWeakPtr(), user_profile));
615 #endif
618 void LoginUtilsImpl::InitRlz(Profile* user_profile, bool disabled) {
619 #if defined(ENABLE_RLZ)
620 PrefService* local_state = g_browser_process->local_state();
621 if (disabled) {
622 // Empty brand code means an organic install (no RLZ pings are sent).
623 google_util::chromeos::ClearBrandForCurrentSession();
625 if (disabled != local_state->GetBoolean(prefs::kRLZDisabled)) {
626 // When switching to RLZ enabled/disabled state, clear all recorded events.
627 RLZTracker::ClearRlzState();
628 local_state->SetBoolean(prefs::kRLZDisabled, disabled);
630 // Init the RLZ library.
631 int ping_delay = user_profile->GetPrefs()->GetInteger(
632 first_run::GetPingDelayPrefName().c_str());
633 // Negative ping delay means to send ping immediately after a first search is
634 // recorded.
635 RLZTracker::InitRlzFromProfileDelayed(
636 user_profile, UserManager::Get()->IsCurrentUserNew(),
637 ping_delay < 0, base::TimeDelta::FromMilliseconds(abs(ping_delay)));
638 if (delegate_)
639 delegate_->OnRlzInitialized(user_profile);
640 #endif
643 void LoginUtilsImpl::CompleteOffTheRecordLogin(const GURL& start_url) {
644 VLOG(1) << "Completing incognito login";
646 // For guest session we ask session manager to restart Chrome with --bwsi
647 // flag. We keep only some of the arguments of this process.
648 const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
649 CommandLine command_line(browser_command_line.GetProgram());
650 std::string cmd_line_str = GetOffTheRecordCommandLine(start_url,
651 browser_command_line,
652 &command_line);
654 RestartChrome(cmd_line_str);
657 void LoginUtilsImpl::SetFirstLoginPrefs(PrefService* prefs) {
658 VLOG(1) << "Setting first login prefs";
659 BootTimesLoader* btl = BootTimesLoader::Get();
660 std::string locale = g_browser_process->GetApplicationLocale();
662 // First, we'll set kLanguagePreloadEngines.
663 input_method::InputMethodManager* manager =
664 input_method::InputMethodManager::Get();
665 std::vector<std::string> input_method_ids;
666 manager->GetInputMethodUtil()->GetFirstLoginInputMethodIds(
667 locale, manager->GetCurrentInputMethod(), &input_method_ids);
668 // Save the input methods in the user's preferences.
669 StringPrefMember language_preload_engines;
670 language_preload_engines.Init(prefs::kLanguagePreloadEngines,
671 prefs);
672 language_preload_engines.SetValue(JoinString(input_method_ids, ','));
673 btl->AddLoginTimeMarker("IMEStarted", false);
675 // Second, we'll set kLanguagePreferredLanguages.
676 std::vector<std::string> language_codes;
677 // The current locale should be on the top.
678 language_codes.push_back(locale);
680 // Add input method IDs based on the input methods, as there may be
681 // input methods that are unrelated to the current locale. Example: the
682 // hardware keyboard layout xkb:us::eng is used for logging in, but the
683 // UI language is set to French. In this case, we should set "fr,en"
684 // to the preferred languages preference.
685 std::vector<std::string> candidates;
686 manager->GetInputMethodUtil()->GetLanguageCodesFromInputMethodIds(
687 input_method_ids, &candidates);
688 for (size_t i = 0; i < candidates.size(); ++i) {
689 const std::string& candidate = candidates[i];
690 // Skip if it's already in language_codes.
691 if (std::count(language_codes.begin(), language_codes.end(),
692 candidate) == 0) {
693 language_codes.push_back(candidate);
696 // Save the preferred languages in the user's preferences.
697 StringPrefMember language_preferred_languages;
698 language_preferred_languages.Init(prefs::kLanguagePreferredLanguages,
699 prefs);
700 language_preferred_languages.SetValue(JoinString(language_codes, ','));
703 scoped_refptr<Authenticator> LoginUtilsImpl::CreateAuthenticator(
704 LoginStatusConsumer* consumer) {
705 // Screen locker needs new Authenticator instance each time.
706 if (ScreenLocker::default_screen_locker()) {
707 if (authenticator_.get())
708 authenticator_->SetConsumer(NULL);
709 authenticator_ = NULL;
712 if (authenticator_.get() == NULL) {
713 authenticator_ = new ParallelAuthenticator(consumer);
714 } else {
715 // TODO(nkostylev): Fix this hack by improving Authenticator dependencies.
716 authenticator_->SetConsumer(consumer);
718 return authenticator_;
721 void LoginUtilsImpl::RestoreAuthenticationSession(Profile* user_profile) {
722 UserManager* user_manager = UserManager::Get();
723 // We don't need to restore session for demo/guest/stub/public account users.
724 if (!user_manager->IsUserLoggedIn() ||
725 user_manager->IsLoggedInAsGuest() ||
726 user_manager->IsLoggedInAsPublicAccount() ||
727 user_manager->IsLoggedInAsDemoUser() ||
728 user_manager->IsLoggedInAsStub()) {
729 return;
732 User* user = user_manager->GetUserByProfile(user_profile);
733 DCHECK(user);
734 if (!net::NetworkChangeNotifier::IsOffline()) {
735 pending_restore_sessions_.erase(user->email());
736 RestoreAuthSession(user_profile, false);
737 } else {
738 // Even if we're online we should wait till initial
739 // OnConnectionTypeChanged() call. Otherwise starting fetchers too early may
740 // end up canceling all request when initial network connection type is
741 // processed. See http://crbug.com/121643.
742 pending_restore_sessions_.insert(user->email());
746 void LoginUtilsImpl::OnSessionRestoreStateChanged(
747 Profile* user_profile,
748 OAuth2LoginManager::SessionRestoreState state) {
749 User::OAuthTokenStatus user_status = User::OAUTH_TOKEN_STATUS_UNKNOWN;
750 OAuth2LoginManager* login_manager =
751 OAuth2LoginManagerFactory::GetInstance()->GetForProfile(user_profile);
753 bool connection_error = false;
754 switch (state) {
755 case OAuth2LoginManager::SESSION_RESTORE_DONE:
756 user_status = User::OAUTH2_TOKEN_STATUS_VALID;
757 break;
758 case OAuth2LoginManager::SESSION_RESTORE_FAILED:
759 user_status = User::OAUTH2_TOKEN_STATUS_INVALID;
760 break;
761 case OAuth2LoginManager::SESSION_RESTORE_CONNECTION_FAILED:
762 connection_error = true;
763 break;
764 case OAuth2LoginManager::SESSION_RESTORE_NOT_STARTED:
765 case OAuth2LoginManager::SESSION_RESTORE_PREPARING:
766 case OAuth2LoginManager::SESSION_RESTORE_IN_PROGRESS:
767 return;
770 // We should not be clearing existing token state if that was a connection
771 // error. http://crbug.com/295245
772 if (!connection_error) {
773 // We are in one of "done" states here.
774 UserManager::Get()->SaveUserOAuthStatus(
775 UserManager::Get()->GetLoggedInUser()->email(),
776 user_status);
779 login_manager->RemoveObserver(this);
782 void LoginUtilsImpl::OnNewRefreshTokenAvaiable(Profile* user_profile) {
783 // Check if we were waiting to restart chrome.
784 if (!exit_after_session_restore_)
785 return;
787 OAuth2LoginManager* login_manager =
788 OAuth2LoginManagerFactory::GetInstance()->GetForProfile(user_profile);
789 login_manager->RemoveObserver(this);
791 // Mark user auth token status as valid.
792 UserManager::Get()->SaveUserOAuthStatus(
793 UserManager::Get()->GetLoggedInUser()->email(),
794 User::OAUTH2_TOKEN_STATUS_VALID);
796 LOG(WARNING) << "Exiting after new refresh token fetched";
797 // We need to exit cleanly in this case to make sure OAuth2 RT is actually
798 // saved.
799 chrome::ExitCleanly();
802 void LoginUtilsImpl::OnConnectionTypeChanged(
803 net::NetworkChangeNotifier::ConnectionType type) {
804 UserManager* user_manager = UserManager::Get();
805 if (type == net::NetworkChangeNotifier::CONNECTION_NONE ||
806 user_manager->IsLoggedInAsGuest() || !user_manager->IsUserLoggedIn()) {
807 return;
810 // Need to iterate over all users and their OAuth2 session state.
811 const UserList& users = user_manager->GetLoggedInUsers();
812 for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) {
813 Profile* user_profile = user_manager->GetProfileByUser(*it);
814 bool should_restore_session =
815 pending_restore_sessions_.find((*it)->email()) !=
816 pending_restore_sessions_.end();
817 OAuth2LoginManager* login_manager =
818 OAuth2LoginManagerFactory::GetInstance()->GetForProfile(user_profile);
819 if (login_manager->state() ==
820 OAuth2LoginManager::SESSION_RESTORE_IN_PROGRESS) {
821 // If we come online for the first time after successful offline login,
822 // we need to kick off OAuth token verification process again.
823 login_manager->ContinueSessionRestore();
824 } else if (should_restore_session) {
825 pending_restore_sessions_.erase((*it)->email());
826 RestoreAuthSession(user_profile, has_web_auth_cookies_);
831 void LoginUtilsImpl::AttemptExit(Profile* profile) {
832 if (session_restore_strategy_ !=
833 OAuth2LoginManager::RESTORE_FROM_COOKIE_JAR) {
834 chrome::AttemptExit();
835 return;
838 // We can't really quit if the session restore process that mints new
839 // refresh token is still in progress.
840 OAuth2LoginManager* login_manager =
841 OAuth2LoginManagerFactory::GetInstance()->GetForProfile(profile);
842 if (login_manager->state() !=
843 OAuth2LoginManager::SESSION_RESTORE_PREPARING &&
844 login_manager->state() !=
845 OAuth2LoginManager::SESSION_RESTORE_IN_PROGRESS) {
846 chrome::AttemptExit();
847 return;
850 LOG(WARNING) << "Attempting browser restart during session restore.";
851 exit_after_session_restore_ = true;
854 // static
855 void LoginUtils::RegisterPrefs(PrefRegistrySimple* registry) {
856 registry->RegisterBooleanPref(prefs::kFactoryResetRequested, false);
857 registry->RegisterStringPref(prefs::kRLZBrand, std::string());
858 registry->RegisterBooleanPref(prefs::kRLZDisabled, false);
861 // static
862 LoginUtils* LoginUtils::Get() {
863 return LoginUtilsWrapper::GetInstance()->get();
866 // static
867 void LoginUtils::Set(LoginUtils* mock) {
868 LoginUtilsWrapper::GetInstance()->reset(mock);
871 // static
872 bool LoginUtils::IsWhitelisted(const std::string& username) {
873 // Skip whitelist check for tests.
874 if (CommandLine::ForCurrentProcess()->HasSwitch(
875 chromeos::switches::kOobeSkipPostLogin)) {
876 return true;
879 CrosSettings* cros_settings = CrosSettings::Get();
880 bool allow_new_user = false;
881 cros_settings->GetBoolean(kAccountsPrefAllowNewUser, &allow_new_user);
882 if (allow_new_user)
883 return true;
884 return cros_settings->FindEmailInList(kAccountsPrefUsers, username);
887 } // namespace chromeos