1 // Copyright 2014 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/users/chrome_user_manager_impl.h"
10 #include "ash/multi_profile_uma.h"
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/command_line.h"
14 #include "base/compiler_specific.h"
15 #include "base/format_macros.h"
16 #include "base/logging.h"
17 #include "base/metrics/histogram.h"
18 #include "base/prefs/pref_registry_simple.h"
19 #include "base/prefs/pref_service.h"
20 #include "base/prefs/scoped_user_pref_update.h"
21 #include "base/strings/string_util.h"
22 #include "base/strings/stringprintf.h"
23 #include "base/strings/utf_string_conversions.h"
24 #include "base/thread_task_runner_handle.h"
25 #include "base/values.h"
26 #include "chrome/browser/browser_process.h"
27 #include "chrome/browser/chrome_notification_types.h"
28 #include "chrome/browser/chromeos/login/demo_mode/demo_app_launcher.h"
29 #include "chrome/browser/chromeos/login/session/user_session_manager.h"
30 #include "chrome/browser/chromeos/login/signin/auth_sync_observer.h"
31 #include "chrome/browser/chromeos/login/signin/auth_sync_observer_factory.h"
32 #include "chrome/browser/chromeos/login/users/avatar/user_image_manager_impl.h"
33 #include "chrome/browser/chromeos/login/users/multi_profile_user_controller.h"
34 #include "chrome/browser/chromeos/login/users/supervised_user_manager_impl.h"
35 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
36 #include "chrome/browser/chromeos/policy/device_local_account.h"
37 #include "chrome/browser/chromeos/profiles/multiprofiles_session_aborted_dialog.h"
38 #include "chrome/browser/chromeos/profiles/profile_helper.h"
39 #include "chrome/browser/chromeos/session_length_limiter.h"
40 #include "chrome/browser/profiles/profile.h"
41 #include "chrome/browser/supervised_user/chromeos/manager_password_service_factory.h"
42 #include "chrome/browser/supervised_user/chromeos/supervised_user_password_service_factory.h"
43 #include "chrome/common/chrome_constants.h"
44 #include "chrome/common/chrome_switches.h"
45 #include "chrome/common/crash_keys.h"
46 #include "chrome/common/pref_names.h"
47 #include "chrome/grit/theme_resources.h"
48 #include "chromeos/chromeos_switches.h"
49 #include "chromeos/login/user_names.h"
50 #include "chromeos/settings/cros_settings_names.h"
51 #include "components/session_manager/core/session_manager.h"
52 #include "components/user_manager/remove_user_delegate.h"
53 #include "components/user_manager/user_image/user_image.h"
54 #include "components/user_manager/user_type.h"
55 #include "content/public/browser/browser_thread.h"
56 #include "content/public/browser/notification_service.h"
57 #include "policy/policy_constants.h"
58 #include "ui/base/resource/resource_bundle.h"
59 #include "ui/wm/core/wm_core_switches.h"
61 using content::BrowserThread;
66 // A vector pref of the the regular users known on this device, arranged in LRU
68 const char kRegularUsers[] = "LoggedInUsers";
70 // A vector pref of the public accounts defined on this device.
71 const char kPublicAccounts[] = "PublicAccounts";
73 // A string pref that gets set when a public account is removed but a user is
74 // currently logged into that account, requiring the account's data to be
75 // removed after logout.
76 const char kPublicAccountPendingDataRemoval[] =
77 "PublicAccountPendingDataRemoval";
82 void ChromeUserManagerImpl::RegisterPrefs(PrefRegistrySimple* registry) {
83 ChromeUserManager::RegisterPrefs(registry);
85 registry->RegisterListPref(kPublicAccounts);
86 registry->RegisterStringPref(kPublicAccountPendingDataRemoval, std::string());
87 SupervisedUserManager::RegisterPrefs(registry);
88 SessionLengthLimiter::RegisterPrefs(registry);
92 scoped_ptr<ChromeUserManager> ChromeUserManagerImpl::CreateChromeUserManager() {
93 return scoped_ptr<ChromeUserManager>(new ChromeUserManagerImpl());
96 ChromeUserManagerImpl::ChromeUserManagerImpl()
97 : ChromeUserManager(base::ThreadTaskRunnerHandle::Get(),
98 BrowserThread::GetBlockingPool()),
99 cros_settings_(CrosSettings::Get()),
100 device_local_account_policy_service_(NULL),
101 supervised_user_manager_(new SupervisedUserManagerImpl(this)),
102 weak_factory_(this) {
103 UpdateNumberOfUsers();
105 // UserManager instance should be used only on UI thread.
106 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
108 chrome::NOTIFICATION_OWNERSHIP_STATUS_CHANGED,
109 content::NotificationService::AllSources());
111 chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED,
112 content::NotificationService::AllSources());
114 chrome::NOTIFICATION_PROFILE_CREATED,
115 content::NotificationService::AllSources());
117 // Since we're in ctor postpone any actions till this is fully created.
118 if (base::MessageLoop::current()) {
119 base::MessageLoop::current()->PostTask(
121 base::Bind(&ChromeUserManagerImpl::RetrieveTrustedDevicePolicies,
122 weak_factory_.GetWeakPtr()));
125 local_accounts_subscription_ = cros_settings_->AddSettingsObserver(
126 kAccountsPrefDeviceLocalAccounts,
127 base::Bind(&ChromeUserManagerImpl::RetrieveTrustedDevicePolicies,
128 weak_factory_.GetWeakPtr()));
129 multi_profile_user_controller_.reset(
130 new MultiProfileUserController(this, GetLocalState()));
132 policy::BrowserPolicyConnectorChromeOS* connector =
133 g_browser_process->platform_part()->browser_policy_connector_chromeos();
134 avatar_policy_observer_.reset(new policy::CloudExternalDataPolicyObserver(
136 connector->GetDeviceLocalAccountPolicyService(),
137 policy::key::kUserAvatarImage,
139 avatar_policy_observer_->Init();
141 wallpaper_policy_observer_.reset(new policy::CloudExternalDataPolicyObserver(
143 connector->GetDeviceLocalAccountPolicyService(),
144 policy::key::kWallpaperImage,
146 wallpaper_policy_observer_->Init();
149 ChromeUserManagerImpl::~ChromeUserManagerImpl() {
152 void ChromeUserManagerImpl::Shutdown() {
153 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
154 ChromeUserManager::Shutdown();
156 local_accounts_subscription_.reset();
158 // Stop the session length limiter.
159 session_length_limiter_.reset();
161 if (device_local_account_policy_service_)
162 device_local_account_policy_service_->RemoveObserver(this);
164 for (UserImageManagerMap::iterator it = user_image_managers_.begin(),
165 ie = user_image_managers_.end();
168 it->second->Shutdown();
170 multi_profile_user_controller_.reset();
171 avatar_policy_observer_.reset();
172 wallpaper_policy_observer_.reset();
173 registrar_.RemoveAll();
176 MultiProfileUserController*
177 ChromeUserManagerImpl::GetMultiProfileUserController() {
178 return multi_profile_user_controller_.get();
181 UserImageManager* ChromeUserManagerImpl::GetUserImageManager(
182 const std::string& user_id) {
183 UserImageManagerMap::iterator ui = user_image_managers_.find(user_id);
184 if (ui != user_image_managers_.end())
185 return ui->second.get();
186 linked_ptr<UserImageManagerImpl> mgr(new UserImageManagerImpl(user_id, this));
187 user_image_managers_[user_id] = mgr;
191 SupervisedUserManager* ChromeUserManagerImpl::GetSupervisedUserManager() {
192 return supervised_user_manager_.get();
195 user_manager::UserList ChromeUserManagerImpl::GetUsersAdmittedForMultiProfile()
197 // Supervised users are not allowed to use multi-profiles.
198 if (GetLoggedInUsers().size() == 1 &&
199 GetPrimaryUser()->GetType() != user_manager::USER_TYPE_REGULAR) {
200 return user_manager::UserList();
203 user_manager::UserList result;
204 const user_manager::UserList& users = GetUsers();
205 for (user_manager::UserList::const_iterator it = users.begin();
208 if ((*it)->GetType() == user_manager::USER_TYPE_REGULAR &&
209 !(*it)->is_logged_in()) {
210 MultiProfileUserController::UserAllowedInSessionReason check;
211 multi_profile_user_controller_->IsUserAllowedInSession((*it)->email(),
214 MultiProfileUserController::NOT_ALLOWED_PRIMARY_USER_POLICY_FORBIDS) {
215 return user_manager::UserList();
218 // Users with a policy that prevents them being added to a session will be
219 // shown in login UI but will be grayed out.
220 // Same applies to owner account (see http://crbug.com/385034).
221 result.push_back(*it);
228 user_manager::UserList ChromeUserManagerImpl::GetUnlockUsers() const {
229 const user_manager::UserList& logged_in_users = GetLoggedInUsers();
230 if (logged_in_users.empty())
231 return user_manager::UserList();
233 user_manager::UserList unlock_users;
235 ProfileHelper::Get()->GetProfileByUserUnsafe(GetPrimaryUser());
236 std::string primary_behavior =
237 profile->GetPrefs()->GetString(prefs::kMultiProfileUserBehavior);
239 // Specific case: only one logged in user or
240 // primary user has primary-only multi-profile policy.
241 if (logged_in_users.size() == 1 ||
242 primary_behavior == MultiProfileUserController::kBehaviorPrimaryOnly) {
243 if (GetPrimaryUser()->can_lock())
244 unlock_users.push_back(primary_user_);
246 // Fill list of potential unlock users based on multi-profile policy state.
247 for (user_manager::UserList::const_iterator it = logged_in_users.begin();
248 it != logged_in_users.end();
250 user_manager::User* user = (*it);
251 Profile* profile = ProfileHelper::Get()->GetProfileByUserUnsafe(user);
252 const std::string behavior =
253 profile->GetPrefs()->GetString(prefs::kMultiProfileUserBehavior);
254 if (behavior == MultiProfileUserController::kBehaviorUnrestricted &&
256 unlock_users.push_back(user);
257 } else if (behavior == MultiProfileUserController::kBehaviorPrimaryOnly) {
259 << "Spotted primary-only multi-profile policy for non-primary user";
267 void ChromeUserManagerImpl::SessionStarted() {
268 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
269 ChromeUserManager::SessionStarted();
271 content::NotificationService::current()->Notify(
272 chrome::NOTIFICATION_SESSION_STARTED,
273 content::Source<UserManager>(this),
274 content::Details<const user_manager::User>(GetActiveUser()));
277 void ChromeUserManagerImpl::RemoveUserInternal(
278 const std::string& user_email,
279 user_manager::RemoveUserDelegate* delegate) {
280 CrosSettings* cros_settings = CrosSettings::Get();
282 const base::Closure& callback =
283 base::Bind(&ChromeUserManagerImpl::RemoveUserInternal,
284 weak_factory_.GetWeakPtr(),
288 // Ensure the value of owner email has been fetched.
289 if (CrosSettingsProvider::TRUSTED !=
290 cros_settings->PrepareTrustedValues(callback)) {
291 // Value of owner email is not fetched yet. RemoveUserInternal will be
292 // called again after fetch completion.
296 cros_settings->GetString(kDeviceOwner, &owner);
297 if (user_email == owner) {
298 // Owner is not allowed to be removed from the device.
301 RemoveNonOwnerUserInternal(user_email, delegate);
304 void ChromeUserManagerImpl::SaveUserOAuthStatus(
305 const std::string& user_id,
306 user_manager::User::OAuthTokenStatus oauth_token_status) {
307 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
308 ChromeUserManager::SaveUserOAuthStatus(user_id, oauth_token_status);
310 GetUserFlow(user_id)->HandleOAuthTokenStatusChange(oauth_token_status);
313 void ChromeUserManagerImpl::SaveUserDisplayName(
314 const std::string& user_id,
315 const base::string16& display_name) {
316 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
317 ChromeUserManager::SaveUserDisplayName(user_id, display_name);
319 // Do not update local state if data stored or cached outside the user's
320 // cryptohome is to be treated as ephemeral.
321 if (!IsUserNonCryptohomeDataEphemeral(user_id))
322 supervised_user_manager_->UpdateManagerName(user_id, display_name);
325 void ChromeUserManagerImpl::StopPolicyObserverForTesting() {
326 avatar_policy_observer_.reset();
327 wallpaper_policy_observer_.reset();
330 void ChromeUserManagerImpl::Observe(
332 const content::NotificationSource& source,
333 const content::NotificationDetails& details) {
335 case chrome::NOTIFICATION_OWNERSHIP_STATUS_CHANGED:
336 if (!device_local_account_policy_service_) {
337 policy::BrowserPolicyConnectorChromeOS* connector =
338 g_browser_process->platform_part()
339 ->browser_policy_connector_chromeos();
340 device_local_account_policy_service_ =
341 connector->GetDeviceLocalAccountPolicyService();
342 if (device_local_account_policy_service_)
343 device_local_account_policy_service_->AddObserver(this);
345 RetrieveTrustedDevicePolicies();
348 case chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED: {
349 Profile* profile = content::Details<Profile>(details).ptr();
350 if (IsUserLoggedIn() && !IsLoggedInAsGuest() && !IsLoggedInAsKioskApp()) {
351 if (IsLoggedInAsSupervisedUser())
352 SupervisedUserPasswordServiceFactory::GetForProfile(profile);
353 if (IsLoggedInAsRegularUser())
354 ManagerPasswordServiceFactory::GetForProfile(profile);
356 if (!profile->IsOffTheRecord()) {
357 AuthSyncObserver* sync_observer =
358 AuthSyncObserverFactory::GetInstance()->GetForProfile(profile);
359 sync_observer->StartObserving();
360 multi_profile_user_controller_->StartObserving(profile);
365 case chrome::NOTIFICATION_PROFILE_CREATED: {
366 Profile* profile = content::Source<Profile>(source).ptr();
367 user_manager::User* user =
368 ProfileHelper::Get()->GetUserByProfile(profile);
370 user->set_profile_is_created();
372 // If there is pending user switch, do it now.
373 if (!GetPendingUserSwitchID().empty()) {
374 // Call SwitchActiveUser async because otherwise it may cause
375 // ProfileManager::GetProfile before the profile gets registered
376 // in ProfileManager. It happens in case of sync profile load when
377 // NOTIFICATION_PROFILE_CREATED is called synchronously.
378 base::MessageLoop::current()->PostTask(
380 base::Bind(&ChromeUserManagerImpl::SwitchActiveUser,
381 weak_factory_.GetWeakPtr(),
382 GetPendingUserSwitchID()));
383 SetPendingUserSwitchID(std::string());
392 void ChromeUserManagerImpl::OnExternalDataSet(const std::string& policy,
393 const std::string& user_id) {
394 if (policy == policy::key::kUserAvatarImage)
395 GetUserImageManager(user_id)->OnExternalDataSet(policy);
396 else if (policy == policy::key::kWallpaperImage)
397 WallpaperManager::Get()->OnPolicySet(policy, user_id);
402 void ChromeUserManagerImpl::OnExternalDataCleared(const std::string& policy,
403 const std::string& user_id) {
404 if (policy == policy::key::kUserAvatarImage)
405 GetUserImageManager(user_id)->OnExternalDataCleared(policy);
406 else if (policy == policy::key::kWallpaperImage)
407 WallpaperManager::Get()->OnPolicyCleared(policy, user_id);
412 void ChromeUserManagerImpl::OnExternalDataFetched(
413 const std::string& policy,
414 const std::string& user_id,
415 scoped_ptr<std::string> data) {
416 if (policy == policy::key::kUserAvatarImage)
417 GetUserImageManager(user_id)->OnExternalDataFetched(policy, data.Pass());
418 else if (policy == policy::key::kWallpaperImage)
419 WallpaperManager::Get()->OnPolicyFetched(policy, user_id, data.Pass());
424 void ChromeUserManagerImpl::OnPolicyUpdated(const std::string& user_id) {
425 const user_manager::User* user = FindUser(user_id);
426 if (!user || user->GetType() != user_manager::USER_TYPE_PUBLIC_ACCOUNT)
428 UpdatePublicAccountDisplayName(user_id);
431 void ChromeUserManagerImpl::OnDeviceLocalAccountsChanged() {
432 // No action needed here, changes to the list of device-local accounts get
433 // handled via the kAccountsPrefDeviceLocalAccounts device setting observer.
436 bool ChromeUserManagerImpl::CanCurrentUserLock() const {
437 return ChromeUserManager::CanCurrentUserLock() &&
438 GetCurrentUserFlow()->CanLockScreen();
441 bool ChromeUserManagerImpl::IsUserNonCryptohomeDataEphemeral(
442 const std::string& user_id) const {
443 // Data belonging to the obsolete public accounts whose data has not been
444 // removed yet is not ephemeral.
445 bool is_obsolete_public_account = IsPublicAccountMarkedForRemoval(user_id);
447 return !is_obsolete_public_account &&
448 ChromeUserManager::IsUserNonCryptohomeDataEphemeral(user_id);
451 bool ChromeUserManagerImpl::AreEphemeralUsersEnabled() const {
452 policy::BrowserPolicyConnectorChromeOS* connector =
453 g_browser_process->platform_part()->browser_policy_connector_chromeos();
454 return GetEphemeralUsersEnabled() &&
455 (connector->IsEnterpriseManaged() || !GetOwnerEmail().empty());
458 const std::string& ChromeUserManagerImpl::GetApplicationLocale() const {
459 return g_browser_process->GetApplicationLocale();
462 PrefService* ChromeUserManagerImpl::GetLocalState() const {
463 return g_browser_process ? g_browser_process->local_state() : NULL;
466 void ChromeUserManagerImpl::HandleUserOAuthTokenStatusChange(
467 const std::string& user_id,
468 user_manager::User::OAuthTokenStatus status) const {
469 GetUserFlow(user_id)->HandleOAuthTokenStatusChange(status);
472 bool ChromeUserManagerImpl::IsEnterpriseManaged() const {
473 policy::BrowserPolicyConnectorChromeOS* connector =
474 g_browser_process->platform_part()->browser_policy_connector_chromeos();
475 return connector->IsEnterpriseManaged();
478 void ChromeUserManagerImpl::LoadPublicAccounts(
479 std::set<std::string>* public_sessions_set) {
480 const base::ListValue* prefs_public_sessions =
481 GetLocalState()->GetList(kPublicAccounts);
482 std::vector<std::string> public_sessions;
483 ParseUserList(*prefs_public_sessions,
484 std::set<std::string>(),
486 public_sessions_set);
487 for (std::vector<std::string>::const_iterator it = public_sessions.begin();
488 it != public_sessions.end();
490 users_.push_back(user_manager::User::CreatePublicAccountUser(*it));
491 UpdatePublicAccountDisplayName(*it);
495 void ChromeUserManagerImpl::PerformPreUserListLoadingActions() {
496 // Clean up user list first. All code down the path should be synchronous,
497 // so that local state after transaction rollback is in consistent state.
498 // This process also should not trigger EnsureUsersLoaded again.
499 if (supervised_user_manager_->HasFailedUserCreationTransaction())
500 supervised_user_manager_->RollbackUserCreationTransaction();
503 void ChromeUserManagerImpl::PerformPostUserListLoadingActions() {
504 for (user_manager::UserList::iterator ui = users_.begin(), ue = users_.end();
507 GetUserImageManager((*ui)->email())->LoadUserImage();
511 void ChromeUserManagerImpl::PerformPostUserLoggedInActions(
512 bool browser_restart) {
513 // Initialize the session length limiter and start it only if
514 // session limit is defined by the policy.
515 session_length_limiter_.reset(
516 new SessionLengthLimiter(NULL, browser_restart));
519 bool ChromeUserManagerImpl::IsDemoApp(const std::string& user_id) const {
520 return DemoAppLauncher::IsDemoAppSession(user_id);
523 bool ChromeUserManagerImpl::IsKioskApp(const std::string& user_id) const {
524 policy::DeviceLocalAccount::Type device_local_account_type;
525 return policy::IsDeviceLocalAccountUser(user_id,
526 &device_local_account_type) &&
527 device_local_account_type ==
528 policy::DeviceLocalAccount::TYPE_KIOSK_APP;
531 bool ChromeUserManagerImpl::IsPublicAccountMarkedForRemoval(
532 const std::string& user_id) const {
534 GetLocalState()->GetString(kPublicAccountPendingDataRemoval);
537 void ChromeUserManagerImpl::RetrieveTrustedDevicePolicies() {
538 // Local state may not be initialized in unit_tests.
539 if (!GetLocalState())
542 SetEphemeralUsersEnabled(false);
543 SetOwnerEmail(std::string());
545 // Schedule a callback if device policy has not yet been verified.
546 if (CrosSettingsProvider::TRUSTED !=
547 cros_settings_->PrepareTrustedValues(
548 base::Bind(&ChromeUserManagerImpl::RetrieveTrustedDevicePolicies,
549 weak_factory_.GetWeakPtr()))) {
553 bool ephemeral_users_enabled = false;
554 cros_settings_->GetBoolean(kAccountsPrefEphemeralUsersEnabled,
555 &ephemeral_users_enabled);
556 SetEphemeralUsersEnabled(ephemeral_users_enabled);
558 std::string owner_email;
559 cros_settings_->GetString(kDeviceOwner, &owner_email);
560 SetOwnerEmail(owner_email);
564 bool changed = UpdateAndCleanUpPublicAccounts(
565 policy::GetDeviceLocalAccounts(cros_settings_));
567 // If ephemeral users are enabled and we are on the login screen, take this
568 // opportunity to clean up by removing all regular users except the owner.
569 if (GetEphemeralUsersEnabled() && !IsUserLoggedIn()) {
570 ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers);
571 prefs_users_update->Clear();
572 for (user_manager::UserList::iterator it = users_.begin();
573 it != users_.end();) {
574 const std::string user_email = (*it)->email();
575 if ((*it)->GetType() == user_manager::USER_TYPE_REGULAR &&
576 user_email != GetOwnerEmail()) {
577 RemoveNonCryptohomeData(user_email);
579 it = users_.erase(it);
582 if ((*it)->GetType() != user_manager::USER_TYPE_PUBLIC_ACCOUNT)
583 prefs_users_update->Append(new base::StringValue(user_email));
590 NotifyUserListChanged();
593 void ChromeUserManagerImpl::GuestUserLoggedIn() {
594 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
595 ChromeUserManager::GuestUserLoggedIn();
597 // TODO(nkostylev): Add support for passing guest session cryptohome
598 // mount point. Legacy (--login-profile) value will be used for now.
599 // http://crosbug.com/230859
600 active_user_->SetStubImage(
601 user_manager::UserImage(
602 *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
603 IDR_PROFILE_PICTURE_LOADING)),
604 user_manager::User::USER_IMAGE_INVALID,
607 // Initializes wallpaper after active_user_ is set.
608 WallpaperManager::Get()->SetUserWallpaperNow(chromeos::login::kGuestUserName);
611 void ChromeUserManagerImpl::RegularUserLoggedIn(const std::string& user_id) {
612 ChromeUserManager::RegularUserLoggedIn(user_id);
614 if (IsCurrentUserNew())
615 WallpaperManager::Get()->SetUserWallpaperNow(user_id);
617 GetUserImageManager(user_id)->UserLoggedIn(IsCurrentUserNew(), false);
619 WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded();
621 // Make sure that new data is persisted to Local State.
622 GetLocalState()->CommitPendingWrite();
625 void ChromeUserManagerImpl::RegularUserLoggedInAsEphemeral(
626 const std::string& user_id) {
627 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
628 ChromeUserManager::RegularUserLoggedInAsEphemeral(user_id);
630 GetUserImageManager(user_id)->UserLoggedIn(IsCurrentUserNew(), false);
631 WallpaperManager::Get()->SetUserWallpaperNow(user_id);
634 void ChromeUserManagerImpl::SupervisedUserLoggedIn(const std::string& user_id) {
635 // TODO(nkostylev): Refactor, share code with RegularUserLoggedIn().
637 // Remove the user from the user list.
638 active_user_ = RemoveRegularOrSupervisedUserFromList(user_id);
640 // If the user was not found on the user list, create a new user.
641 if (!GetActiveUser()) {
642 SetIsCurrentUserNew(true);
643 active_user_ = user_manager::User::CreateSupervisedUser(user_id);
644 // Leaving OAuth token status at the default state = unknown.
645 WallpaperManager::Get()->SetUserWallpaperNow(user_id);
647 if (supervised_user_manager_->CheckForFirstRun(user_id)) {
648 SetIsCurrentUserNew(true);
649 WallpaperManager::Get()->SetUserWallpaperNow(user_id);
651 SetIsCurrentUserNew(false);
655 // Add the user to the front of the user list.
656 ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers);
657 prefs_users_update->Insert(0, new base::StringValue(user_id));
658 users_.insert(users_.begin(), active_user_);
660 // Now that user is in the list, save display name.
661 if (IsCurrentUserNew()) {
662 SaveUserDisplayName(GetActiveUser()->email(),
663 GetActiveUser()->GetDisplayName());
666 GetUserImageManager(user_id)->UserLoggedIn(IsCurrentUserNew(), true);
667 WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded();
669 // Make sure that new data is persisted to Local State.
670 GetLocalState()->CommitPendingWrite();
673 void ChromeUserManagerImpl::PublicAccountUserLoggedIn(
674 user_manager::User* user) {
675 SetIsCurrentUserNew(true);
678 // The UserImageManager chooses a random avatar picture when a user logs in
679 // for the first time. Tell the UserImageManager that this user is not new to
680 // prevent the avatar from getting changed.
681 GetUserImageManager(user->email())->UserLoggedIn(false, true);
682 WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded();
685 void ChromeUserManagerImpl::KioskAppLoggedIn(const std::string& app_id) {
686 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
687 policy::DeviceLocalAccount::Type device_local_account_type;
688 DCHECK(policy::IsDeviceLocalAccountUser(app_id, &device_local_account_type));
689 DCHECK_EQ(policy::DeviceLocalAccount::TYPE_KIOSK_APP,
690 device_local_account_type);
692 active_user_ = user_manager::User::CreateKioskAppUser(app_id);
693 active_user_->SetStubImage(
694 user_manager::UserImage(
695 *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
696 IDR_PROFILE_PICTURE_LOADING)),
697 user_manager::User::USER_IMAGE_INVALID,
700 WallpaperManager::Get()->SetUserWallpaperNow(app_id);
702 // TODO(bartfab): Add KioskAppUsers to the users_ list and keep metadata like
703 // the kiosk_app_id in these objects, removing the need to re-parse the
704 // device-local account list here to extract the kiosk_app_id.
705 const std::vector<policy::DeviceLocalAccount> device_local_accounts =
706 policy::GetDeviceLocalAccounts(cros_settings_);
707 const policy::DeviceLocalAccount* account = NULL;
708 for (std::vector<policy::DeviceLocalAccount>::const_iterator it =
709 device_local_accounts.begin();
710 it != device_local_accounts.end();
712 if (it->user_id == app_id) {
717 std::string kiosk_app_id;
719 kiosk_app_id = account->kiosk_app_id;
721 LOG(ERROR) << "Logged into nonexistent kiosk-app account: " << app_id;
725 CommandLine* command_line = CommandLine::ForCurrentProcess();
726 command_line->AppendSwitch(::switches::kForceAppMode);
727 command_line->AppendSwitchASCII(::switches::kAppId, kiosk_app_id);
729 // Disable window animation since kiosk app runs in a single full screen
730 // window and window animation causes start-up janks.
731 command_line->AppendSwitch(wm::switches::kWindowAnimationsDisabled);
734 void ChromeUserManagerImpl::DemoAccountLoggedIn() {
735 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
737 user_manager::User::CreateKioskAppUser(DemoAppLauncher::kDemoUserName);
738 active_user_->SetStubImage(
739 user_manager::UserImage(
740 *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
741 IDR_PROFILE_PICTURE_LOADING)),
742 user_manager::User::USER_IMAGE_INVALID,
744 WallpaperManager::Get()->SetUserWallpaperNow(DemoAppLauncher::kDemoUserName);
746 CommandLine* command_line = CommandLine::ForCurrentProcess();
747 command_line->AppendSwitch(::switches::kForceAppMode);
748 command_line->AppendSwitchASCII(::switches::kAppId,
749 DemoAppLauncher::kDemoAppId);
751 // Disable window animation since the demo app runs in a single full screen
752 // window and window animation causes start-up janks.
753 CommandLine::ForCurrentProcess()->AppendSwitch(
754 wm::switches::kWindowAnimationsDisabled);
757 void ChromeUserManagerImpl::RetailModeUserLoggedIn() {
758 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
759 SetIsCurrentUserNew(true);
760 active_user_ = user_manager::User::CreateRetailModeUser();
761 GetUserImageManager(chromeos::login::kRetailModeUserName)
762 ->UserLoggedIn(IsCurrentUserNew(), true);
763 WallpaperManager::Get()->SetUserWallpaperNow(
764 chromeos::login::kRetailModeUserName);
767 void ChromeUserManagerImpl::NotifyOnLogin() {
768 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
770 UserSessionManager::OverrideHomedir();
771 UpdateNumberOfUsers();
773 ChromeUserManager::NotifyOnLogin();
775 // TODO(nkostylev): Deprecate this notification in favor of
776 // ActiveUserChanged() observer call.
777 content::NotificationService::current()->Notify(
778 chrome::NOTIFICATION_LOGIN_USER_CHANGED,
779 content::Source<UserManager>(this),
780 content::Details<const user_manager::User>(GetActiveUser()));
782 UserSessionManager::GetInstance()->PerformPostUserLoggedInActions();
785 void ChromeUserManagerImpl::UpdateOwnership() {
786 bool is_owner = DeviceSettingsService::Get()->HasPrivateOwnerKey();
787 VLOG(1) << "Current user " << (is_owner ? "is owner" : "is not owner");
789 SetCurrentUserIsOwner(is_owner);
792 void ChromeUserManagerImpl::RemoveNonCryptohomeData(
793 const std::string& user_id) {
794 ChromeUserManager::RemoveNonCryptohomeData(user_id);
796 WallpaperManager::Get()->RemoveUserWallpaperInfo(user_id);
797 GetUserImageManager(user_id)->DeleteUserImage();
799 supervised_user_manager_->RemoveNonCryptohomeData(user_id);
801 multi_profile_user_controller_->RemoveCachedValues(user_id);
805 ChromeUserManagerImpl::CleanUpPublicAccountNonCryptohomeDataPendingRemoval() {
806 PrefService* local_state = GetLocalState();
807 const std::string public_account_pending_data_removal =
808 local_state->GetString(kPublicAccountPendingDataRemoval);
809 if (public_account_pending_data_removal.empty() ||
811 public_account_pending_data_removal == GetActiveUser()->email())) {
815 RemoveNonCryptohomeData(public_account_pending_data_removal);
816 local_state->ClearPref(kPublicAccountPendingDataRemoval);
819 void ChromeUserManagerImpl::CleanUpPublicAccountNonCryptohomeData(
820 const std::vector<std::string>& old_public_accounts) {
821 std::set<std::string> users;
822 for (user_manager::UserList::const_iterator it = users_.begin();
825 users.insert((*it)->email());
827 // If the user is logged into a public account that has been removed from the
828 // user list, mark the account's data as pending removal after logout.
829 if (IsLoggedInAsPublicAccount()) {
830 const std::string active_user_id = GetActiveUser()->email();
831 if (users.find(active_user_id) == users.end()) {
832 GetLocalState()->SetString(kPublicAccountPendingDataRemoval,
834 users.insert(active_user_id);
838 // Remove the data belonging to any other public accounts that are no longer
839 // found on the user list.
840 for (std::vector<std::string>::const_iterator it =
841 old_public_accounts.begin();
842 it != old_public_accounts.end();
844 if (users.find(*it) == users.end())
845 RemoveNonCryptohomeData(*it);
849 bool ChromeUserManagerImpl::UpdateAndCleanUpPublicAccounts(
850 const std::vector<policy::DeviceLocalAccount>& device_local_accounts) {
851 // Try to remove any public account data marked as pending removal.
852 CleanUpPublicAccountNonCryptohomeDataPendingRemoval();
854 // Get the current list of public accounts.
855 std::vector<std::string> old_public_accounts;
856 for (user_manager::UserList::const_iterator it = users_.begin();
859 if ((*it)->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT)
860 old_public_accounts.push_back((*it)->email());
863 // Get the new list of public accounts from policy.
864 std::vector<std::string> new_public_accounts;
865 for (std::vector<policy::DeviceLocalAccount>::const_iterator it =
866 device_local_accounts.begin();
867 it != device_local_accounts.end();
869 // TODO(mnissler, nkostylev, bartfab): Process Kiosk Apps within the
870 // standard login framework: http://crbug.com/234694
871 if (it->type == policy::DeviceLocalAccount::TYPE_PUBLIC_SESSION)
872 new_public_accounts.push_back(it->user_id);
875 // If the list of public accounts has not changed, return.
876 if (new_public_accounts.size() == old_public_accounts.size()) {
877 bool changed = false;
878 for (size_t i = 0; i < new_public_accounts.size(); ++i) {
879 if (new_public_accounts[i] != old_public_accounts[i]) {
888 // Persist the new list of public accounts in a pref.
889 ListPrefUpdate prefs_public_accounts_update(GetLocalState(), kPublicAccounts);
890 prefs_public_accounts_update->Clear();
891 for (std::vector<std::string>::const_iterator it =
892 new_public_accounts.begin();
893 it != new_public_accounts.end();
895 prefs_public_accounts_update->AppendString(*it);
898 // Remove the old public accounts from the user list.
899 for (user_manager::UserList::iterator it = users_.begin();
900 it != users_.end();) {
901 if ((*it)->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT) {
902 if (*it != GetLoggedInUser())
904 it = users_.erase(it);
910 // Add the new public accounts to the front of the user list.
911 for (std::vector<std::string>::const_reverse_iterator it =
912 new_public_accounts.rbegin();
913 it != new_public_accounts.rend();
915 if (IsLoggedInAsPublicAccount() && *it == GetActiveUser()->email())
916 users_.insert(users_.begin(), GetLoggedInUser());
918 users_.insert(users_.begin(),
919 user_manager::User::CreatePublicAccountUser(*it));
920 UpdatePublicAccountDisplayName(*it);
923 for (user_manager::UserList::iterator
925 ue = users_.begin() + new_public_accounts.size();
928 GetUserImageManager((*ui)->email())->LoadUserImage();
931 // Remove data belonging to public accounts that are no longer found on the
933 CleanUpPublicAccountNonCryptohomeData(old_public_accounts);
938 void ChromeUserManagerImpl::UpdatePublicAccountDisplayName(
939 const std::string& user_id) {
940 std::string display_name;
942 if (device_local_account_policy_service_) {
943 policy::DeviceLocalAccountPolicyBroker* broker =
944 device_local_account_policy_service_->GetBrokerForUser(user_id);
946 display_name = broker->GetDisplayName();
949 // Set or clear the display name.
950 SaveUserDisplayName(user_id, base::UTF8ToUTF16(display_name));
953 UserFlow* ChromeUserManagerImpl::GetCurrentUserFlow() const {
954 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
955 if (!IsUserLoggedIn())
956 return GetDefaultUserFlow();
957 return GetUserFlow(GetLoggedInUser()->email());
960 UserFlow* ChromeUserManagerImpl::GetUserFlow(const std::string& user_id) const {
961 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
962 FlowMap::const_iterator it = specific_flows_.find(user_id);
963 if (it != specific_flows_.end())
965 return GetDefaultUserFlow();
968 void ChromeUserManagerImpl::SetUserFlow(const std::string& user_id,
970 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
971 ResetUserFlow(user_id);
972 specific_flows_[user_id] = flow;
975 void ChromeUserManagerImpl::ResetUserFlow(const std::string& user_id) {
976 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
977 FlowMap::iterator it = specific_flows_.find(user_id);
978 if (it != specific_flows_.end()) {
980 specific_flows_.erase(it);
984 bool ChromeUserManagerImpl::AreSupervisedUsersAllowed() const {
985 bool supervised_users_allowed = false;
986 cros_settings_->GetBoolean(kAccountsPrefSupervisedUsersEnabled,
987 &supervised_users_allowed);
988 return supervised_users_allowed;
991 UserFlow* ChromeUserManagerImpl::GetDefaultUserFlow() const {
992 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
993 if (!default_flow_.get())
994 default_flow_.reset(new DefaultUserFlow());
995 return default_flow_.get();
998 void ChromeUserManagerImpl::NotifyUserListChanged() {
999 content::NotificationService::current()->Notify(
1000 chrome::NOTIFICATION_USER_LIST_CHANGED,
1001 content::Source<UserManager>(this),
1002 content::NotificationService::NoDetails());
1005 void ChromeUserManagerImpl::NotifyUserAddedToSession(
1006 const user_manager::User* added_user,
1007 bool user_switch_pending) {
1008 if (user_switch_pending)
1009 SetPendingUserSwitchID(added_user->email());
1011 UpdateNumberOfUsers();
1012 ChromeUserManager::NotifyUserAddedToSession(added_user, user_switch_pending);
1015 void ChromeUserManagerImpl::OnUserNotAllowed(const std::string& user_email) {
1016 LOG(ERROR) << "Shutdown session because a user is not allowed to be in the "
1018 chromeos::ShowMultiprofilesSessionAbortedDialog(user_email);
1021 void ChromeUserManagerImpl::UpdateNumberOfUsers() {
1022 size_t users = GetLoggedInUsers().size();
1024 // Write the user number as UMA stat when a multi user session is possible.
1025 if ((users + GetUsersAdmittedForMultiProfile().size()) > 1)
1026 ash::MultiProfileUMA::RecordUserCount(users);
1029 base::debug::SetCrashKeyValue(
1030 crash_keys::kNumberOfUsers,
1031 base::StringPrintf("%" PRIuS, GetLoggedInUsers().size()));
1034 } // namespace chromeos