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"
10 #include "base/chromeos/chromeos_version.h"
11 #include "base/command_line.h"
12 #include "base/compiler_specific.h"
13 #include "base/file_util.h"
14 #include "base/files/file_path.h"
15 #include "base/location.h"
16 #include "base/memory/ref_counted.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/memory/singleton.h"
19 #include "base/memory/weak_ptr.h"
20 #include "base/path_service.h"
21 #include "base/prefs/pref_member.h"
22 #include "base/prefs/pref_registry_simple.h"
23 #include "base/prefs/pref_service.h"
24 #include "base/strings/string_util.h"
25 #include "base/strings/utf_string_conversions.h"
26 #include "base/synchronization/lock.h"
27 #include "base/task_runner_util.h"
28 #include "base/threading/worker_pool.h"
29 #include "base/time/time.h"
30 #include "chrome/browser/about_flags.h"
31 #include "chrome/browser/app_mode/app_mode_utils.h"
32 #include "chrome/browser/browser_process.h"
33 #include "chrome/browser/browser_shutdown.h"
34 #include "chrome/browser/chrome_notification_types.h"
35 #include "chrome/browser/chromeos/boot_times_loader.h"
36 #include "chrome/browser/chromeos/input_method/input_method_util.h"
37 #include "chrome/browser/chromeos/login/chrome_restart_request.h"
38 #include "chrome/browser/chromeos/login/language_switch_menu.h"
39 #include "chrome/browser/chromeos/login/login_display_host.h"
40 #include "chrome/browser/chromeos/login/oauth2_login_manager.h"
41 #include "chrome/browser/chromeos/login/oauth2_login_manager_factory.h"
42 #include "chrome/browser/chromeos/login/parallel_authenticator.h"
43 #include "chrome/browser/chromeos/login/profile_auth_data.h"
44 #include "chrome/browser/chromeos/login/screen_locker.h"
45 #include "chrome/browser/chromeos/login/user_manager.h"
46 #include "chrome/browser/chromeos/settings/cros_settings.h"
47 #include "chrome/browser/chromeos/settings/cros_settings_names.h"
48 #include "chrome/browser/extensions/extension_service.h"
49 #include "chrome/browser/first_run/first_run.h"
50 #include "chrome/browser/google/google_util_chromeos.h"
51 #include "chrome/browser/lifetime/application_lifetime.h"
52 #include "chrome/browser/pref_service_flags_storage.h"
53 #include "chrome/browser/profiles/profile.h"
54 #include "chrome/browser/profiles/profile_manager.h"
55 #include "chrome/browser/rlz/rlz.h"
56 #include "chrome/browser/signin/signin_manager.h"
57 #include "chrome/browser/signin/signin_manager_factory.h"
58 #include "chrome/browser/signin/token_service.h"
59 #include "chrome/browser/signin/token_service_factory.h"
60 #include "chrome/browser/sync/profile_sync_service.h"
61 #include "chrome/browser/sync/profile_sync_service_factory.h"
62 #include "chrome/browser/ui/startup/startup_browser_creator.h"
63 #include "chrome/common/chrome_paths.h"
64 #include "chrome/common/chrome_switches.h"
65 #include "chrome/common/logging_chrome.h"
66 #include "chrome/common/pref_names.h"
67 #include "chromeos/chromeos_switches.h"
68 #include "chromeos/cryptohome/cryptohome_library.h"
69 #include "chromeos/dbus/dbus_thread_manager.h"
70 #include "chromeos/dbus/session_manager_client.h"
71 #include "chromeos/ime/input_method_manager.h"
72 #include "content/public/browser/browser_thread.h"
73 #include "content/public/browser/notification_service.h"
74 #include "google_apis/gaia/gaia_auth_consumer.h"
75 #include "net/base/network_change_notifier.h"
76 #include "net/url_request/url_request_context.h"
77 #include "net/url_request/url_request_context_getter.h"
80 using content::BrowserThread
;
86 #if defined(ENABLE_RLZ)
87 // Flag file that disables RLZ tracking, when present.
88 const base::FilePath::CharType kRLZDisabledFlagName
[] =
89 FILE_PATH_LITERAL(".rlz_disabled");
91 base::FilePath
GetRlzDisabledFlagPath() {
92 return file_util::GetHomeDir().Append(kRLZDisabledFlagName
);
100 public OAuth2LoginManager::Observer
,
101 public net::NetworkChangeNotifier::ConnectionTypeObserver
,
102 public base::SupportsWeakPtr
<LoginUtilsImpl
> {
105 : using_oauth_(false),
106 has_web_auth_cookies_(false),
108 should_restore_auth_session_(false),
109 session_restore_strategy_(
110 OAuth2LoginManager::RESTORE_FROM_SAVED_OAUTH2_REFRESH_TOKEN
) {
111 net::NetworkChangeNotifier::AddConnectionTypeObserver(this);
114 virtual ~LoginUtilsImpl() {
115 net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
118 // LoginUtils implementation:
119 virtual void DoBrowserLaunch(Profile
* profile
,
120 LoginDisplayHost
* login_host
) OVERRIDE
;
121 virtual void PrepareProfile(
122 const UserContext
& user_context
,
123 const std::string
& display_email
,
126 bool has_active_session
,
127 LoginUtils::Delegate
* delegate
) OVERRIDE
;
128 virtual void DelegateDeleted(LoginUtils::Delegate
* delegate
) OVERRIDE
;
129 virtual void CompleteOffTheRecordLogin(const GURL
& start_url
) OVERRIDE
;
130 virtual void SetFirstLoginPrefs(PrefService
* prefs
) OVERRIDE
;
131 virtual scoped_refptr
<Authenticator
> CreateAuthenticator(
132 LoginStatusConsumer
* consumer
) OVERRIDE
;
133 virtual void RestoreAuthenticationSession(Profile
* profile
) OVERRIDE
;
134 virtual void InitRlzDelayed(Profile
* user_profile
) OVERRIDE
;
136 // OAuth2LoginManager::Delegate overrides.
137 virtual void OnSessionRestoreStateChanged(
138 Profile
* user_profile
,
139 OAuth2LoginManager::SessionRestoreState state
) OVERRIDE
;
140 virtual void OnSessionAuthenticated(Profile
* user_profile
) OVERRIDE
;
142 // net::NetworkChangeNotifier::ConnectionTypeObserver overrides.
143 virtual void OnConnectionTypeChanged(
144 net::NetworkChangeNotifier::ConnectionType type
) OVERRIDE
;
147 // Restarts OAuth session authentication check.
148 void KickStartAuthentication(Profile
* profile
);
150 // Check user's profile for kApplicationLocale setting.
151 void RespectLocalePreference(Profile
* pref
);
153 // Callback for Profile::CREATE_STATUS_CREATED profile state.
154 // Initializes basic preferences for newly created profile. Any other
155 // early profile initialization that needs to happen before
156 // ProfileManager::DoFinalInit() gets called is done here.
157 void InitProfilePreferences(Profile
* user_profile
,
158 const std::string
& email
);
160 // Callback for asynchronous profile creation.
161 void OnProfileCreated(const std::string
& email
,
163 Profile::CreateStatus status
);
165 // Callback for Profile::CREATE_STATUS_INITIALIZED profile state.
166 // Profile is created, extensions and promo resources are initialized.
167 void UserProfileInitialized(Profile
* user_profile
);
169 // Callback to resume profile creation after transferring auth data from
170 // the authentication profile.
171 void CompleteProfileCreate(Profile
* user_profile
);
173 // Finalized profile preparation.
174 void FinalizePrepareProfile(Profile
* user_profile
);
176 // Initializes member variables needed for session restore process via
177 // OAuthLoginManager.
178 void InitSessionRestoreStrategy();
180 // Restores GAIA auth cookies for the created user profile from OAuth2 token.
181 void RestoreAuthSession(Profile
* user_profile
,
182 bool restore_from_auth_cookies
);
184 // Initializes RLZ. If |disabled| is true, RLZ pings are disabled.
185 void InitRlz(Profile
* user_profile
, bool disabled
);
187 // Starts signing related services. Initiates TokenService token retrieval.
188 void StartSignedInServices(Profile
* profile
);
190 UserContext user_context_
;
193 // True if the authentication profile's cookie jar should contain
194 // authentication cookies from the authentication extension log in flow.
195 bool has_web_auth_cookies_
;
196 // Has to be scoped_refptr, see comment for CreateAuthenticator(...).
197 scoped_refptr
<Authenticator
> authenticator_
;
199 // Delegate to be fired when the profile will be prepared.
200 LoginUtils::Delegate
* delegate_
;
202 // True if should restore authentication session when notified about
203 // online state change.
204 bool should_restore_auth_session_
;
206 // Sesion restore strategy.
207 OAuth2LoginManager::SessionRestoreStrategy session_restore_strategy_
;
208 // OAuth2 refresh token for session restore.
209 std::string oauth2_refresh_token_
;
211 DISALLOW_COPY_AND_ASSIGN(LoginUtilsImpl
);
214 class LoginUtilsWrapper
{
216 static LoginUtilsWrapper
* GetInstance() {
217 return Singleton
<LoginUtilsWrapper
>::get();
221 base::AutoLock
create(create_lock_
);
223 reset(new LoginUtilsImpl
);
227 void reset(LoginUtils
* ptr
) {
232 friend struct DefaultSingletonTraits
<LoginUtilsWrapper
>;
234 LoginUtilsWrapper() {}
236 base::Lock create_lock_
;
237 scoped_ptr
<LoginUtils
> ptr_
;
239 DISALLOW_COPY_AND_ASSIGN(LoginUtilsWrapper
);
242 void LoginUtilsImpl::DoBrowserLaunch(Profile
* profile
,
243 LoginDisplayHost
* login_host
) {
244 if (browser_shutdown::IsTryingToQuit())
247 if (!UserManager::Get()->GetCurrentUserFlow()->ShouldLaunchBrowser()) {
248 UserManager::Get()->GetCurrentUserFlow()->LaunchExtraSteps(profile
);
252 CommandLine
user_flags(CommandLine::NO_PROGRAM
);
253 about_flags::PrefServiceFlagsStorage
flags_storage_(profile
->GetPrefs());
254 about_flags::ConvertFlagsToSwitches(&flags_storage_
, &user_flags
);
255 // Only restart if needed and if not going into managed mode.
256 // Don't restart browser if it is not first profile in session.
257 if (UserManager::Get()->GetLoggedInUsers().size() == 1 &&
258 !UserManager::Get()->IsLoggedInAsLocallyManagedUser() &&
259 !about_flags::AreSwitchesIdenticalToCurrentCommandLine(
260 user_flags
, *CommandLine::ForCurrentProcess())) {
261 CommandLine::StringVector flags
;
262 // argv[0] is the program name |CommandLine::NO_PROGRAM|.
263 flags
.assign(user_flags
.argv().begin() + 1, user_flags
.argv().end());
264 VLOG(1) << "Restarting to apply per-session flags...";
265 DBusThreadManager::Get()->GetSessionManagerClient()->SetFlagsForUser(
266 UserManager::Get()->GetActiveUser()->email(), flags
);
267 chrome::ExitCleanly();
272 login_host
->SetStatusAreaVisible(true);
273 login_host
->BeforeSessionStart();
276 BootTimesLoader::Get()->AddLoginTimeMarker("BrowserLaunched", false);
278 VLOG(1) << "Launching browser...";
279 StartupBrowserCreator browser_creator
;
281 chrome::startup::IsFirstRun first_run
= first_run::IsChromeFirstRun() ?
282 chrome::startup::IS_FIRST_RUN
: chrome::startup::IS_NOT_FIRST_RUN
;
284 browser_creator
.LaunchBrowser(*CommandLine::ForCurrentProcess(),
287 chrome::startup::IS_PROCESS_STARTUP
,
291 // Mark login host for deletion after browser starts. This
292 // guarantees that the message loop will be referenced by the
293 // browser before it is dereferenced by the login host.
295 login_host
->Finalize();
296 UserManager::Get()->SessionStarted();
299 void LoginUtilsImpl::PrepareProfile(
300 const UserContext
& user_context
,
301 const std::string
& display_email
,
304 bool has_active_session
,
305 LoginUtils::Delegate
* delegate
) {
306 BootTimesLoader
* btl
= BootTimesLoader::Get();
308 VLOG(1) << "Completing login for " << user_context
.username
;
310 if (!has_active_session
) {
311 btl
->AddLoginTimeMarker("StartSession-Start", false);
312 DBusThreadManager::Get()->GetSessionManagerClient()->StartSession(
313 user_context
.username
);
314 btl
->AddLoginTimeMarker("StartSession-End", false);
317 btl
->AddLoginTimeMarker("UserLoggedIn-Start", false);
318 UserManager
* user_manager
= UserManager::Get();
319 user_manager
->UserLoggedIn(user_context
.username
,
320 user_context
.username_hash
,
322 btl
->AddLoginTimeMarker("UserLoggedIn-End", false);
324 // Switch log file as soon as possible.
325 if (base::chromeos::IsRunningOnChromeOS())
326 logging::RedirectChromeLogging(*(CommandLine::ForCurrentProcess()));
328 // Update user's displayed email.
329 if (!display_email
.empty())
330 user_manager
->SaveUserDisplayEmail(user_context
.username
, display_email
);
332 user_context_
= user_context
;
334 using_oauth_
= using_oauth
;
335 has_web_auth_cookies_
= has_cookies
;
336 delegate_
= delegate
;
337 InitSessionRestoreStrategy();
339 // Can't use display_email because it is empty when existing user logs in
340 // using sing-in pod on login screen (i.e. user didn't type email).
341 g_browser_process
->profile_manager()->CreateProfileAsync(
342 user_manager
->GetUserProfileDir(user_context
.username
),
343 base::Bind(&LoginUtilsImpl::OnProfileCreated
, AsWeakPtr(),
344 user_context
.username
),
345 string16(), string16(), std::string());
348 void LoginUtilsImpl::DelegateDeleted(LoginUtils::Delegate
* delegate
) {
349 if (delegate_
== delegate
)
353 void LoginUtilsImpl::InitProfilePreferences(Profile
* user_profile
,
354 const std::string
& email
) {
355 if (UserManager::Get()->IsCurrentUserNew())
356 SetFirstLoginPrefs(user_profile
->GetPrefs());
358 if (UserManager::Get()->IsLoggedInAsLocallyManagedUser()) {
359 User
* active_user
= UserManager::Get()->GetActiveUser();
360 std::string managed_user_sync_id
=
361 UserManager::Get()->GetManagedUserSyncId(active_user
->email());
363 // TODO(ibraaaa): Remove that when 97% of our users are using M31.
364 // http://crbug.com/276163
365 if (managed_user_sync_id
.empty())
366 managed_user_sync_id
= "DUMMY_ID";
368 user_profile
->GetPrefs()->SetString(prefs::kManagedUserId
,
369 managed_user_sync_id
);
371 // Make sure that the google service username is properly set (we do this
372 // on every sign in, not just the first login, to deal with existing
373 // profiles that might not have it set yet).
374 StringPrefMember google_services_username
;
375 google_services_username
.Init(prefs::kGoogleServicesUsername
,
376 user_profile
->GetPrefs());
377 const User
* user
= UserManager::Get()->FindUser(email
);
378 google_services_username
.SetValue(user
? user
->display_email() : email
);
381 RespectLocalePreference(user_profile
);
384 void LoginUtilsImpl::InitSessionRestoreStrategy() {
385 CommandLine
* command_line
= CommandLine::ForCurrentProcess();
386 bool in_app_mode
= chrome::IsRunningInForcedAppMode();
388 // Are we in kiosk app mode?
390 if (command_line
->HasSwitch(::switches::kAppModeOAuth2Token
)) {
391 oauth2_refresh_token_
= command_line
->GetSwitchValueASCII(
392 ::switches::kAppModeOAuth2Token
);
395 if (command_line
->HasSwitch(::switches::kAppModeAuthCode
)) {
396 user_context_
.auth_code
= command_line
->GetSwitchValueASCII(
397 ::switches::kAppModeAuthCode
);
400 DCHECK(!has_web_auth_cookies_
);
401 if (!user_context_
.auth_code
.empty()) {
402 session_restore_strategy_
= OAuth2LoginManager::RESTORE_FROM_AUTH_CODE
;
403 } else if (!oauth2_refresh_token_
.empty()) {
404 session_restore_strategy_
=
405 OAuth2LoginManager::RESTORE_FROM_PASSED_OAUTH2_REFRESH_TOKEN
;
407 session_restore_strategy_
=
408 OAuth2LoginManager::RESTORE_FROM_SAVED_OAUTH2_REFRESH_TOKEN
;
413 if (has_web_auth_cookies_
) {
414 session_restore_strategy_
= OAuth2LoginManager::RESTORE_FROM_COOKIE_JAR
;
415 } else if (!user_context_
.auth_code
.empty()) {
416 session_restore_strategy_
= OAuth2LoginManager::RESTORE_FROM_AUTH_CODE
;
418 session_restore_strategy_
=
419 OAuth2LoginManager::RESTORE_FROM_SAVED_OAUTH2_REFRESH_TOKEN
;
424 void LoginUtilsImpl::OnProfileCreated(
425 const std::string
& email
,
426 Profile
* user_profile
,
427 Profile::CreateStatus status
) {
431 case Profile::CREATE_STATUS_INITIALIZED
:
432 UserProfileInitialized(user_profile
);
434 case Profile::CREATE_STATUS_CREATED
:
435 InitProfilePreferences(user_profile
, email
);
437 case Profile::CREATE_STATUS_LOCAL_FAIL
:
438 case Profile::CREATE_STATUS_REMOTE_FAIL
:
439 case Profile::CREATE_STATUS_CANCELED
:
440 case Profile::MAX_CREATE_STATUS
:
446 void LoginUtilsImpl::UserProfileInitialized(Profile
* user_profile
) {
447 BootTimesLoader
* btl
= BootTimesLoader::Get();
448 btl
->AddLoginTimeMarker("UserProfileGotten", false);
451 // Transfer proxy authentication cache, cookies (optionally) and server
452 // bound certs from the profile that was used for authentication. This
453 // profile contains cookies that auth extension should have already put in
454 // place that will ensure that the newly created session is authenticated
455 // for the websites that work with the used authentication schema.
456 ProfileAuthData::Transfer(authenticator_
->authentication_profile(),
458 has_web_auth_cookies_
, // transfer_cookies
460 &LoginUtilsImpl::CompleteProfileCreate
,
466 FinalizePrepareProfile(user_profile
);
469 void LoginUtilsImpl::CompleteProfileCreate(Profile
* user_profile
) {
470 RestoreAuthSession(user_profile
, has_web_auth_cookies_
);
471 FinalizePrepareProfile(user_profile
);
474 void LoginUtilsImpl::RestoreAuthSession(Profile
* user_profile
,
475 bool restore_from_auth_cookies
) {
476 CHECK((authenticator_
.get() && authenticator_
->authentication_profile()) ||
477 !restore_from_auth_cookies
);
479 if (chrome::IsRunningInForcedAppMode() ||
480 CommandLine::ForCurrentProcess()->HasSwitch(
481 chromeos::switches::kOobeSkipPostLogin
))
484 // Remove legacy OAuth1 token if we have one. If it's valid, we should already
485 // have OAuth2 refresh token in TokenService that could be used to retrieve
486 // all other tokens and user_context.
487 OAuth2LoginManager
* login_manager
=
488 OAuth2LoginManagerFactory::GetInstance()->GetForProfile(user_profile
);
489 login_manager
->AddObserver(this);
490 login_manager
->RestoreSession(
491 authenticator_
.get() && authenticator_
->authentication_profile()
492 ? authenticator_
->authentication_profile()->GetRequestContext()
494 session_restore_strategy_
,
495 oauth2_refresh_token_
,
496 user_context_
.auth_code
);
499 void LoginUtilsImpl::FinalizePrepareProfile(Profile
* user_profile
) {
500 BootTimesLoader
* btl
= BootTimesLoader::Get();
501 // Own TPM device if, for any reason, it has not been done in EULA
503 CryptohomeLibrary
* cryptohome
= CryptohomeLibrary::Get();
504 btl
->AddLoginTimeMarker("TPMOwn-Start", false);
505 if (cryptohome
->TpmIsEnabled() && !cryptohome
->TpmIsBeingOwned()) {
506 if (cryptohome
->TpmIsOwned()) {
507 cryptohome
->TpmClearStoredPassword();
509 cryptohome
->TpmCanAttemptOwnership();
512 btl
->AddLoginTimeMarker("TPMOwn-End", false);
514 user_profile
->OnLogin();
516 // Send the notification before creating the browser so additional objects
517 // that need the profile (e.g. the launcher) can be created first.
518 content::NotificationService::current()->Notify(
519 chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED
,
520 content::NotificationService::AllSources(),
521 content::Details
<Profile
>(user_profile
));
523 InitRlzDelayed(user_profile
);
525 // TODO(altimofeev): This pointer should probably never be NULL, but it looks
526 // like LoginUtilsImpl::OnProfileCreated() may be getting called before
527 // LoginUtilsImpl::PrepareProfile() has set |delegate_| when Chrome is killed
528 // during shutdown in tests -- see http://crosbug.com/18269. Replace this
529 // 'if' statement with a CHECK(delegate_) once the underlying issue is
532 delegate_
->OnProfilePrepared(user_profile
);
535 void LoginUtilsImpl::InitRlzDelayed(Profile
* user_profile
) {
536 #if defined(ENABLE_RLZ)
537 if (!g_browser_process
->local_state()->HasPrefPath(prefs::kRLZBrand
)) {
538 // Read brand code asynchronously from an OEM file and repost ourselves.
539 google_util::chromeos::SetBrandFromFile(
540 base::Bind(&LoginUtilsImpl::InitRlzDelayed
, AsWeakPtr(), user_profile
));
543 base::PostTaskAndReplyWithResult(
544 base::WorkerPool::GetTaskRunner(false),
546 base::Bind(&base::PathExists
, GetRlzDisabledFlagPath()),
547 base::Bind(&LoginUtilsImpl::InitRlz
, AsWeakPtr(), user_profile
));
551 void LoginUtilsImpl::InitRlz(Profile
* user_profile
, bool disabled
) {
552 #if defined(ENABLE_RLZ)
553 PrefService
* local_state
= g_browser_process
->local_state();
555 // Empty brand code means an organic install (no RLZ pings are sent).
556 google_util::chromeos::ClearBrandForCurrentSession();
558 if (disabled
!= local_state
->GetBoolean(prefs::kRLZDisabled
)) {
559 // When switching to RLZ enabled/disabled state, clear all recorded events.
560 RLZTracker::ClearRlzState();
561 local_state
->SetBoolean(prefs::kRLZDisabled
, disabled
);
563 // Init the RLZ library.
564 int ping_delay
= user_profile
->GetPrefs()->GetInteger(
565 first_run::GetPingDelayPrefName().c_str());
566 // Negative ping delay means to send ping immediately after a first search is
568 RLZTracker::InitRlzFromProfileDelayed(
569 user_profile
, UserManager::Get()->IsCurrentUserNew(),
570 ping_delay
< 0, base::TimeDelta::FromMilliseconds(abs(ping_delay
)));
572 delegate_
->OnRlzInitialized(user_profile
);
576 void LoginUtilsImpl::StartSignedInServices(Profile
* user_profile
) {
577 // Fetch/Create the SigninManager - this will cause the TokenService to load
578 // tokens for the currently signed-in user if the SigninManager hasn't
579 // already been initialized.
580 SigninManagerBase
* signin
=
581 SigninManagerFactory::GetForProfile(user_profile
);
583 // Make sure SigninManager is connected to our current user (this should
584 // happen automatically because we set kGoogleServicesUsername in
585 // OnProfileCreated()).
586 DCHECK_EQ(UserManager::Get()->GetLoggedInUser()->display_email(),
587 signin
->GetAuthenticatedUsername());
588 static bool initialized
= false;
591 // Notify the sync service that signin was successful. Note: Since the sync
592 // service is lazy-initialized, we need to make sure it has been created.
593 ProfileSyncService
* sync_service
=
594 ProfileSyncServiceFactory::GetInstance()->GetForProfile(user_profile
);
595 // We may not always have a passphrase (for example, on a restart after a
596 // browser crash). Only notify the sync service if we have a passphrase,
597 // so it can do any required re-encryption.
598 if (!user_context_
.password
.empty() && sync_service
) {
599 GoogleServiceSigninSuccessDetails
details(
600 signin
->GetAuthenticatedUsername(),
601 user_context_
.password
);
602 content::NotificationService::current()->Notify(
603 chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL
,
604 content::Source
<Profile
>(user_profile
),
605 content::Details
<const GoogleServiceSigninSuccessDetails
>(&details
));
608 user_context_
.password
.clear();
609 user_context_
.auth_code
.clear();
612 void LoginUtilsImpl::RespectLocalePreference(Profile
* profile
) {
613 DCHECK(profile
!= NULL
);
614 PrefService
* prefs
= profile
->GetPrefs();
615 DCHECK(prefs
!= NULL
);
616 if (g_browser_process
== NULL
)
619 std::string pref_locale
= prefs
->GetString(prefs::kApplicationLocale
);
620 if (pref_locale
.empty())
621 pref_locale
= prefs
->GetString(prefs::kApplicationLocaleBackup
);
622 if (pref_locale
.empty())
623 pref_locale
= g_browser_process
->GetApplicationLocale();
624 DCHECK(!pref_locale
.empty());
625 profile
->ChangeAppLocale(pref_locale
, Profile::APP_LOCALE_CHANGED_VIA_LOGIN
);
626 // Here we don't enable keyboard layouts. Input methods are set up when
627 // the user first logs in. Then the user may customize the input methods.
628 // Hence changing input methods here, just because the user's UI language
629 // is different from the login screen UI language, is not desirable. Note
630 // that input method preferences are synced, so users can use their
631 // farovite input methods as soon as the preferences are synced.
632 LanguageSwitchMenu::SwitchLanguage(pref_locale
);
635 void LoginUtilsImpl::CompleteOffTheRecordLogin(const GURL
& start_url
) {
636 VLOG(1) << "Completing incognito login";
638 // For guest session we ask session manager to restart Chrome with --bwsi
639 // flag. We keep only some of the arguments of this process.
640 const CommandLine
& browser_command_line
= *CommandLine::ForCurrentProcess();
641 CommandLine
command_line(browser_command_line
.GetProgram());
642 std::string cmd_line_str
= GetOffTheRecordCommandLine(start_url
,
643 browser_command_line
,
646 RestartChrome(cmd_line_str
);
649 void LoginUtilsImpl::SetFirstLoginPrefs(PrefService
* prefs
) {
650 VLOG(1) << "Setting first login prefs";
651 BootTimesLoader
* btl
= BootTimesLoader::Get();
652 std::string locale
= g_browser_process
->GetApplicationLocale();
654 // First, we'll set kLanguagePreloadEngines.
655 input_method::InputMethodManager
* manager
=
656 input_method::InputMethodManager::Get();
657 std::vector
<std::string
> input_method_ids
;
658 manager
->GetInputMethodUtil()->GetFirstLoginInputMethodIds(
659 locale
, manager
->GetCurrentInputMethod(), &input_method_ids
);
660 // Save the input methods in the user's preferences.
661 StringPrefMember language_preload_engines
;
662 language_preload_engines
.Init(prefs::kLanguagePreloadEngines
,
664 language_preload_engines
.SetValue(JoinString(input_method_ids
, ','));
665 btl
->AddLoginTimeMarker("IMEStarted", false);
667 // Second, we'll set kLanguagePreferredLanguages.
668 std::vector
<std::string
> language_codes
;
669 // The current locale should be on the top.
670 language_codes
.push_back(locale
);
672 // Add input method IDs based on the input methods, as there may be
673 // input methods that are unrelated to the current locale. Example: the
674 // hardware keyboard layout xkb:us::eng is used for logging in, but the
675 // UI language is set to French. In this case, we should set "fr,en"
676 // to the preferred languages preference.
677 std::vector
<std::string
> candidates
;
678 manager
->GetInputMethodUtil()->GetLanguageCodesFromInputMethodIds(
679 input_method_ids
, &candidates
);
680 for (size_t i
= 0; i
< candidates
.size(); ++i
) {
681 const std::string
& candidate
= candidates
[i
];
682 // Skip if it's already in language_codes.
683 if (std::count(language_codes
.begin(), language_codes
.end(),
685 language_codes
.push_back(candidate
);
688 // Save the preferred languages in the user's preferences.
689 StringPrefMember language_preferred_languages
;
690 language_preferred_languages
.Init(prefs::kLanguagePreferredLanguages
,
692 language_preferred_languages
.SetValue(JoinString(language_codes
, ','));
695 scoped_refptr
<Authenticator
> LoginUtilsImpl::CreateAuthenticator(
696 LoginStatusConsumer
* consumer
) {
697 // Screen locker needs new Authenticator instance each time.
698 if (ScreenLocker::default_screen_locker()) {
699 if (authenticator_
.get())
700 authenticator_
->SetConsumer(NULL
);
701 authenticator_
= NULL
;
704 if (authenticator_
.get() == NULL
) {
705 authenticator_
= new ParallelAuthenticator(consumer
);
707 // TODO(nkostylev): Fix this hack by improving Authenticator dependencies.
708 authenticator_
->SetConsumer(consumer
);
710 return authenticator_
;
713 void LoginUtilsImpl::RestoreAuthenticationSession(Profile
* user_profile
) {
714 // We don't need to restore session for demo/guest/stub/public account users.
715 if (!UserManager::Get()->IsUserLoggedIn() ||
716 UserManager::Get()->IsLoggedInAsGuest() ||
717 UserManager::Get()->IsLoggedInAsPublicAccount() ||
718 UserManager::Get()->IsLoggedInAsDemoUser() ||
719 UserManager::Get()->IsLoggedInAsStub()) {
723 if (!net::NetworkChangeNotifier::IsOffline()) {
724 should_restore_auth_session_
= false;
725 RestoreAuthSession(user_profile
, false);
727 // Even if we're online we should wait till initial
728 // OnConnectionTypeChanged() call. Otherwise starting fetchers too early may
729 // end up canceling all request when initial network connection type is
730 // processed. See http://crbug.com/121643.
731 should_restore_auth_session_
= true;
735 void LoginUtilsImpl::OnSessionRestoreStateChanged(
736 Profile
* user_profile
,
737 OAuth2LoginManager::SessionRestoreState state
) {
738 OAuth2LoginManager
* login_manager
=
739 OAuth2LoginManagerFactory::GetInstance()->GetForProfile(user_profile
);
741 case OAuth2LoginManager::SESSION_RESTORE_NOT_STARTED
:
743 case OAuth2LoginManager::SESSION_RESTORE_PREPARING
:
745 case OAuth2LoginManager::SESSION_RESTORE_IN_PROGRESS
:
747 case OAuth2LoginManager::SESSION_RESTORE_DONE
:
748 UserManager::Get()->SaveUserOAuthStatus(
749 UserManager::Get()->GetLoggedInUser()->email(),
750 User::OAUTH2_TOKEN_STATUS_VALID
);
751 login_manager
->RemoveObserver(this);
753 case OAuth2LoginManager::SESSION_RESTORE_FAILED
:
754 UserManager::Get()->SaveUserOAuthStatus(
755 UserManager::Get()->GetLoggedInUser()->email(),
756 User::OAUTH2_TOKEN_STATUS_INVALID
);
757 login_manager
->RemoveObserver(this);
762 void LoginUtilsImpl::OnSessionAuthenticated(Profile
* user_profile
) {
763 StartSignedInServices(user_profile
);
766 void LoginUtilsImpl::OnConnectionTypeChanged(
767 net::NetworkChangeNotifier::ConnectionType type
) {
768 Profile
* user_profile
= ProfileManager::GetDefaultProfile();
769 OAuth2LoginManager
* login_manager
=
770 OAuth2LoginManagerFactory::GetInstance()->GetForProfile(user_profile
);
772 if (type
!= net::NetworkChangeNotifier::CONNECTION_NONE
&&
773 UserManager::Get()->IsUserLoggedIn()) {
774 if (login_manager
->state() ==
775 OAuth2LoginManager::SESSION_RESTORE_IN_PROGRESS
) {
776 // If we come online for the first time after successful offline login,
777 // we need to kick off OAuth token verification process again.
778 login_manager
->ContinueSessionRestore();
779 } else if (should_restore_auth_session_
) {
780 should_restore_auth_session_
= false;
781 RestoreAuthSession(user_profile
, has_web_auth_cookies_
);
787 void LoginUtils::RegisterPrefs(PrefRegistrySimple
* registry
) {
788 registry
->RegisterBooleanPref(prefs::kFactoryResetRequested
, false);
789 registry
->RegisterStringPref(prefs::kRLZBrand
, std::string());
790 registry
->RegisterBooleanPref(prefs::kRLZDisabled
, false);
794 LoginUtils
* LoginUtils::Get() {
795 return LoginUtilsWrapper::GetInstance()->get();
799 void LoginUtils::Set(LoginUtils
* mock
) {
800 LoginUtilsWrapper::GetInstance()->reset(mock
);
804 bool LoginUtils::IsWhitelisted(const std::string
& username
) {
805 CrosSettings
* cros_settings
= CrosSettings::Get();
806 bool allow_new_user
= false;
807 cros_settings
->GetBoolean(kAccountsPrefAllowNewUser
, &allow_new_user
);
810 return cros_settings
->FindEmailInList(kAccountsPrefUsers
, username
);
813 } // namespace chromeos