Upstream version 10.38.208.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / chromeos / login / users / chrome_user_manager_impl.cc
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.
4
5 #include "chrome/browser/chromeos/login/users/chrome_user_manager_impl.h"
6
7 #include <cstddef>
8 #include <set>
9
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"
60
61 using content::BrowserThread;
62
63 namespace chromeos {
64 namespace {
65
66 // A vector pref of the the regular users known on this device, arranged in LRU
67 // order.
68 const char kRegularUsers[] = "LoggedInUsers";
69
70 // A vector pref of the public accounts defined on this device.
71 const char kPublicAccounts[] = "PublicAccounts";
72
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";
78
79 }  // namespace
80
81 // static
82 void ChromeUserManagerImpl::RegisterPrefs(PrefRegistrySimple* registry) {
83   ChromeUserManager::RegisterPrefs(registry);
84
85   registry->RegisterListPref(kPublicAccounts);
86   registry->RegisterStringPref(kPublicAccountPendingDataRemoval, std::string());
87   SupervisedUserManager::RegisterPrefs(registry);
88   SessionLengthLimiter::RegisterPrefs(registry);
89 }
90
91 // static
92 scoped_ptr<ChromeUserManager> ChromeUserManagerImpl::CreateChromeUserManager() {
93   return scoped_ptr<ChromeUserManager>(new ChromeUserManagerImpl());
94 }
95
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();
104
105   // UserManager instance should be used only on UI thread.
106   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
107   registrar_.Add(this,
108                  chrome::NOTIFICATION_OWNERSHIP_STATUS_CHANGED,
109                  content::NotificationService::AllSources());
110   registrar_.Add(this,
111                  chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED,
112                  content::NotificationService::AllSources());
113   registrar_.Add(this,
114                  chrome::NOTIFICATION_PROFILE_CREATED,
115                  content::NotificationService::AllSources());
116
117   // Since we're in ctor postpone any actions till this is fully created.
118   if (base::MessageLoop::current()) {
119     base::MessageLoop::current()->PostTask(
120         FROM_HERE,
121         base::Bind(&ChromeUserManagerImpl::RetrieveTrustedDevicePolicies,
122                    weak_factory_.GetWeakPtr()));
123   }
124
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()));
131
132   policy::BrowserPolicyConnectorChromeOS* connector =
133       g_browser_process->platform_part()->browser_policy_connector_chromeos();
134   avatar_policy_observer_.reset(new policy::CloudExternalDataPolicyObserver(
135       cros_settings_,
136       connector->GetDeviceLocalAccountPolicyService(),
137       policy::key::kUserAvatarImage,
138       this));
139   avatar_policy_observer_->Init();
140
141   wallpaper_policy_observer_.reset(new policy::CloudExternalDataPolicyObserver(
142       cros_settings_,
143       connector->GetDeviceLocalAccountPolicyService(),
144       policy::key::kWallpaperImage,
145       this));
146   wallpaper_policy_observer_->Init();
147 }
148
149 ChromeUserManagerImpl::~ChromeUserManagerImpl() {
150 }
151
152 void ChromeUserManagerImpl::Shutdown() {
153   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
154   ChromeUserManager::Shutdown();
155
156   local_accounts_subscription_.reset();
157
158   // Stop the session length limiter.
159   session_length_limiter_.reset();
160
161   if (device_local_account_policy_service_)
162     device_local_account_policy_service_->RemoveObserver(this);
163
164   for (UserImageManagerMap::iterator it = user_image_managers_.begin(),
165                                      ie = user_image_managers_.end();
166        it != ie;
167        ++it) {
168     it->second->Shutdown();
169   }
170   multi_profile_user_controller_.reset();
171   avatar_policy_observer_.reset();
172   wallpaper_policy_observer_.reset();
173   registrar_.RemoveAll();
174 }
175
176 MultiProfileUserController*
177 ChromeUserManagerImpl::GetMultiProfileUserController() {
178   return multi_profile_user_controller_.get();
179 }
180
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;
188   return mgr.get();
189 }
190
191 SupervisedUserManager* ChromeUserManagerImpl::GetSupervisedUserManager() {
192   return supervised_user_manager_.get();
193 }
194
195 user_manager::UserList ChromeUserManagerImpl::GetUsersAdmittedForMultiProfile()
196     const {
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();
201   }
202
203   user_manager::UserList result;
204   const user_manager::UserList& users = GetUsers();
205   for (user_manager::UserList::const_iterator it = users.begin();
206        it != users.end();
207        ++it) {
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(),
212                                                              &check);
213       if (check ==
214           MultiProfileUserController::NOT_ALLOWED_PRIMARY_USER_POLICY_FORBIDS) {
215         return user_manager::UserList();
216       }
217
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);
222     }
223   }
224
225   return result;
226 }
227
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();
232
233   user_manager::UserList unlock_users;
234   Profile* profile =
235       ProfileHelper::Get()->GetProfileByUserUnsafe(GetPrimaryUser());
236   std::string primary_behavior =
237       profile->GetPrefs()->GetString(prefs::kMultiProfileUserBehavior);
238
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_);
245   } else {
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();
249          ++it) {
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 &&
255           user->can_lock()) {
256         unlock_users.push_back(user);
257       } else if (behavior == MultiProfileUserController::kBehaviorPrimaryOnly) {
258         NOTREACHED()
259             << "Spotted primary-only multi-profile policy for non-primary user";
260       }
261     }
262   }
263
264   return unlock_users;
265 }
266
267 void ChromeUserManagerImpl::SessionStarted() {
268   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
269   ChromeUserManager::SessionStarted();
270
271   content::NotificationService::current()->Notify(
272       chrome::NOTIFICATION_SESSION_STARTED,
273       content::Source<UserManager>(this),
274       content::Details<const user_manager::User>(GetActiveUser()));
275 }
276
277 void ChromeUserManagerImpl::RemoveUserInternal(
278     const std::string& user_email,
279     user_manager::RemoveUserDelegate* delegate) {
280   CrosSettings* cros_settings = CrosSettings::Get();
281
282   const base::Closure& callback =
283       base::Bind(&ChromeUserManagerImpl::RemoveUserInternal,
284                  weak_factory_.GetWeakPtr(),
285                  user_email,
286                  delegate);
287
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.
293     return;
294   }
295   std::string owner;
296   cros_settings->GetString(kDeviceOwner, &owner);
297   if (user_email == owner) {
298     // Owner is not allowed to be removed from the device.
299     return;
300   }
301   RemoveNonOwnerUserInternal(user_email, delegate);
302 }
303
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);
309
310   GetUserFlow(user_id)->HandleOAuthTokenStatusChange(oauth_token_status);
311 }
312
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);
318
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);
323 }
324
325 void ChromeUserManagerImpl::StopPolicyObserverForTesting() {
326   avatar_policy_observer_.reset();
327   wallpaper_policy_observer_.reset();
328 }
329
330 void ChromeUserManagerImpl::Observe(
331     int type,
332     const content::NotificationSource& source,
333     const content::NotificationDetails& details) {
334   switch (type) {
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);
344       }
345       RetrieveTrustedDevicePolicies();
346       UpdateOwnership();
347       break;
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);
355
356         if (!profile->IsOffTheRecord()) {
357           AuthSyncObserver* sync_observer =
358               AuthSyncObserverFactory::GetInstance()->GetForProfile(profile);
359           sync_observer->StartObserving();
360           multi_profile_user_controller_->StartObserving(profile);
361         }
362       }
363       break;
364     }
365     case chrome::NOTIFICATION_PROFILE_CREATED: {
366       Profile* profile = content::Source<Profile>(source).ptr();
367       user_manager::User* user =
368           ProfileHelper::Get()->GetUserByProfile(profile);
369       if (user != NULL)
370         user->set_profile_is_created();
371
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(
379             FROM_HERE,
380             base::Bind(&ChromeUserManagerImpl::SwitchActiveUser,
381                        weak_factory_.GetWeakPtr(),
382                        GetPendingUserSwitchID()));
383         SetPendingUserSwitchID(std::string());
384       }
385       break;
386     }
387     default:
388       NOTREACHED();
389   }
390 }
391
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);
398   else
399     NOTREACHED();
400 }
401
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);
408   else
409     NOTREACHED();
410 }
411
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());
420   else
421     NOTREACHED();
422 }
423
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)
427     return;
428   UpdatePublicAccountDisplayName(user_id);
429 }
430
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.
434 }
435
436 bool ChromeUserManagerImpl::CanCurrentUserLock() const {
437   return ChromeUserManager::CanCurrentUserLock() &&
438          GetCurrentUserFlow()->CanLockScreen();
439 }
440
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);
446
447   return !is_obsolete_public_account &&
448          ChromeUserManager::IsUserNonCryptohomeDataEphemeral(user_id);
449 }
450
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());
456 }
457
458 const std::string& ChromeUserManagerImpl::GetApplicationLocale() const {
459   return g_browser_process->GetApplicationLocale();
460 }
461
462 PrefService* ChromeUserManagerImpl::GetLocalState() const {
463   return g_browser_process ? g_browser_process->local_state() : NULL;
464 }
465
466 void ChromeUserManagerImpl::HandleUserOAuthTokenStatusChange(
467     const std::string& user_id,
468     user_manager::User::OAuthTokenStatus status) const {
469   GetUserFlow(user_id)->HandleOAuthTokenStatusChange(status);
470 }
471
472 bool ChromeUserManagerImpl::IsEnterpriseManaged() const {
473   policy::BrowserPolicyConnectorChromeOS* connector =
474       g_browser_process->platform_part()->browser_policy_connector_chromeos();
475   return connector->IsEnterpriseManaged();
476 }
477
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>(),
485                 &public_sessions,
486                 public_sessions_set);
487   for (std::vector<std::string>::const_iterator it = public_sessions.begin();
488        it != public_sessions.end();
489        ++it) {
490     users_.push_back(user_manager::User::CreatePublicAccountUser(*it));
491     UpdatePublicAccountDisplayName(*it);
492   }
493 }
494
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();
501 }
502
503 void ChromeUserManagerImpl::PerformPostUserListLoadingActions() {
504   for (user_manager::UserList::iterator ui = users_.begin(), ue = users_.end();
505        ui != ue;
506        ++ui) {
507     GetUserImageManager((*ui)->email())->LoadUserImage();
508   }
509 }
510
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));
517 }
518
519 bool ChromeUserManagerImpl::IsDemoApp(const std::string& user_id) const {
520   return DemoAppLauncher::IsDemoAppSession(user_id);
521 }
522
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;
529 }
530
531 bool ChromeUserManagerImpl::IsPublicAccountMarkedForRemoval(
532     const std::string& user_id) const {
533   return user_id ==
534          GetLocalState()->GetString(kPublicAccountPendingDataRemoval);
535 }
536
537 void ChromeUserManagerImpl::RetrieveTrustedDevicePolicies() {
538   // Local state may not be initialized in unit_tests.
539   if (!GetLocalState())
540     return;
541
542   SetEphemeralUsersEnabled(false);
543   SetOwnerEmail(std::string());
544
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()))) {
550     return;
551   }
552
553   bool ephemeral_users_enabled = false;
554   cros_settings_->GetBoolean(kAccountsPrefEphemeralUsersEnabled,
555                              &ephemeral_users_enabled);
556   SetEphemeralUsersEnabled(ephemeral_users_enabled);
557
558   std::string owner_email;
559   cros_settings_->GetString(kDeviceOwner, &owner_email);
560   SetOwnerEmail(owner_email);
561
562   EnsureUsersLoaded();
563
564   bool changed = UpdateAndCleanUpPublicAccounts(
565       policy::GetDeviceLocalAccounts(cros_settings_));
566
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);
578         DeleteUser(*it);
579         it = users_.erase(it);
580         changed = true;
581       } else {
582         if ((*it)->GetType() != user_manager::USER_TYPE_PUBLIC_ACCOUNT)
583           prefs_users_update->Append(new base::StringValue(user_email));
584         ++it;
585       }
586     }
587   }
588
589   if (changed)
590     NotifyUserListChanged();
591 }
592
593 void ChromeUserManagerImpl::GuestUserLoggedIn() {
594   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
595   ChromeUserManager::GuestUserLoggedIn();
596
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,
605       false);
606
607   // Initializes wallpaper after active_user_ is set.
608   WallpaperManager::Get()->SetUserWallpaperNow(chromeos::login::kGuestUserName);
609 }
610
611 void ChromeUserManagerImpl::RegularUserLoggedIn(const std::string& user_id) {
612   ChromeUserManager::RegularUserLoggedIn(user_id);
613
614   if (IsCurrentUserNew())
615     WallpaperManager::Get()->SetUserWallpaperNow(user_id);
616
617   GetUserImageManager(user_id)->UserLoggedIn(IsCurrentUserNew(), false);
618
619   WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded();
620
621   // Make sure that new data is persisted to Local State.
622   GetLocalState()->CommitPendingWrite();
623 }
624
625 void ChromeUserManagerImpl::RegularUserLoggedInAsEphemeral(
626     const std::string& user_id) {
627   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
628   ChromeUserManager::RegularUserLoggedInAsEphemeral(user_id);
629
630   GetUserImageManager(user_id)->UserLoggedIn(IsCurrentUserNew(), false);
631   WallpaperManager::Get()->SetUserWallpaperNow(user_id);
632 }
633
634 void ChromeUserManagerImpl::SupervisedUserLoggedIn(const std::string& user_id) {
635   // TODO(nkostylev): Refactor, share code with RegularUserLoggedIn().
636
637   // Remove the user from the user list.
638   active_user_ = RemoveRegularOrSupervisedUserFromList(user_id);
639
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);
646   } else {
647     if (supervised_user_manager_->CheckForFirstRun(user_id)) {
648       SetIsCurrentUserNew(true);
649       WallpaperManager::Get()->SetUserWallpaperNow(user_id);
650     } else {
651       SetIsCurrentUserNew(false);
652     }
653   }
654
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_);
659
660   // Now that user is in the list, save display name.
661   if (IsCurrentUserNew()) {
662     SaveUserDisplayName(GetActiveUser()->email(),
663                         GetActiveUser()->GetDisplayName());
664   }
665
666   GetUserImageManager(user_id)->UserLoggedIn(IsCurrentUserNew(), true);
667   WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded();
668
669   // Make sure that new data is persisted to Local State.
670   GetLocalState()->CommitPendingWrite();
671 }
672
673 void ChromeUserManagerImpl::PublicAccountUserLoggedIn(
674     user_manager::User* user) {
675   SetIsCurrentUserNew(true);
676   active_user_ = user;
677
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();
683 }
684
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);
691
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,
698       false);
699
700   WallpaperManager::Get()->SetUserWallpaperNow(app_id);
701
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();
711        ++it) {
712     if (it->user_id == app_id) {
713       account = &*it;
714       break;
715     }
716   }
717   std::string kiosk_app_id;
718   if (account) {
719     kiosk_app_id = account->kiosk_app_id;
720   } else {
721     LOG(ERROR) << "Logged into nonexistent kiosk-app account: " << app_id;
722     NOTREACHED();
723   }
724
725   CommandLine* command_line = CommandLine::ForCurrentProcess();
726   command_line->AppendSwitch(::switches::kForceAppMode);
727   command_line->AppendSwitchASCII(::switches::kAppId, kiosk_app_id);
728
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);
732 }
733
734 void ChromeUserManagerImpl::DemoAccountLoggedIn() {
735   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
736   active_user_ =
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,
743       false);
744   WallpaperManager::Get()->SetUserWallpaperNow(DemoAppLauncher::kDemoUserName);
745
746   CommandLine* command_line = CommandLine::ForCurrentProcess();
747   command_line->AppendSwitch(::switches::kForceAppMode);
748   command_line->AppendSwitchASCII(::switches::kAppId,
749                                   DemoAppLauncher::kDemoAppId);
750
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);
755 }
756
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);
765 }
766
767 void ChromeUserManagerImpl::NotifyOnLogin() {
768   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
769
770   UserSessionManager::OverrideHomedir();
771   UpdateNumberOfUsers();
772
773   ChromeUserManager::NotifyOnLogin();
774
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()));
781
782   UserSessionManager::GetInstance()->PerformPostUserLoggedInActions();
783 }
784
785 void ChromeUserManagerImpl::UpdateOwnership() {
786   bool is_owner = DeviceSettingsService::Get()->HasPrivateOwnerKey();
787   VLOG(1) << "Current user " << (is_owner ? "is owner" : "is not owner");
788
789   SetCurrentUserIsOwner(is_owner);
790 }
791
792 void ChromeUserManagerImpl::RemoveNonCryptohomeData(
793     const std::string& user_id) {
794   ChromeUserManager::RemoveNonCryptohomeData(user_id);
795
796   WallpaperManager::Get()->RemoveUserWallpaperInfo(user_id);
797   GetUserImageManager(user_id)->DeleteUserImage();
798
799   supervised_user_manager_->RemoveNonCryptohomeData(user_id);
800
801   multi_profile_user_controller_->RemoveCachedValues(user_id);
802 }
803
804 void
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() ||
810       (IsUserLoggedIn() &&
811        public_account_pending_data_removal == GetActiveUser()->email())) {
812     return;
813   }
814
815   RemoveNonCryptohomeData(public_account_pending_data_removal);
816   local_state->ClearPref(kPublicAccountPendingDataRemoval);
817 }
818
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();
823        it != users_.end();
824        ++it)
825     users.insert((*it)->email());
826
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,
833                                  active_user_id);
834       users.insert(active_user_id);
835     }
836   }
837
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();
843        ++it) {
844     if (users.find(*it) == users.end())
845       RemoveNonCryptohomeData(*it);
846   }
847 }
848
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();
853
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();
857        it != users_.end();
858        ++it) {
859     if ((*it)->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT)
860       old_public_accounts.push_back((*it)->email());
861   }
862
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();
868        ++it) {
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);
873   }
874
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]) {
880         changed = true;
881         break;
882       }
883     }
884     if (!changed)
885       return false;
886   }
887
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();
894        ++it) {
895     prefs_public_accounts_update->AppendString(*it);
896   }
897
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())
903         DeleteUser(*it);
904       it = users_.erase(it);
905     } else {
906       ++it;
907     }
908   }
909
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();
914        ++it) {
915     if (IsLoggedInAsPublicAccount() && *it == GetActiveUser()->email())
916       users_.insert(users_.begin(), GetLoggedInUser());
917     else
918       users_.insert(users_.begin(),
919                     user_manager::User::CreatePublicAccountUser(*it));
920     UpdatePublicAccountDisplayName(*it);
921   }
922
923   for (user_manager::UserList::iterator
924            ui = users_.begin(),
925            ue = users_.begin() + new_public_accounts.size();
926        ui != ue;
927        ++ui) {
928     GetUserImageManager((*ui)->email())->LoadUserImage();
929   }
930
931   // Remove data belonging to public accounts that are no longer found on the
932   // user list.
933   CleanUpPublicAccountNonCryptohomeData(old_public_accounts);
934
935   return true;
936 }
937
938 void ChromeUserManagerImpl::UpdatePublicAccountDisplayName(
939     const std::string& user_id) {
940   std::string display_name;
941
942   if (device_local_account_policy_service_) {
943     policy::DeviceLocalAccountPolicyBroker* broker =
944         device_local_account_policy_service_->GetBrokerForUser(user_id);
945     if (broker)
946       display_name = broker->GetDisplayName();
947   }
948
949   // Set or clear the display name.
950   SaveUserDisplayName(user_id, base::UTF8ToUTF16(display_name));
951 }
952
953 UserFlow* ChromeUserManagerImpl::GetCurrentUserFlow() const {
954   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
955   if (!IsUserLoggedIn())
956     return GetDefaultUserFlow();
957   return GetUserFlow(GetLoggedInUser()->email());
958 }
959
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())
964     return it->second;
965   return GetDefaultUserFlow();
966 }
967
968 void ChromeUserManagerImpl::SetUserFlow(const std::string& user_id,
969                                         UserFlow* flow) {
970   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
971   ResetUserFlow(user_id);
972   specific_flows_[user_id] = flow;
973 }
974
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()) {
979     delete it->second;
980     specific_flows_.erase(it);
981   }
982 }
983
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;
989 }
990
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();
996 }
997
998 void ChromeUserManagerImpl::NotifyUserListChanged() {
999   content::NotificationService::current()->Notify(
1000       chrome::NOTIFICATION_USER_LIST_CHANGED,
1001       content::Source<UserManager>(this),
1002       content::NotificationService::NoDetails());
1003 }
1004
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());
1010
1011   UpdateNumberOfUsers();
1012   ChromeUserManager::NotifyUserAddedToSession(added_user, user_switch_pending);
1013 }
1014
1015 void ChromeUserManagerImpl::OnUserNotAllowed(const std::string& user_email) {
1016   LOG(ERROR) << "Shutdown session because a user is not allowed to be in the "
1017                 "current session";
1018   chromeos::ShowMultiprofilesSessionAbortedDialog(user_email);
1019 }
1020
1021 void ChromeUserManagerImpl::UpdateNumberOfUsers() {
1022   size_t users = GetLoggedInUsers().size();
1023   if (users) {
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);
1027   }
1028
1029   base::debug::SetCrashKeyValue(
1030       crash_keys::kNumberOfUsers,
1031       base::StringPrintf("%" PRIuS, GetLoggedInUsers().size()));
1032 }
1033
1034 }  // namespace chromeos