Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / chromeos / login / user_manager_impl.cc
1 // Copyright (c) 2013 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/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/files/file_path.h"
16 #include "base/format_macros.h"
17 #include "base/logging.h"
18 #include "base/metrics/histogram.h"
19 #include "base/prefs/pref_registry_simple.h"
20 #include "base/prefs/pref_service.h"
21 #include "base/prefs/scoped_user_pref_update.h"
22 #include "base/rand_util.h"
23 #include "base/strings/string_util.h"
24 #include "base/strings/stringprintf.h"
25 #include "base/strings/utf_string_conversions.h"
26 #include "base/sys_info.h"
27 #include "base/threading/worker_pool.h"
28 #include "base/values.h"
29 #include "chrome/browser/app_mode/app_mode_utils.h"
30 #include "chrome/browser/browser_process.h"
31 #include "chrome/browser/chrome_notification_types.h"
32 #include "chrome/browser/chromeos/base/locale_util.h"
33 #include "chrome/browser/chromeos/login/auth_sync_observer.h"
34 #include "chrome/browser/chromeos/login/auth_sync_observer_factory.h"
35 #include "chrome/browser/chromeos/login/demo_mode/demo_app_launcher.h"
36 #include "chrome/browser/chromeos/login/login_display.h"
37 #include "chrome/browser/chromeos/login/login_utils.h"
38 #include "chrome/browser/chromeos/login/multi_profile_user_controller.h"
39 #include "chrome/browser/chromeos/login/remove_user_delegate.h"
40 #include "chrome/browser/chromeos/login/supervised_user_manager_impl.h"
41 #include "chrome/browser/chromeos/login/user_image_manager_impl.h"
42 #include "chrome/browser/chromeos/login/wizard_controller.h"
43 #include "chrome/browser/chromeos/net/network_portal_detector.h"
44 #include "chrome/browser/chromeos/net/network_portal_detector_strategy.h"
45 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
46 #include "chrome/browser/chromeos/policy/device_local_account.h"
47 #include "chrome/browser/chromeos/profiles/multiprofiles_session_aborted_dialog.h"
48 #include "chrome/browser/chromeos/profiles/profile_helper.h"
49 #include "chrome/browser/chromeos/session_length_limiter.h"
50 #include "chrome/browser/managed_mode/chromeos/managed_user_password_service_factory.h"
51 #include "chrome/browser/managed_mode/chromeos/manager_password_service_factory.h"
52 #include "chrome/browser/net/nss_context.h"
53 #include "chrome/browser/profiles/profile.h"
54 #include "chrome/browser/profiles/profile_manager.h"
55 #include "chrome/browser/sync/profile_sync_service.h"
56 #include "chrome/browser/sync/profile_sync_service_factory.h"
57 #include "chrome/common/chrome_constants.h"
58 #include "chrome/common/chrome_switches.h"
59 #include "chrome/common/crash_keys.h"
60 #include "chrome/common/pref_names.h"
61 #include "chromeos/cert_loader.h"
62 #include "chromeos/chromeos_switches.h"
63 #include "chromeos/cryptohome/async_method_caller.h"
64 #include "chromeos/dbus/dbus_thread_manager.h"
65 #include "chromeos/login/login_state.h"
66 #include "chromeos/settings/cros_settings_names.h"
67 #include "content/public/browser/browser_thread.h"
68 #include "content/public/browser/notification_service.h"
69 #include "google_apis/gaia/gaia_auth_util.h"
70 #include "google_apis/gaia/google_service_auth_error.h"
71 #include "policy/policy_constants.h"
72 #include "ui/base/l10n/l10n_util.h"
73 #include "ui/wm/core/wm_core_switches.h"
74
75 using content::BrowserThread;
76
77 namespace chromeos {
78 namespace {
79
80 // A vector pref of the the regular users known on this device, arranged in LRU
81 // order.
82 const char kRegularUsers[] = "LoggedInUsers";
83
84 // A vector pref of the public accounts defined on this device.
85 const char kPublicAccounts[] = "PublicAccounts";
86
87 // A string pref that gets set when a public account is removed but a user is
88 // currently logged into that account, requiring the account's data to be
89 // removed after logout.
90 const char kPublicAccountPendingDataRemoval[] =
91     "PublicAccountPendingDataRemoval";
92
93 // A dictionary that maps user IDs to the displayed name.
94 const char kUserDisplayName[] = "UserDisplayName";
95
96 // A dictionary that maps user IDs to the user's given name.
97 const char kUserGivenName[] = "UserGivenName";
98
99 // A dictionary that maps user IDs to the displayed (non-canonical) emails.
100 const char kUserDisplayEmail[] = "UserDisplayEmail";
101
102 // A dictionary that maps user IDs to OAuth token presence flag.
103 const char kUserOAuthTokenStatus[] = "OAuthTokenStatus";
104
105 // A dictionary that maps user IDs to a flag indicating whether online
106 // authentication against GAIA should be enforced during the next sign-in.
107 const char kUserForceOnlineSignin[] = "UserForceOnlineSignin";
108
109 // A string pref containing the ID of the last user who logged in if it was
110 // a regular user or an empty string if it was another type of user (guest,
111 // kiosk, public account, etc.).
112 const char kLastLoggedInRegularUser[] = "LastLoggedInRegularUser";
113
114 // Upper bound for a histogram metric reporting the amount of time between
115 // one regular user logging out and a different regular user logging in.
116 const int kLogoutToLoginDelayMaxSec = 1800;
117
118 // Callback that is called after user removal is complete.
119 void OnRemoveUserComplete(const std::string& user_email,
120                           bool success,
121                           cryptohome::MountError return_code) {
122   // Log the error, but there's not much we can do.
123   if (!success) {
124     LOG(ERROR) << "Removal of cryptohome for " << user_email
125                << " failed, return code: " << return_code;
126   }
127 }
128
129 // Helper function that copies users from |users_list| to |users_vector| and
130 // |users_set|. Duplicates and users already present in |existing_users| are
131 // skipped.
132 void ParseUserList(const base::ListValue& users_list,
133                    const std::set<std::string>& existing_users,
134                    std::vector<std::string>* users_vector,
135                    std::set<std::string>* users_set) {
136   users_vector->clear();
137   users_set->clear();
138   for (size_t i = 0; i < users_list.GetSize(); ++i) {
139     std::string email;
140     if (!users_list.GetString(i, &email) || email.empty()) {
141       LOG(ERROR) << "Corrupt entry in user list at index " << i << ".";
142       continue;
143     }
144     if (existing_users.find(email) != existing_users.end() ||
145         !users_set->insert(email).second) {
146       LOG(ERROR) << "Duplicate user: " << email;
147       continue;
148     }
149     users_vector->push_back(email);
150   }
151 }
152
153 class UserHashMatcher {
154  public:
155   explicit UserHashMatcher(const std::string& h) : username_hash(h) {}
156   bool operator()(const User* user) const {
157     return user->username_hash() == username_hash;
158   }
159
160  private:
161   const std::string& username_hash;
162 };
163
164 // Runs on SequencedWorkerPool thread. Passes resolved locale to
165 // |on_resolve_callback| on UI thread.
166 void ResolveLocale(
167     const std::string& raw_locale,
168     base::Callback<void(const std::string&)> on_resolve_callback) {
169   DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI));
170   std::string resolved_locale;
171   // Ignore result
172   l10n_util::CheckAndResolveLocale(raw_locale, &resolved_locale);
173   BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
174       base::Bind(on_resolve_callback, resolved_locale));
175 }
176
177 // Callback to GetNSSCertDatabaseForProfile. It starts CertLoader using the
178 // provided NSS database. It must be called for primary user only.
179 void OnGetNSSCertDatabaseForUser(net::NSSCertDatabase* database) {
180   if (!CertLoader::IsInitialized())
181     return;
182
183   CertLoader::Get()->StartWithNSSDB(database);
184 }
185
186 }  // namespace
187
188 // static
189 void UserManager::RegisterPrefs(PrefRegistrySimple* registry) {
190   registry->RegisterListPref(kRegularUsers);
191   registry->RegisterListPref(kPublicAccounts);
192   registry->RegisterStringPref(kPublicAccountPendingDataRemoval, "");
193   registry->RegisterStringPref(kLastLoggedInRegularUser, "");
194   registry->RegisterDictionaryPref(kUserDisplayName);
195   registry->RegisterDictionaryPref(kUserGivenName);
196   registry->RegisterDictionaryPref(kUserDisplayEmail);
197   registry->RegisterDictionaryPref(kUserOAuthTokenStatus);
198   registry->RegisterDictionaryPref(kUserForceOnlineSignin);
199   SupervisedUserManager::RegisterPrefs(registry);
200   SessionLengthLimiter::RegisterPrefs(registry);
201 }
202
203 UserManagerImpl::UserManagerImpl()
204     : cros_settings_(CrosSettings::Get()),
205       device_local_account_policy_service_(NULL),
206       user_loading_stage_(STAGE_NOT_LOADED),
207       active_user_(NULL),
208       primary_user_(NULL),
209       session_started_(false),
210       user_sessions_restored_(false),
211       is_current_user_owner_(false),
212       is_current_user_new_(false),
213       is_current_user_ephemeral_regular_user_(false),
214       ephemeral_users_enabled_(false),
215       supervised_user_manager_(new SupervisedUserManagerImpl(this)),
216       manager_creation_time_(base::TimeTicks::Now()) {
217   UpdateNumberOfUsers();
218   // UserManager instance should be used only on UI thread.
219   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
220   registrar_.Add(this, chrome::NOTIFICATION_OWNERSHIP_STATUS_CHANGED,
221       content::NotificationService::AllSources());
222   registrar_.Add(this, chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED,
223       content::NotificationService::AllSources());
224   registrar_.Add(this,
225                  chrome::NOTIFICATION_PROFILE_CREATED,
226                  content::NotificationService::AllSources());
227   RetrieveTrustedDevicePolicies();
228   local_accounts_subscription_ = cros_settings_->AddSettingsObserver(
229       kAccountsPrefDeviceLocalAccounts,
230       base::Bind(&UserManagerImpl::RetrieveTrustedDevicePolicies,
231                  base::Unretained(this)));
232   supervised_users_subscription_ = cros_settings_->AddSettingsObserver(
233       kAccountsPrefSupervisedUsersEnabled,
234       base::Bind(&UserManagerImpl::RetrieveTrustedDevicePolicies,
235                  base::Unretained(this)));
236   multi_profile_user_controller_.reset(new MultiProfileUserController(
237       this, g_browser_process->local_state()));
238
239   policy::BrowserPolicyConnectorChromeOS* connector =
240       g_browser_process->platform_part()->browser_policy_connector_chromeos();
241   avatar_policy_observer_.reset(new policy::CloudExternalDataPolicyObserver(
242       cros_settings_,
243       this,
244       connector->GetDeviceLocalAccountPolicyService(),
245       policy::key::kUserAvatarImage,
246       this));
247   avatar_policy_observer_->Init();
248
249   wallpaper_policy_observer_.reset(new policy::CloudExternalDataPolicyObserver(
250       cros_settings_,
251       this,
252       connector->GetDeviceLocalAccountPolicyService(),
253       policy::key::kWallpaperImage,
254       this));
255   wallpaper_policy_observer_->Init();
256
257   UpdateLoginState();
258 }
259
260 UserManagerImpl::~UserManagerImpl() {
261   // Can't use STLDeleteElements because of the private destructor of User.
262   for (UserList::iterator it = users_.begin(); it != users_.end();
263        it = users_.erase(it)) {
264     DeleteUser(*it);
265   }
266   // These are pointers to the same User instances that were in users_ list.
267   logged_in_users_.clear();
268   lru_logged_in_users_.clear();
269
270   DeleteUser(active_user_);
271 }
272
273 void UserManagerImpl::Shutdown() {
274   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
275   local_accounts_subscription_.reset();
276   supervised_users_subscription_.reset();
277   // Stop the session length limiter.
278   session_length_limiter_.reset();
279
280   if (device_local_account_policy_service_)
281     device_local_account_policy_service_->RemoveObserver(this);
282
283   for (UserImageManagerMap::iterator it = user_image_managers_.begin(),
284                                      ie = user_image_managers_.end();
285        it != ie; ++it) {
286     it->second->Shutdown();
287   }
288   multi_profile_user_controller_.reset();
289   avatar_policy_observer_.reset();
290   wallpaper_policy_observer_.reset();
291 }
292
293 MultiProfileUserController* UserManagerImpl::GetMultiProfileUserController() {
294   return multi_profile_user_controller_.get();
295 }
296
297 UserImageManager* UserManagerImpl::GetUserImageManager(
298     const std::string& user_id) {
299   UserImageManagerMap::iterator ui = user_image_managers_.find(user_id);
300   if (ui != user_image_managers_.end())
301     return ui->second.get();
302   linked_ptr<UserImageManagerImpl> mgr(new UserImageManagerImpl(user_id, this));
303   user_image_managers_[user_id] = mgr;
304   return mgr.get();
305 }
306
307 SupervisedUserManager* UserManagerImpl::GetSupervisedUserManager() {
308   return supervised_user_manager_.get();
309 }
310
311 const UserList& UserManagerImpl::GetUsers() const {
312   const_cast<UserManagerImpl*>(this)->EnsureUsersLoaded();
313   return users_;
314 }
315
316 UserList UserManagerImpl::GetUsersAdmittedForMultiProfile() const {
317   if (!UserManager::IsMultipleProfilesAllowed())
318     return UserList();
319
320   // Supervised users are not allowed to use multi profile.
321   if (logged_in_users_.size() == 1 &&
322       GetPrimaryUser()->GetType() != User::USER_TYPE_REGULAR)
323     return UserList();
324
325   UserList result;
326   int num_users_allowed = 0;
327   const UserList& users = GetUsers();
328   for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) {
329     if ((*it)->GetType() == User::USER_TYPE_REGULAR && !(*it)->is_logged_in()) {
330       MultiProfileUserController::UserAllowedInSessionResult check =
331           multi_profile_user_controller_->
332               IsUserAllowedInSession((*it)->email());
333       if (check == MultiProfileUserController::
334               NOT_ALLOWED_PRIMARY_USER_POLICY_FORBIDS) {
335         return UserList();
336       }
337
338       // Users with a policy that prevents them being added to a session will be
339       // shown in login UI but will be grayed out.
340       if (check == MultiProfileUserController::ALLOWED ||
341           check == MultiProfileUserController::NOT_ALLOWED_POLICY_FORBIDS) {
342         result.push_back(*it);
343         if (check == MultiProfileUserController::ALLOWED)
344           num_users_allowed++;
345       }
346     }
347   }
348
349   // We only show multi-profiles sign in UI if there's at least one user that
350   // is allowed to be added to the session.
351   if (!num_users_allowed)
352     result.clear();
353
354   return result;
355 }
356
357 const UserList& UserManagerImpl::GetLoggedInUsers() const {
358   return logged_in_users_;
359 }
360
361 const UserList& UserManagerImpl::GetLRULoggedInUsers() {
362   // If there is no user logged in, we return the active user as the only one.
363   if (lru_logged_in_users_.empty() && active_user_) {
364     temp_single_logged_in_users_.clear();
365     temp_single_logged_in_users_.insert(temp_single_logged_in_users_.begin(),
366                                         active_user_);
367     return temp_single_logged_in_users_;
368   }
369   return lru_logged_in_users_;
370 }
371
372 UserList UserManagerImpl::GetUnlockUsers() const {
373   const UserList& logged_in_users = GetLoggedInUsers();
374   if (logged_in_users.empty())
375     return UserList();
376
377   UserList unlock_users;
378   Profile* profile = GetProfileByUser(primary_user_);
379   std::string primary_behavior =
380       profile->GetPrefs()->GetString(prefs::kMultiProfileUserBehavior);
381
382   // Specific case: only one logged in user or
383   // primary user has primary-only multi-profile policy.
384   if (logged_in_users.size() == 1 ||
385       primary_behavior == MultiProfileUserController::kBehaviorPrimaryOnly) {
386     if (primary_user_->can_lock())
387       unlock_users.push_back(primary_user_);
388   } else {
389     // Fill list of potential unlock users based on multi-profile policy state.
390     for (UserList::const_iterator it = logged_in_users.begin();
391          it != logged_in_users.end(); ++it) {
392       User* user = (*it);
393       Profile* profile = GetProfileByUser(user);
394       const std::string behavior =
395           profile->GetPrefs()->GetString(prefs::kMultiProfileUserBehavior);
396       if (behavior == MultiProfileUserController::kBehaviorUnrestricted &&
397           user->can_lock()) {
398         unlock_users.push_back(user);
399       } else if (behavior == MultiProfileUserController::kBehaviorPrimaryOnly) {
400         NOTREACHED()
401             << "Spotted primary-only multi-profile policy for non-primary user";
402       }
403     }
404   }
405
406   return unlock_users;
407 }
408
409 const std::string& UserManagerImpl::GetOwnerEmail() {
410   return owner_email_;
411 }
412
413 void UserManagerImpl::UserLoggedIn(const std::string& user_id,
414                                    const std::string& username_hash,
415                                    bool browser_restart) {
416   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
417
418   if (!CommandLine::ForCurrentProcess()->HasSwitch(::switches::kMultiProfiles))
419     DCHECK(!IsUserLoggedIn());
420
421   User* user = FindUserInListAndModify(user_id);
422   if (active_user_ && user) {
423     user->set_is_logged_in(true);
424     user->set_username_hash(username_hash);
425     logged_in_users_.push_back(user);
426     lru_logged_in_users_.push_back(user);
427     // Reset the new user flag if the user already exists.
428     is_current_user_new_ = false;
429     NotifyUserAddedToSession(user);
430     // Remember that we need to switch to this user as soon as profile ready.
431     pending_user_switch_ = user_id;
432     return;
433   }
434
435   policy::DeviceLocalAccount::Type device_local_account_type;
436   if (user_id == UserManager::kGuestUserName) {
437     GuestUserLoggedIn();
438   } else if (user_id == UserManager::kRetailModeUserName) {
439     RetailModeUserLoggedIn();
440   } else if (policy::IsDeviceLocalAccountUser(user_id,
441                                               &device_local_account_type) &&
442              device_local_account_type ==
443                  policy::DeviceLocalAccount::TYPE_KIOSK_APP) {
444     KioskAppLoggedIn(user_id);
445   } else if (DemoAppLauncher::IsDemoAppSession(user_id)) {
446     DemoAccountLoggedIn();
447   } else {
448     EnsureUsersLoaded();
449
450     if (user && user->GetType() == User::USER_TYPE_PUBLIC_ACCOUNT) {
451       PublicAccountUserLoggedIn(user);
452     } else if ((user && user->GetType() == User::USER_TYPE_LOCALLY_MANAGED) ||
453                (!user && gaia::ExtractDomainName(user_id) ==
454                     UserManager::kLocallyManagedUserDomain)) {
455       LocallyManagedUserLoggedIn(user_id);
456     } else if (browser_restart && user_id == g_browser_process->local_state()->
457                    GetString(kPublicAccountPendingDataRemoval)) {
458       PublicAccountUserLoggedIn(User::CreatePublicAccountUser(user_id));
459     } else if (user_id != owner_email_ && !user &&
460                (AreEphemeralUsersEnabled() || browser_restart)) {
461       RegularUserLoggedInAsEphemeral(user_id);
462     } else {
463       RegularUserLoggedIn(user_id);
464     }
465
466     // Initialize the session length limiter and start it only if
467     // session limit is defined by the policy.
468     session_length_limiter_.reset(new SessionLengthLimiter(NULL,
469                                                            browser_restart));
470   }
471   DCHECK(active_user_);
472   active_user_->set_is_logged_in(true);
473   active_user_->set_is_active(true);
474   active_user_->set_username_hash(username_hash);
475
476   // Place user who just signed in to the top of the logged in users.
477   logged_in_users_.insert(logged_in_users_.begin(), active_user_);
478   SetLRUUser(active_user_);
479
480   if (!primary_user_) {
481     primary_user_ = active_user_;
482     if (primary_user_->GetType() == User::USER_TYPE_REGULAR)
483       SendRegularUserLoginMetrics(user_id);
484   }
485
486   UMA_HISTOGRAM_ENUMERATION("UserManager.LoginUserType",
487                             active_user_->GetType(), User::NUM_USER_TYPES);
488
489   g_browser_process->local_state()->SetString(kLastLoggedInRegularUser,
490     (active_user_->GetType() == User::USER_TYPE_REGULAR) ? user_id : "");
491
492   NotifyOnLogin();
493 }
494
495 void UserManagerImpl::SwitchActiveUser(const std::string& user_id) {
496   if (!CommandLine::ForCurrentProcess()->HasSwitch(::switches::kMultiProfiles))
497     return;
498
499   User* user = FindUserAndModify(user_id);
500   if (!user) {
501     NOTREACHED() << "Switching to a non-existing user";
502     return;
503   }
504   if (user == active_user_) {
505     NOTREACHED() << "Switching to a user who is already active";
506     return;
507   }
508   if (!user->is_logged_in()) {
509     NOTREACHED() << "Switching to a user that is not logged in";
510     return;
511   }
512   if (user->GetType() != User::USER_TYPE_REGULAR) {
513     NOTREACHED() << "Switching to a non-regular user";
514     return;
515   }
516   if (user->username_hash().empty()) {
517     NOTREACHED() << "Switching to a user that doesn't have username_hash set";
518     return;
519   }
520
521   DCHECK(active_user_);
522   active_user_->set_is_active(false);
523   user->set_is_active(true);
524   active_user_ = user;
525
526   // Move the user to the front.
527   SetLRUUser(active_user_);
528
529   NotifyActiveUserHashChanged(active_user_->username_hash());
530   NotifyActiveUserChanged(active_user_);
531 }
532
533 void UserManagerImpl::RestoreActiveSessions() {
534   DBusThreadManager::Get()->GetSessionManagerClient()->RetrieveActiveSessions(
535       base::Bind(&UserManagerImpl::OnRestoreActiveSessions,
536                  base::Unretained(this)));
537 }
538
539 void UserManagerImpl::SessionStarted() {
540   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
541   session_started_ = true;
542   UpdateLoginState();
543   content::NotificationService::current()->Notify(
544       chrome::NOTIFICATION_SESSION_STARTED,
545       content::Source<UserManager>(this),
546       content::Details<const User>(active_user_));
547   if (is_current_user_new_) {
548     // Make sure that the new user's data is persisted to Local State.
549     g_browser_process->local_state()->CommitPendingWrite();
550   }
551 }
552
553 void UserManagerImpl::RemoveUser(const std::string& user_id,
554                                  RemoveUserDelegate* delegate) {
555   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
556
557   const User* user = FindUser(user_id);
558   if (!user || (user->GetType() != User::USER_TYPE_REGULAR &&
559                 user->GetType() != User::USER_TYPE_LOCALLY_MANAGED))
560     return;
561
562   // Sanity check: we must not remove single user unless it's an enterprise
563   // device. This check may seem redundant at a first sight because
564   // this single user must be an owner and we perform special check later
565   // in order not to remove an owner. However due to non-instant nature of
566   // ownership assignment this later check may sometimes fail.
567   // See http://crosbug.com/12723
568   policy::BrowserPolicyConnectorChromeOS* connector =
569       g_browser_process->platform_part()
570           ->browser_policy_connector_chromeos();
571   if (users_.size() < 2 && !connector->IsEnterpriseManaged())
572     return;
573
574   // Sanity check: do not allow any of the the logged in users to be removed.
575   for (UserList::const_iterator it = logged_in_users_.begin();
576        it != logged_in_users_.end(); ++it) {
577     if ((*it)->email() == user_id)
578       return;
579   }
580
581   RemoveUserInternal(user_id, delegate);
582 }
583
584 void UserManagerImpl::RemoveUserInternal(const std::string& user_email,
585                                          RemoveUserDelegate* delegate) {
586   CrosSettings* cros_settings = CrosSettings::Get();
587
588   // Ensure the value of owner email has been fetched.
589   if (CrosSettingsProvider::TRUSTED != cros_settings->PrepareTrustedValues(
590           base::Bind(&UserManagerImpl::RemoveUserInternal,
591                      base::Unretained(this),
592                      user_email, delegate))) {
593     // Value of owner email is not fetched yet.  RemoveUserInternal will be
594     // called again after fetch completion.
595     return;
596   }
597   std::string owner;
598   cros_settings->GetString(kDeviceOwner, &owner);
599   if (user_email == owner) {
600     // Owner is not allowed to be removed from the device.
601     return;
602   }
603   RemoveNonOwnerUserInternal(user_email, delegate);
604 }
605
606 void UserManagerImpl::RemoveNonOwnerUserInternal(const std::string& user_email,
607                                                  RemoveUserDelegate* delegate) {
608   if (delegate)
609     delegate->OnBeforeUserRemoved(user_email);
610   RemoveUserFromList(user_email);
611   cryptohome::AsyncMethodCaller::GetInstance()->AsyncRemove(
612       user_email, base::Bind(&OnRemoveUserComplete, user_email));
613
614   if (delegate)
615     delegate->OnUserRemoved(user_email);
616 }
617
618 void UserManagerImpl::RemoveUserFromList(const std::string& user_id) {
619   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
620   RemoveNonCryptohomeData(user_id);
621   if (user_loading_stage_ == STAGE_LOADED) {
622     DeleteUser(RemoveRegularOrLocallyManagedUserFromList(user_id));
623   } else if (user_loading_stage_ == STAGE_LOADING) {
624     DCHECK(gaia::ExtractDomainName(user_id) ==
625         UserManager::kLocallyManagedUserDomain);
626     // Special case, removing partially-constructed supervised user during user
627     // list loading.
628     ListPrefUpdate users_update(g_browser_process->local_state(),
629                                 kRegularUsers);
630     users_update->Remove(base::StringValue(user_id), NULL);
631   } else {
632     NOTREACHED() << "Users are not loaded yet.";
633     return;
634   }
635   // Make sure that new data is persisted to Local State.
636   g_browser_process->local_state()->CommitPendingWrite();
637 }
638
639 bool UserManagerImpl::IsKnownUser(const std::string& user_id) const {
640   return FindUser(user_id) != NULL;
641 }
642
643 const User* UserManagerImpl::FindUser(const std::string& user_id) const {
644   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
645   if (active_user_ && active_user_->email() == user_id)
646     return active_user_;
647   return FindUserInList(user_id);
648 }
649
650 User* UserManagerImpl::FindUserAndModify(const std::string& user_id) {
651   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
652   if (active_user_ && active_user_->email() == user_id)
653     return active_user_;
654   return FindUserInListAndModify(user_id);
655 }
656
657 const User* UserManagerImpl::GetLoggedInUser() const {
658   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
659   return active_user_;
660 }
661
662 User* UserManagerImpl::GetLoggedInUser() {
663   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
664   return active_user_;
665 }
666
667 const User* UserManagerImpl::GetActiveUser() const {
668   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
669   return active_user_;
670 }
671
672 User* UserManagerImpl::GetActiveUser() {
673   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
674   return active_user_;
675 }
676
677 const User* UserManagerImpl::GetPrimaryUser() const {
678   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
679   return primary_user_;
680 }
681
682 User* UserManagerImpl::GetUserByProfile(Profile* profile) const {
683   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
684   if (ProfileHelper::IsSigninProfile(profile))
685     return NULL;
686
687   if (IsMultipleProfilesAllowed()) {
688     const std::string username_hash =
689         ProfileHelper::GetUserIdHashFromProfile(profile);
690     const UserList& users = GetUsers();
691     const UserList::const_iterator pos = std::find_if(
692         users.begin(), users.end(), UserHashMatcher(username_hash));
693     if (pos != users.end())
694       return *pos;
695
696     // Many tests do not have their users registered with UserManager and
697     // runs here. If |active_user_| matches |profile|, returns it.
698     return active_user_ &&
699                    ProfileHelper::GetProfilePathByUserIdHash(
700                        active_user_->username_hash()) == profile->GetPath()
701                ? active_user_
702                : NULL;
703   }
704   return active_user_;
705 }
706
707 Profile* UserManagerImpl::GetProfileByUser(const User* user) const {
708   Profile* profile = NULL;
709   if (IsMultipleProfilesAllowed() && user->is_profile_created())
710     profile = ProfileHelper::GetProfileByUserIdHash(user->username_hash());
711   else
712     profile = ProfileManager::GetActiveUserProfile();
713
714   // GetActiveUserProfile() or GetProfileByUserIdHash() returns a new instance
715   // of ProfileImpl(), but actually its OffTheRecordProfile() should be used.
716   if (profile && IsLoggedInAsGuest())
717     profile = profile->GetOffTheRecordProfile();
718   return profile;
719 }
720
721 void UserManagerImpl::SaveUserOAuthStatus(
722     const std::string& user_id,
723     User::OAuthTokenStatus oauth_token_status) {
724   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
725
726   DVLOG(1) << "Saving user OAuth token status in Local State";
727   User* user = FindUserAndModify(user_id);
728   if (user)
729     user->set_oauth_token_status(oauth_token_status);
730
731   GetUserFlow(user_id)->HandleOAuthTokenStatusChange(oauth_token_status);
732
733   // Do not update local state if data stored or cached outside the user's
734   // cryptohome is to be treated as ephemeral.
735   if (IsUserNonCryptohomeDataEphemeral(user_id))
736     return;
737
738   PrefService* local_state = g_browser_process->local_state();
739
740   DictionaryPrefUpdate oauth_status_update(local_state, kUserOAuthTokenStatus);
741   oauth_status_update->SetWithoutPathExpansion(user_id,
742       new base::FundamentalValue(static_cast<int>(oauth_token_status)));
743 }
744
745 void UserManagerImpl::SaveForceOnlineSignin(const std::string& user_id,
746                                             bool force_online_signin) {
747   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
748
749   // Do not update local state if data stored or cached outside the user's
750   // cryptohome is to be treated as ephemeral.
751   if (IsUserNonCryptohomeDataEphemeral(user_id))
752     return;
753
754   DictionaryPrefUpdate force_online_update(g_browser_process->local_state(),
755                                            kUserForceOnlineSignin);
756   force_online_update->SetBooleanWithoutPathExpansion(user_id,
757                                                       force_online_signin);
758 }
759
760 void UserManagerImpl::SaveUserDisplayName(const std::string& user_id,
761                                           const base::string16& display_name) {
762   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
763
764   if (User* user = FindUserAndModify(user_id)) {
765     user->set_display_name(display_name);
766
767     // Do not update local state if data stored or cached outside the user's
768     // cryptohome is to be treated as ephemeral.
769     if (!IsUserNonCryptohomeDataEphemeral(user_id)) {
770       PrefService* local_state = g_browser_process->local_state();
771
772       DictionaryPrefUpdate display_name_update(local_state, kUserDisplayName);
773       display_name_update->SetWithoutPathExpansion(
774           user_id,
775           new base::StringValue(display_name));
776
777       supervised_user_manager_->UpdateManagerName(user_id, display_name);
778     }
779   }
780 }
781
782 base::string16 UserManagerImpl::GetUserDisplayName(
783     const std::string& user_id) const {
784   const User* user = FindUser(user_id);
785   return user ? user->display_name() : base::string16();
786 }
787
788 void UserManagerImpl::SaveUserDisplayEmail(const std::string& user_id,
789                                            const std::string& display_email) {
790   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
791
792   User* user = FindUserAndModify(user_id);
793   if (!user)
794     return;  // Ignore if there is no such user.
795
796   user->set_display_email(display_email);
797
798   // Do not update local state if data stored or cached outside the user's
799   // cryptohome is to be treated as ephemeral.
800   if (IsUserNonCryptohomeDataEphemeral(user_id))
801     return;
802
803   PrefService* local_state = g_browser_process->local_state();
804
805   DictionaryPrefUpdate display_email_update(local_state, kUserDisplayEmail);
806   display_email_update->SetWithoutPathExpansion(
807       user_id,
808       new base::StringValue(display_email));
809 }
810
811 std::string UserManagerImpl::GetUserDisplayEmail(
812     const std::string& user_id) const {
813   const User* user = FindUser(user_id);
814   return user ? user->display_email() : user_id;
815 }
816
817 void UserManagerImpl::UpdateUserAccountData(
818     const std::string& user_id,
819     const UserAccountData& account_data) {
820   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
821
822   SaveUserDisplayName(user_id, account_data.display_name());
823
824   if (User* user = FindUserAndModify(user_id)) {
825     base::string16 given_name = account_data.given_name();
826     user->set_given_name(given_name);
827     if (!IsUserNonCryptohomeDataEphemeral(user_id)) {
828       PrefService* local_state = g_browser_process->local_state();
829
830       DictionaryPrefUpdate given_name_update(local_state, kUserGivenName);
831       given_name_update->SetWithoutPathExpansion(
832           user_id,
833           new base::StringValue(given_name));
834     }
835   }
836
837   UpdateUserAccountLocale(user_id, account_data.locale());
838 }
839
840 // TODO(alemate): http://crbug.com/288941 : Respect preferred language list in
841 // the Google user profile.
842 //
843 // Returns true if callback will be called.
844 bool UserManagerImpl::RespectLocalePreference(
845     Profile* profile,
846     const User* user,
847     scoped_ptr<locale_util::SwitchLanguageCallback> callback) const {
848   if (g_browser_process == NULL)
849     return false;
850   if ((user == NULL) || (user != GetPrimaryUser()) ||
851       (!user->is_profile_created()))
852     return false;
853
854   // In case of Multi Profile mode we don't apply profile locale because it is
855   // unsafe.
856   if (GetLoggedInUsers().size() != 1)
857     return false;
858   const PrefService* prefs = profile->GetPrefs();
859   if (prefs == NULL)
860     return false;
861
862   std::string pref_locale;
863   const std::string pref_app_locale =
864       prefs->GetString(prefs::kApplicationLocale);
865   const std::string pref_bkup_locale =
866       prefs->GetString(prefs::kApplicationLocaleBackup);
867
868   pref_locale = pref_app_locale;
869   if (pref_locale.empty())
870     pref_locale = pref_bkup_locale;
871
872   const std::string* account_locale = NULL;
873   if (pref_locale.empty() && user->has_gaia_account()) {
874     if (user->GetAccountLocale() == NULL)
875       return false;  // wait until Account profile is loaded.
876     account_locale = user->GetAccountLocale();
877     pref_locale = *account_locale;
878   }
879   const std::string global_app_locale =
880       g_browser_process->GetApplicationLocale();
881   if (pref_locale.empty())
882     pref_locale = global_app_locale;
883   DCHECK(!pref_locale.empty());
884   LOG(WARNING) << "RespectLocalePreference: "
885                << "app_locale='" << pref_app_locale << "', "
886                << "bkup_locale='" << pref_bkup_locale << "', "
887                << (account_locale != NULL
888                        ? (std::string("account_locale='") + (*account_locale) +
889                           "'. ")
890                        : (std::string("account_locale - unused. ")))
891                << " Selected '" << pref_locale << "'";
892   profile->ChangeAppLocale(pref_locale, Profile::APP_LOCALE_CHANGED_VIA_LOGIN);
893
894   // Here we don't enable keyboard layouts for normal users. Input methods
895   // are set up when the user first logs in. Then the user may customize the
896   // input methods.  Hence changing input methods here, just because the user's
897   // UI language is different from the login screen UI language, is not
898   // desirable. Note that input method preferences are synced, so users can use
899   // their farovite input methods as soon as the preferences are synced.
900   //
901   // For Guest mode, user locale preferences will never get initialized.
902   // So input methods should be enabled somewhere.
903   const bool enable_layouts = UserManager::Get()->IsLoggedInAsGuest();
904   locale_util::SwitchLanguage(pref_locale,
905                               enable_layouts,
906                               false /* login_layouts_only */,
907                               callback.Pass());
908
909   return true;
910 }
911
912 void UserManagerImpl::StopPolicyObserverForTesting() {
913   avatar_policy_observer_.reset();
914   wallpaper_policy_observer_.reset();
915 }
916
917 void UserManagerImpl::Observe(int type,
918                               const content::NotificationSource& source,
919                               const content::NotificationDetails& details) {
920   switch (type) {
921     case chrome::NOTIFICATION_OWNERSHIP_STATUS_CHANGED:
922       if (!device_local_account_policy_service_) {
923         policy::BrowserPolicyConnectorChromeOS* connector =
924             g_browser_process->platform_part()
925                 ->browser_policy_connector_chromeos();
926         device_local_account_policy_service_ =
927             connector->GetDeviceLocalAccountPolicyService();
928         if (device_local_account_policy_service_)
929           device_local_account_policy_service_->AddObserver(this);
930       }
931       // Making this call synchronously is not gonna cut it because
932       // notification order is not defined and in a single message loop run and
933       // getting trusted settings rely on a reload that happens on the very same
934       // notification observation.
935       base::MessageLoop::current()->PostTask(FROM_HERE,
936             base::Bind(&UserManagerImpl::RetrieveTrustedDevicePolicies,
937                        base::Unretained(this)));
938       UserManagerImpl::UpdateOwnership();
939       break;
940     case chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED: {
941       Profile* profile = content::Details<Profile>(details).ptr();
942       if (IsUserLoggedIn() &&
943           !IsLoggedInAsGuest() &&
944           !IsLoggedInAsKioskApp()) {
945         if (IsLoggedInAsLocallyManagedUser())
946           ManagedUserPasswordServiceFactory::GetForProfile(profile);
947         if (IsLoggedInAsRegularUser())
948           ManagerPasswordServiceFactory::GetForProfile(profile);
949
950         if (!profile->IsOffTheRecord()) {
951           AuthSyncObserver* sync_observer =
952               AuthSyncObserverFactory::GetInstance()->GetForProfile(profile);
953           sync_observer->StartObserving();
954           multi_profile_user_controller_->StartObserving(profile);
955         }
956       }
957
958       // Now that the user profile has been initialized and
959       // |GetNSSCertDatabaseForProfile| is safe to be used, get the NSS cert
960       // database for the primary user and start certificate loader with it.
961       if (IsUserLoggedIn() &&
962           GetPrimaryUser() &&
963           profile == GetProfileByUser(GetPrimaryUser()) &&
964           CertLoader::IsInitialized() &&
965           base::SysInfo::IsRunningOnChromeOS()) {
966         GetNSSCertDatabaseForProfile(profile,
967                                      base::Bind(&OnGetNSSCertDatabaseForUser));
968       }
969       break;
970     }
971     case chrome::NOTIFICATION_PROFILE_CREATED: {
972       Profile* profile = content::Source<Profile>(source).ptr();
973       User* user = GetUserByProfile(profile);
974       if (user != NULL)
975         user->set_profile_is_created();
976       // If there is pending user switch, do it now.
977       if (!pending_user_switch_.empty()) {
978         // Call SwitchActiveUser async because otherwise it may cause
979         // ProfileManager::GetProfile before the profile gets registered
980         // in ProfileManager. It happens in case of sync profile load when
981         // NOTIFICATION_PROFILE_CREATED is called synchronously.
982         base::MessageLoop::current()->PostTask(FROM_HERE,
983           base::Bind(&UserManagerImpl::SwitchActiveUser,
984                      base::Unretained(this),
985                      pending_user_switch_));
986         pending_user_switch_.clear();
987       }
988       break;
989     }
990     default:
991       NOTREACHED();
992   }
993 }
994
995 void UserManagerImpl::OnExternalDataSet(const std::string& policy,
996                                         const std::string& user_id) {
997   if (policy == policy::key::kUserAvatarImage)
998     GetUserImageManager(user_id)->OnExternalDataSet(policy);
999   else if (policy == policy::key::kWallpaperImage)
1000     WallpaperManager::Get()->OnPolicySet(policy, user_id);
1001   else
1002     NOTREACHED();
1003 }
1004
1005 void UserManagerImpl::OnExternalDataCleared(const std::string& policy,
1006                                             const std::string& user_id) {
1007   if (policy == policy::key::kUserAvatarImage)
1008     GetUserImageManager(user_id)->OnExternalDataCleared(policy);
1009   else if (policy == policy::key::kWallpaperImage)
1010     WallpaperManager::Get()->OnPolicyCleared(policy, user_id);
1011   else
1012     NOTREACHED();
1013 }
1014
1015 void UserManagerImpl::OnExternalDataFetched(const std::string& policy,
1016                                             const std::string& user_id,
1017                                             scoped_ptr<std::string> data) {
1018   if (policy == policy::key::kUserAvatarImage)
1019     GetUserImageManager(user_id)->OnExternalDataFetched(policy, data.Pass());
1020   else if (policy == policy::key::kWallpaperImage)
1021     WallpaperManager::Get()->OnPolicyFetched(policy, user_id, data.Pass());
1022   else
1023     NOTREACHED();
1024 }
1025
1026 void UserManagerImpl::OnPolicyUpdated(const std::string& user_id) {
1027   UpdatePublicAccountDisplayName(user_id);
1028   NotifyUserListChanged();
1029 }
1030
1031 void UserManagerImpl::OnDeviceLocalAccountsChanged() {
1032   // No action needed here, changes to the list of device-local accounts get
1033   // handled via the kAccountsPrefDeviceLocalAccounts device setting observer.
1034 }
1035
1036 bool UserManagerImpl::IsCurrentUserOwner() const {
1037   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1038   base::AutoLock lk(is_current_user_owner_lock_);
1039   return is_current_user_owner_;
1040 }
1041
1042 void UserManagerImpl::SetCurrentUserIsOwner(bool is_current_user_owner) {
1043   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1044   {
1045     base::AutoLock lk(is_current_user_owner_lock_);
1046     is_current_user_owner_ = is_current_user_owner;
1047   }
1048   UpdateLoginState();
1049 }
1050
1051 bool UserManagerImpl::IsCurrentUserNew() const {
1052   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1053   return is_current_user_new_;
1054 }
1055
1056 bool UserManagerImpl::IsCurrentUserNonCryptohomeDataEphemeral() const {
1057   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1058   return IsUserLoggedIn() &&
1059          IsUserNonCryptohomeDataEphemeral(GetLoggedInUser()->email());
1060 }
1061
1062 bool UserManagerImpl::CanCurrentUserLock() const {
1063   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1064   return IsUserLoggedIn() && active_user_->can_lock() &&
1065       GetCurrentUserFlow()->CanLockScreen();
1066 }
1067
1068 bool UserManagerImpl::IsUserLoggedIn() const {
1069   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1070   return active_user_;
1071 }
1072
1073 bool UserManagerImpl::IsLoggedInAsRegularUser() const {
1074   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1075   return IsUserLoggedIn() &&
1076          active_user_->GetType() == User::USER_TYPE_REGULAR;
1077 }
1078
1079 bool UserManagerImpl::IsLoggedInAsDemoUser() const {
1080   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1081   return IsUserLoggedIn() &&
1082          active_user_->GetType() == User::USER_TYPE_RETAIL_MODE;
1083 }
1084
1085 bool UserManagerImpl::IsLoggedInAsPublicAccount() const {
1086   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1087   return IsUserLoggedIn() &&
1088       active_user_->GetType() == User::USER_TYPE_PUBLIC_ACCOUNT;
1089 }
1090
1091 bool UserManagerImpl::IsLoggedInAsGuest() const {
1092   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1093   return IsUserLoggedIn() &&
1094          active_user_->GetType() == User::USER_TYPE_GUEST;
1095 }
1096
1097 bool UserManagerImpl::IsLoggedInAsLocallyManagedUser() const {
1098   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1099   return IsUserLoggedIn() &&
1100       active_user_->GetType() == User::USER_TYPE_LOCALLY_MANAGED;
1101 }
1102
1103 bool UserManagerImpl::IsLoggedInAsKioskApp() const {
1104   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1105   return IsUserLoggedIn() &&
1106       active_user_->GetType() == User::USER_TYPE_KIOSK_APP;
1107 }
1108
1109 bool UserManagerImpl::IsLoggedInAsStub() const {
1110   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1111   return IsUserLoggedIn() && active_user_->email() == kStubUser;
1112 }
1113
1114 bool UserManagerImpl::IsSessionStarted() const {
1115   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1116   return session_started_;
1117 }
1118
1119 bool UserManagerImpl::UserSessionsRestored() const {
1120   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1121   return user_sessions_restored_;
1122 }
1123
1124 bool UserManagerImpl::HasBrowserRestarted() const {
1125   CommandLine* command_line = CommandLine::ForCurrentProcess();
1126   return base::SysInfo::IsRunningOnChromeOS() &&
1127          command_line->HasSwitch(switches::kLoginUser) &&
1128          !command_line->HasSwitch(switches::kLoginPassword);
1129 }
1130
1131 bool UserManagerImpl::IsUserNonCryptohomeDataEphemeral(
1132     const std::string& user_id) const {
1133   // Data belonging to the guest, retail mode and stub users is always
1134   // ephemeral.
1135   if (user_id == UserManager::kGuestUserName ||
1136       user_id == UserManager::kRetailModeUserName ||
1137       user_id == kStubUser) {
1138     return true;
1139   }
1140
1141   // Data belonging to the owner, anyone found on the user list and obsolete
1142   // public accounts whose data has not been removed yet is not ephemeral.
1143   if (user_id == owner_email_  || UserExistsInList(user_id) ||
1144       user_id == g_browser_process->local_state()->
1145           GetString(kPublicAccountPendingDataRemoval)) {
1146     return false;
1147   }
1148
1149   // Data belonging to the currently logged-in user is ephemeral when:
1150   // a) The user logged into a regular account while the ephemeral users policy
1151   //    was enabled.
1152   //    - or -
1153   // b) The user logged into any other account type.
1154   if (IsUserLoggedIn() && (user_id == GetLoggedInUser()->email()) &&
1155       (is_current_user_ephemeral_regular_user_ || !IsLoggedInAsRegularUser())) {
1156     return true;
1157   }
1158
1159   // Data belonging to any other user is ephemeral when:
1160   // a) Going through the regular login flow and the ephemeral users policy is
1161   //    enabled.
1162   //    - or -
1163   // b) The browser is restarting after a crash.
1164   return AreEphemeralUsersEnabled() || HasBrowserRestarted();
1165 }
1166
1167 void UserManagerImpl::AddObserver(UserManager::Observer* obs) {
1168   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1169   observer_list_.AddObserver(obs);
1170 }
1171
1172 void UserManagerImpl::RemoveObserver(UserManager::Observer* obs) {
1173   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1174   observer_list_.RemoveObserver(obs);
1175 }
1176
1177 void UserManagerImpl::AddSessionStateObserver(
1178     UserManager::UserSessionStateObserver* obs) {
1179   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1180   session_state_observer_list_.AddObserver(obs);
1181 }
1182
1183 void UserManagerImpl::RemoveSessionStateObserver(
1184     UserManager::UserSessionStateObserver* obs) {
1185   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1186   session_state_observer_list_.RemoveObserver(obs);
1187 }
1188
1189 void UserManagerImpl::NotifyLocalStateChanged() {
1190   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1191   FOR_EACH_OBSERVER(UserManager::Observer, observer_list_,
1192                     LocalStateChanged(this));
1193 }
1194
1195 void UserManagerImpl::OnProfilePrepared(Profile* profile) {
1196   LoginUtils::Get()->DoBrowserLaunch(profile,
1197                                      NULL);     // host_, not needed here
1198
1199   if (!CommandLine::ForCurrentProcess()->HasSwitch(::switches::kTestName)) {
1200     // Did not log in (we crashed or are debugging), need to restore Sync.
1201     // TODO(nkostylev): Make sure that OAuth state is restored correctly for all
1202     // users once it is fully multi-profile aware. http://crbug.com/238987
1203     // For now if we have other user pending sessions they'll override OAuth
1204     // session restore for previous users.
1205     LoginUtils::Get()->RestoreAuthenticationSession(profile);
1206   }
1207
1208   // Restore other user sessions if any.
1209   RestorePendingUserSessions();
1210 }
1211
1212 void UserManagerImpl::EnsureUsersLoaded() {
1213   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1214   if (!g_browser_process || !g_browser_process->local_state())
1215     return;
1216
1217   if (user_loading_stage_ != STAGE_NOT_LOADED)
1218     return;
1219   user_loading_stage_ = STAGE_LOADING;
1220   // Clean up user list first. All code down the path should be synchronous,
1221   // so that local state after transaction rollback is in consistent state.
1222   // This process also should not trigger EnsureUsersLoaded again.
1223   if (supervised_user_manager_->HasFailedUserCreationTransaction())
1224     supervised_user_manager_->RollbackUserCreationTransaction();
1225
1226   PrefService* local_state = g_browser_process->local_state();
1227   const base::ListValue* prefs_regular_users =
1228       local_state->GetList(kRegularUsers);
1229   const base::ListValue* prefs_public_sessions =
1230       local_state->GetList(kPublicAccounts);
1231   const base::DictionaryValue* prefs_display_names =
1232       local_state->GetDictionary(kUserDisplayName);
1233   const base::DictionaryValue* prefs_given_names =
1234       local_state->GetDictionary(kUserGivenName);
1235   const base::DictionaryValue* prefs_display_emails =
1236       local_state->GetDictionary(kUserDisplayEmail);
1237
1238   // Load public sessions first.
1239   std::vector<std::string> public_sessions;
1240   std::set<std::string> public_sessions_set;
1241   ParseUserList(*prefs_public_sessions, std::set<std::string>(),
1242                 &public_sessions, &public_sessions_set);
1243   for (std::vector<std::string>::const_iterator it = public_sessions.begin();
1244        it != public_sessions.end(); ++it) {
1245     users_.push_back(User::CreatePublicAccountUser(*it));
1246     UpdatePublicAccountDisplayName(*it);
1247   }
1248
1249   // Load regular users and locally managed users.
1250   std::vector<std::string> regular_users;
1251   std::set<std::string> regular_users_set;
1252   ParseUserList(*prefs_regular_users, public_sessions_set,
1253                 &regular_users, &regular_users_set);
1254   for (std::vector<std::string>::const_iterator it = regular_users.begin();
1255        it != regular_users.end(); ++it) {
1256     User* user = NULL;
1257     const std::string domain = gaia::ExtractDomainName(*it);
1258     if (domain == UserManager::kLocallyManagedUserDomain)
1259       user = User::CreateLocallyManagedUser(*it);
1260     else
1261       user = User::CreateRegularUser(*it);
1262     user->set_oauth_token_status(LoadUserOAuthStatus(*it));
1263     user->set_force_online_signin(LoadForceOnlineSignin(*it));
1264     users_.push_back(user);
1265
1266     base::string16 display_name;
1267     if (prefs_display_names->GetStringWithoutPathExpansion(*it,
1268                                                            &display_name)) {
1269       user->set_display_name(display_name);
1270     }
1271
1272     base::string16 given_name;
1273     if (prefs_given_names->GetStringWithoutPathExpansion(*it, &given_name)) {
1274       user->set_given_name(given_name);
1275     }
1276
1277     std::string display_email;
1278     if (prefs_display_emails->GetStringWithoutPathExpansion(*it,
1279                                                             &display_email)) {
1280       user->set_display_email(display_email);
1281     }
1282   }
1283
1284   user_loading_stage_ = STAGE_LOADED;
1285
1286   for (UserList::iterator ui = users_.begin(), ue = users_.end();
1287        ui != ue; ++ui) {
1288     GetUserImageManager((*ui)->email())->LoadUserImage();
1289   }
1290 }
1291
1292 void UserManagerImpl::RetrieveTrustedDevicePolicies() {
1293   ephemeral_users_enabled_ = false;
1294   owner_email_ = "";
1295
1296   // Schedule a callback if device policy has not yet been verified.
1297   if (CrosSettingsProvider::TRUSTED != cros_settings_->PrepareTrustedValues(
1298       base::Bind(&UserManagerImpl::RetrieveTrustedDevicePolicies,
1299                  base::Unretained(this)))) {
1300     return;
1301   }
1302
1303   cros_settings_->GetBoolean(kAccountsPrefEphemeralUsersEnabled,
1304                              &ephemeral_users_enabled_);
1305   cros_settings_->GetString(kDeviceOwner, &owner_email_);
1306
1307   EnsureUsersLoaded();
1308
1309   bool changed = UpdateAndCleanUpPublicAccounts(
1310       policy::GetDeviceLocalAccounts(cros_settings_));
1311
1312   // If ephemeral users are enabled and we are on the login screen, take this
1313   // opportunity to clean up by removing all regular users except the owner.
1314   if (ephemeral_users_enabled_ && !IsUserLoggedIn()) {
1315     ListPrefUpdate prefs_users_update(g_browser_process->local_state(),
1316                                       kRegularUsers);
1317     prefs_users_update->Clear();
1318     for (UserList::iterator it = users_.begin(); it != users_.end(); ) {
1319       const std::string user_email = (*it)->email();
1320       if ((*it)->GetType() == User::USER_TYPE_REGULAR &&
1321           user_email != owner_email_) {
1322         RemoveNonCryptohomeData(user_email);
1323         DeleteUser(*it);
1324         it = users_.erase(it);
1325         changed = true;
1326       } else {
1327         if ((*it)->GetType() != User::USER_TYPE_PUBLIC_ACCOUNT)
1328           prefs_users_update->Append(new base::StringValue(user_email));
1329         ++it;
1330       }
1331     }
1332   }
1333
1334   if (changed)
1335     NotifyUserListChanged();
1336 }
1337
1338 bool UserManagerImpl::AreEphemeralUsersEnabled() const {
1339   policy::BrowserPolicyConnectorChromeOS* connector =
1340       g_browser_process->platform_part()->browser_policy_connector_chromeos();
1341   return ephemeral_users_enabled_ &&
1342          (connector->IsEnterpriseManaged() || !owner_email_.empty());
1343 }
1344
1345 UserList& UserManagerImpl::GetUsersAndModify() {
1346   EnsureUsersLoaded();
1347   return users_;
1348 }
1349
1350 const User* UserManagerImpl::FindUserInList(const std::string& user_id) const {
1351   const UserList& users = GetUsers();
1352   for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) {
1353     if ((*it)->email() == user_id)
1354       return *it;
1355   }
1356   return NULL;
1357 }
1358
1359 const bool UserManagerImpl::UserExistsInList(const std::string& user_id) const {
1360   PrefService* local_state = g_browser_process->local_state();
1361   const base::ListValue* user_list = local_state->GetList(kRegularUsers);
1362   for (size_t i = 0; i < user_list->GetSize(); ++i) {
1363     std::string email;
1364     if (user_list->GetString(i, &email) && (user_id == email))
1365       return true;
1366   }
1367   return false;
1368 }
1369
1370 User* UserManagerImpl::FindUserInListAndModify(const std::string& user_id) {
1371   UserList& users = GetUsersAndModify();
1372   for (UserList::iterator it = users.begin(); it != users.end(); ++it) {
1373     if ((*it)->email() == user_id)
1374       return *it;
1375   }
1376   return NULL;
1377 }
1378
1379 void UserManagerImpl::GuestUserLoggedIn() {
1380   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1381   active_user_ = User::CreateGuestUser();
1382   // TODO(nkostylev): Add support for passing guest session cryptohome
1383   // mount point. Legacy (--login-profile) value will be used for now.
1384   // http://crosbug.com/230859
1385   active_user_->SetStubImage(User::kInvalidImageIndex, false);
1386   // Initializes wallpaper after active_user_ is set.
1387   WallpaperManager::Get()->SetUserWallpaperNow(UserManager::kGuestUserName);
1388 }
1389
1390 void UserManagerImpl::AddUserRecord(User* user) {
1391   // Add the user to the front of the user list.
1392   ListPrefUpdate prefs_users_update(g_browser_process->local_state(),
1393                                     kRegularUsers);
1394   prefs_users_update->Insert(0, new base::StringValue(user->email()));
1395   users_.insert(users_.begin(), user);
1396 }
1397
1398 void UserManagerImpl::RegularUserLoggedIn(const std::string& user_id) {
1399   // Remove the user from the user list.
1400   active_user_ = RemoveRegularOrLocallyManagedUserFromList(user_id);
1401
1402   // If the user was not found on the user list, create a new user.
1403   is_current_user_new_ = !active_user_;
1404   if (!active_user_) {
1405     active_user_ = User::CreateRegularUser(user_id);
1406     active_user_->set_oauth_token_status(LoadUserOAuthStatus(user_id));
1407     SaveUserDisplayName(active_user_->email(),
1408                         base::UTF8ToUTF16(active_user_->GetAccountName(true)));
1409     WallpaperManager::Get()->SetUserWallpaperNow(user_id);
1410   }
1411
1412   AddUserRecord(active_user_);
1413
1414   GetUserImageManager(user_id)->UserLoggedIn(is_current_user_new_, false);
1415
1416   WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded();
1417
1418   // Make sure that new data is persisted to Local State.
1419   g_browser_process->local_state()->CommitPendingWrite();
1420 }
1421
1422 void UserManagerImpl::RegularUserLoggedInAsEphemeral(
1423     const std::string& user_id) {
1424   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1425   is_current_user_new_ = true;
1426   is_current_user_ephemeral_regular_user_ = true;
1427   active_user_ = User::CreateRegularUser(user_id);
1428   GetUserImageManager(user_id)->UserLoggedIn(is_current_user_new_, false);
1429   WallpaperManager::Get()->SetUserWallpaperNow(user_id);
1430 }
1431
1432 void UserManagerImpl::LocallyManagedUserLoggedIn(
1433     const std::string& user_id) {
1434   // TODO(nkostylev): Refactor, share code with RegularUserLoggedIn().
1435
1436   // Remove the user from the user list.
1437   active_user_ = RemoveRegularOrLocallyManagedUserFromList(user_id);
1438   // If the user was not found on the user list, create a new user.
1439   if (!active_user_) {
1440     is_current_user_new_ = true;
1441     active_user_ = User::CreateLocallyManagedUser(user_id);
1442     // Leaving OAuth token status at the default state = unknown.
1443     WallpaperManager::Get()->SetUserWallpaperNow(user_id);
1444   } else {
1445     if (supervised_user_manager_->CheckForFirstRun(user_id)) {
1446       is_current_user_new_ = true;
1447       WallpaperManager::Get()->SetUserWallpaperNow(user_id);
1448     } else {
1449       is_current_user_new_ = false;
1450     }
1451   }
1452
1453   // Add the user to the front of the user list.
1454   ListPrefUpdate prefs_users_update(g_browser_process->local_state(),
1455                                     kRegularUsers);
1456   prefs_users_update->Insert(0, new base::StringValue(user_id));
1457   users_.insert(users_.begin(), active_user_);
1458
1459   // Now that user is in the list, save display name.
1460   if (is_current_user_new_) {
1461     SaveUserDisplayName(active_user_->email(),
1462                         active_user_->GetDisplayName());
1463   }
1464
1465   GetUserImageManager(user_id)->UserLoggedIn(is_current_user_new_, true);
1466   WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded();
1467
1468   // Make sure that new data is persisted to Local State.
1469   g_browser_process->local_state()->CommitPendingWrite();
1470 }
1471
1472 void UserManagerImpl::PublicAccountUserLoggedIn(User* user) {
1473   is_current_user_new_ = true;
1474   active_user_ = user;
1475   // The UserImageManager chooses a random avatar picture when a user logs in
1476   // for the first time. Tell the UserImageManager that this user is not new to
1477   // prevent the avatar from getting changed.
1478   GetUserImageManager(user->email())->UserLoggedIn(false, true);
1479   WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded();
1480 }
1481
1482 void UserManagerImpl::KioskAppLoggedIn(const std::string& app_id) {
1483   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1484   policy::DeviceLocalAccount::Type device_local_account_type;
1485   DCHECK(policy::IsDeviceLocalAccountUser(app_id,
1486                                           &device_local_account_type));
1487   DCHECK_EQ(policy::DeviceLocalAccount::TYPE_KIOSK_APP,
1488             device_local_account_type);
1489
1490   active_user_ = User::CreateKioskAppUser(app_id);
1491   active_user_->SetStubImage(User::kInvalidImageIndex, false);
1492
1493   WallpaperManager::Get()->SetUserWallpaperNow(app_id);
1494
1495   // TODO(bartfab): Add KioskAppUsers to the users_ list and keep metadata like
1496   // the kiosk_app_id in these objects, removing the need to re-parse the
1497   // device-local account list here to extract the kiosk_app_id.
1498   const std::vector<policy::DeviceLocalAccount> device_local_accounts =
1499       policy::GetDeviceLocalAccounts(cros_settings_);
1500   const policy::DeviceLocalAccount* account = NULL;
1501   for (std::vector<policy::DeviceLocalAccount>::const_iterator
1502            it = device_local_accounts.begin();
1503        it != device_local_accounts.end(); ++it) {
1504     if (it->user_id == app_id) {
1505       account = &*it;
1506       break;
1507     }
1508   }
1509   std::string kiosk_app_id;
1510   if (account) {
1511     kiosk_app_id = account->kiosk_app_id;
1512   } else {
1513     LOG(ERROR) << "Logged into nonexistent kiosk-app account: " << app_id;
1514     NOTREACHED();
1515   }
1516
1517   CommandLine* command_line = CommandLine::ForCurrentProcess();
1518   command_line->AppendSwitch(::switches::kForceAppMode);
1519   command_line->AppendSwitchASCII(::switches::kAppId, kiosk_app_id);
1520
1521   // Disable window animation since kiosk app runs in a single full screen
1522   // window and window animation causes start-up janks.
1523   command_line->AppendSwitch(
1524       wm::switches::kWindowAnimationsDisabled);
1525 }
1526
1527 void UserManagerImpl::DemoAccountLoggedIn() {
1528   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1529   active_user_ = User::CreateKioskAppUser(DemoAppLauncher::kDemoUserName);
1530   active_user_->SetStubImage(User::kInvalidImageIndex, false);
1531   WallpaperManager::Get()->SetUserWallpaperNow(DemoAppLauncher::kDemoUserName);
1532
1533   CommandLine* command_line = CommandLine::ForCurrentProcess();
1534   command_line->AppendSwitch(::switches::kForceAppMode);
1535   command_line->AppendSwitchASCII(::switches::kAppId,
1536                                   DemoAppLauncher::kDemoAppId);
1537
1538   // Disable window animation since the demo app runs in a single full screen
1539   // window and window animation causes start-up janks.
1540   CommandLine::ForCurrentProcess()->AppendSwitch(
1541       wm::switches::kWindowAnimationsDisabled);
1542 }
1543
1544 void UserManagerImpl::RetailModeUserLoggedIn() {
1545   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1546   is_current_user_new_ = true;
1547   active_user_ = User::CreateRetailModeUser();
1548   GetUserImageManager(UserManager::kRetailModeUserName)->UserLoggedIn(
1549       is_current_user_new_,
1550       true);
1551   WallpaperManager::Get()->SetUserWallpaperNow(
1552       UserManager::kRetailModeUserName);
1553 }
1554
1555 void UserManagerImpl::NotifyOnLogin() {
1556   UpdateNumberOfUsers();
1557   CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1558   NotifyActiveUserHashChanged(active_user_->username_hash());
1559   NotifyActiveUserChanged(active_user_);
1560
1561   UpdateLoginState();
1562   // TODO(nkostylev): Deprecate this notification in favor of
1563   // ActiveUserChanged() observer call.
1564   content::NotificationService::current()->Notify(
1565       chrome::NOTIFICATION_LOGIN_USER_CHANGED,
1566       content::Source<UserManager>(this),
1567       content::Details<const User>(active_user_));
1568
1569   // Owner must be first user in session. DeviceSettingsService can't deal with
1570   // multiple user and will mix up ownership, crbug.com/230018.
1571   if (GetLoggedInUsers().size() == 1) {
1572     // Indicate to DeviceSettingsService that the owner key may have become
1573     // available.
1574     DeviceSettingsService::Get()->SetUsername(active_user_->email());
1575
1576     if (NetworkPortalDetector::IsInitialized()) {
1577       NetworkPortalDetector::Get()->SetStrategy(
1578           PortalDetectorStrategy::STRATEGY_ID_SESSION);
1579     }
1580   }
1581 }
1582
1583 User::OAuthTokenStatus UserManagerImpl::LoadUserOAuthStatus(
1584     const std::string& user_id) const {
1585   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1586
1587   PrefService* local_state = g_browser_process->local_state();
1588   const base::DictionaryValue* prefs_oauth_status =
1589       local_state->GetDictionary(kUserOAuthTokenStatus);
1590   int oauth_token_status = User::OAUTH_TOKEN_STATUS_UNKNOWN;
1591   if (prefs_oauth_status &&
1592       prefs_oauth_status->GetIntegerWithoutPathExpansion(
1593           user_id, &oauth_token_status)) {
1594     User::OAuthTokenStatus result =
1595         static_cast<User::OAuthTokenStatus>(oauth_token_status);
1596     if (result == User::OAUTH2_TOKEN_STATUS_INVALID)
1597       GetUserFlow(user_id)->HandleOAuthTokenStatusChange(result);
1598     return result;
1599   }
1600   return User::OAUTH_TOKEN_STATUS_UNKNOWN;
1601 }
1602
1603 bool UserManagerImpl::LoadForceOnlineSignin(const std::string& user_id) const {
1604   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1605
1606   PrefService* local_state = g_browser_process->local_state();
1607   const base::DictionaryValue* prefs_force_online =
1608       local_state->GetDictionary(kUserForceOnlineSignin);
1609   bool force_online_signin = false;
1610   if (prefs_force_online) {
1611     prefs_force_online->GetBooleanWithoutPathExpansion(user_id,
1612                                                        &force_online_signin);
1613   }
1614   return force_online_signin;
1615 }
1616
1617 void UserManagerImpl::UpdateOwnership() {
1618   bool is_owner = DeviceSettingsService::Get()->HasPrivateOwnerKey();
1619   VLOG(1) << "Current user " << (is_owner ? "is owner" : "is not owner");
1620
1621   SetCurrentUserIsOwner(is_owner);
1622 }
1623
1624 void UserManagerImpl::RemoveNonCryptohomeData(const std::string& user_id) {
1625   WallpaperManager::Get()->RemoveUserWallpaperInfo(user_id);
1626   GetUserImageManager(user_id)->DeleteUserImage();
1627
1628   PrefService* prefs = g_browser_process->local_state();
1629   DictionaryPrefUpdate prefs_display_name_update(prefs, kUserDisplayName);
1630   prefs_display_name_update->RemoveWithoutPathExpansion(user_id, NULL);
1631
1632   DictionaryPrefUpdate prefs_given_name_update(prefs, kUserGivenName);
1633   prefs_given_name_update->RemoveWithoutPathExpansion(user_id, NULL);
1634
1635   DictionaryPrefUpdate prefs_display_email_update(prefs, kUserDisplayEmail);
1636   prefs_display_email_update->RemoveWithoutPathExpansion(user_id, NULL);
1637
1638   DictionaryPrefUpdate prefs_oauth_update(prefs, kUserOAuthTokenStatus);
1639   prefs_oauth_update->RemoveWithoutPathExpansion(user_id, NULL);
1640
1641   DictionaryPrefUpdate prefs_force_online_update(prefs, kUserForceOnlineSignin);
1642   prefs_force_online_update->RemoveWithoutPathExpansion(user_id, NULL);
1643
1644   supervised_user_manager_->RemoveNonCryptohomeData(user_id);
1645
1646   multi_profile_user_controller_->RemoveCachedValues(user_id);
1647 }
1648
1649 User* UserManagerImpl::RemoveRegularOrLocallyManagedUserFromList(
1650     const std::string& user_id) {
1651   ListPrefUpdate prefs_users_update(g_browser_process->local_state(),
1652                                     kRegularUsers);
1653   prefs_users_update->Clear();
1654   User* user = NULL;
1655   for (UserList::iterator it = users_.begin(); it != users_.end(); ) {
1656     const std::string user_email = (*it)->email();
1657     if (user_email == user_id) {
1658       user = *it;
1659       it = users_.erase(it);
1660     } else {
1661       if ((*it)->GetType() == User::USER_TYPE_REGULAR ||
1662           (*it)->GetType() == User::USER_TYPE_LOCALLY_MANAGED) {
1663         prefs_users_update->Append(new base::StringValue(user_email));
1664       }
1665       ++it;
1666     }
1667   }
1668   return user;
1669 }
1670
1671 void UserManagerImpl::CleanUpPublicAccountNonCryptohomeDataPendingRemoval() {
1672   PrefService* local_state = g_browser_process->local_state();
1673   const std::string public_account_pending_data_removal =
1674       local_state->GetString(kPublicAccountPendingDataRemoval);
1675   if (public_account_pending_data_removal.empty() ||
1676       (IsUserLoggedIn() &&
1677        public_account_pending_data_removal == GetActiveUser()->email())) {
1678     return;
1679   }
1680
1681   RemoveNonCryptohomeData(public_account_pending_data_removal);
1682   local_state->ClearPref(kPublicAccountPendingDataRemoval);
1683 }
1684
1685 void UserManagerImpl::CleanUpPublicAccountNonCryptohomeData(
1686     const std::vector<std::string>& old_public_accounts) {
1687   std::set<std::string> users;
1688   for (UserList::const_iterator it = users_.begin(); it != users_.end(); ++it)
1689     users.insert((*it)->email());
1690
1691   // If the user is logged into a public account that has been removed from the
1692   // user list, mark the account's data as pending removal after logout.
1693   if (IsLoggedInAsPublicAccount()) {
1694     const std::string active_user_id = GetActiveUser()->email();
1695     if (users.find(active_user_id) == users.end()) {
1696       g_browser_process->local_state()->SetString(
1697           kPublicAccountPendingDataRemoval, active_user_id);
1698       users.insert(active_user_id);
1699     }
1700   }
1701
1702   // Remove the data belonging to any other public accounts that are no longer
1703   // found on the user list.
1704   for (std::vector<std::string>::const_iterator
1705            it = old_public_accounts.begin();
1706        it != old_public_accounts.end(); ++it) {
1707     if (users.find(*it) == users.end())
1708       RemoveNonCryptohomeData(*it);
1709   }
1710 }
1711
1712 bool UserManagerImpl::UpdateAndCleanUpPublicAccounts(
1713     const std::vector<policy::DeviceLocalAccount>& device_local_accounts) {
1714   // Try to remove any public account data marked as pending removal.
1715   CleanUpPublicAccountNonCryptohomeDataPendingRemoval();
1716
1717   // Get the current list of public accounts.
1718   std::vector<std::string> old_public_accounts;
1719   for (UserList::const_iterator it = users_.begin(); it != users_.end(); ++it) {
1720     if ((*it)->GetType() == User::USER_TYPE_PUBLIC_ACCOUNT)
1721       old_public_accounts.push_back((*it)->email());
1722   }
1723
1724   // Get the new list of public accounts from policy.
1725   std::vector<std::string> new_public_accounts;
1726   for (std::vector<policy::DeviceLocalAccount>::const_iterator it =
1727            device_local_accounts.begin();
1728        it != device_local_accounts.end(); ++it) {
1729     // TODO(mnissler, nkostylev, bartfab): Process Kiosk Apps within the
1730     // standard login framework: http://crbug.com/234694
1731     if (it->type == policy::DeviceLocalAccount::TYPE_PUBLIC_SESSION)
1732       new_public_accounts.push_back(it->user_id);
1733   }
1734
1735   // If the list of public accounts has not changed, return.
1736   if (new_public_accounts.size() == old_public_accounts.size()) {
1737     bool changed = false;
1738     for (size_t i = 0; i < new_public_accounts.size(); ++i) {
1739       if (new_public_accounts[i] != old_public_accounts[i]) {
1740         changed = true;
1741         break;
1742       }
1743     }
1744     if (!changed)
1745       return false;
1746   }
1747
1748   // Persist the new list of public accounts in a pref.
1749   ListPrefUpdate prefs_public_accounts_update(g_browser_process->local_state(),
1750                                               kPublicAccounts);
1751   prefs_public_accounts_update->Clear();
1752   for (std::vector<std::string>::const_iterator it =
1753            new_public_accounts.begin();
1754        it != new_public_accounts.end(); ++it) {
1755     prefs_public_accounts_update->AppendString(*it);
1756   }
1757
1758   // Remove the old public accounts from the user list.
1759   for (UserList::iterator it = users_.begin(); it != users_.end();) {
1760     if ((*it)->GetType() == User::USER_TYPE_PUBLIC_ACCOUNT) {
1761       if (*it != GetLoggedInUser())
1762         DeleteUser(*it);
1763       it = users_.erase(it);
1764     } else {
1765       ++it;
1766     }
1767   }
1768
1769   // Add the new public accounts to the front of the user list.
1770   for (std::vector<std::string>::const_reverse_iterator it =
1771            new_public_accounts.rbegin();
1772        it != new_public_accounts.rend(); ++it) {
1773     if (IsLoggedInAsPublicAccount() && *it == GetActiveUser()->email())
1774       users_.insert(users_.begin(), GetLoggedInUser());
1775     else
1776       users_.insert(users_.begin(), User::CreatePublicAccountUser(*it));
1777     UpdatePublicAccountDisplayName(*it);
1778   }
1779
1780   for (UserList::iterator ui = users_.begin(),
1781                           ue = users_.begin() + new_public_accounts.size();
1782        ui != ue; ++ui) {
1783     GetUserImageManager((*ui)->email())->LoadUserImage();
1784   }
1785
1786   // Remove data belonging to public accounts that are no longer found on the
1787   // user list.
1788   CleanUpPublicAccountNonCryptohomeData(old_public_accounts);
1789
1790   return true;
1791 }
1792
1793 void UserManagerImpl::UpdatePublicAccountDisplayName(
1794     const std::string& user_id) {
1795   std::string display_name;
1796
1797   if (device_local_account_policy_service_) {
1798     policy::DeviceLocalAccountPolicyBroker* broker =
1799         device_local_account_policy_service_->GetBrokerForUser(user_id);
1800     if (broker)
1801       display_name = broker->GetDisplayName();
1802   }
1803
1804   // Set or clear the display name.
1805   SaveUserDisplayName(user_id, base::UTF8ToUTF16(display_name));
1806 }
1807
1808 UserFlow* UserManagerImpl::GetCurrentUserFlow() const {
1809   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1810   if (!IsUserLoggedIn())
1811     return GetDefaultUserFlow();
1812   return GetUserFlow(GetLoggedInUser()->email());
1813 }
1814
1815 UserFlow* UserManagerImpl::GetUserFlow(const std::string& user_id) const {
1816   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1817   FlowMap::const_iterator it = specific_flows_.find(user_id);
1818   if (it != specific_flows_.end())
1819     return it->second;
1820   return GetDefaultUserFlow();
1821 }
1822
1823 void UserManagerImpl::SetUserFlow(const std::string& user_id, UserFlow* flow) {
1824   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1825   ResetUserFlow(user_id);
1826   specific_flows_[user_id] = flow;
1827 }
1828
1829 void UserManagerImpl::ResetUserFlow(const std::string& user_id) {
1830   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1831   FlowMap::iterator it = specific_flows_.find(user_id);
1832   if (it != specific_flows_.end()) {
1833     delete it->second;
1834     specific_flows_.erase(it);
1835   }
1836 }
1837
1838 bool UserManagerImpl::GetAppModeChromeClientOAuthInfo(
1839     std::string* chrome_client_id, std::string* chrome_client_secret) {
1840   if (!chrome::IsRunningInForcedAppMode() ||
1841       chrome_client_id_.empty() ||
1842       chrome_client_secret_.empty()) {
1843     return false;
1844   }
1845
1846   *chrome_client_id = chrome_client_id_;
1847   *chrome_client_secret = chrome_client_secret_;
1848   return true;
1849 }
1850
1851 void UserManagerImpl::SetAppModeChromeClientOAuthInfo(
1852     const std::string& chrome_client_id,
1853     const std::string& chrome_client_secret) {
1854   if (!chrome::IsRunningInForcedAppMode())
1855     return;
1856
1857   chrome_client_id_ = chrome_client_id;
1858   chrome_client_secret_ = chrome_client_secret;
1859 }
1860
1861 bool UserManagerImpl::AreLocallyManagedUsersAllowed() const {
1862   bool locally_managed_users_allowed = false;
1863   cros_settings_->GetBoolean(kAccountsPrefSupervisedUsersEnabled,
1864                              &locally_managed_users_allowed);
1865   policy::BrowserPolicyConnectorChromeOS* connector =
1866       g_browser_process->platform_part()->browser_policy_connector_chromeos();
1867   return locally_managed_users_allowed || !connector->IsEnterpriseManaged();
1868 }
1869
1870 base::FilePath UserManagerImpl::GetUserProfileDir(
1871     const std::string& user_id) const {
1872   // TODO(dpolukhin): Remove Chrome OS specific profile path logic from
1873   // ProfileManager and use only this function to construct profile path.
1874   // TODO(nkostylev): Cleanup profile dir related code paths crbug.com/294233
1875   base::FilePath profile_dir;
1876   const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1877   if (command_line.HasSwitch(::switches::kMultiProfiles)) {
1878     const User* user = FindUser(user_id);
1879     if (user && !user->username_hash().empty())
1880       profile_dir = ProfileHelper::GetUserProfileDir(user->username_hash());
1881   } else if (command_line.HasSwitch(chromeos::switches::kLoginProfile)) {
1882     profile_dir = ProfileHelper::GetProfileDirByLegacyLoginProfileSwitch();
1883   } else {
1884     // We should never be logged in with no profile dir unless
1885     // multi-profiles are enabled.
1886     NOTREACHED();
1887     profile_dir = base::FilePath();
1888   }
1889
1890   ProfileManager* profile_manager = g_browser_process->profile_manager();
1891   profile_dir = profile_manager->user_data_dir().Append(profile_dir);
1892
1893   return profile_dir;
1894 }
1895
1896 UserFlow* UserManagerImpl::GetDefaultUserFlow() const {
1897   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1898   if (!default_flow_.get())
1899     default_flow_.reset(new DefaultUserFlow());
1900   return default_flow_.get();
1901 }
1902
1903 void UserManagerImpl::NotifyUserListChanged() {
1904   content::NotificationService::current()->Notify(
1905       chrome::NOTIFICATION_USER_LIST_CHANGED,
1906       content::Source<UserManager>(this),
1907       content::NotificationService::NoDetails());
1908 }
1909
1910 void UserManagerImpl::NotifyActiveUserChanged(const User* active_user) {
1911   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1912   FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
1913                     session_state_observer_list_,
1914                     ActiveUserChanged(active_user));
1915 }
1916
1917 void UserManagerImpl::NotifyUserAddedToSession(const User* added_user) {
1918   UpdateNumberOfUsers();
1919   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1920   FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
1921                     session_state_observer_list_,
1922                     UserAddedToSession(added_user));
1923 }
1924
1925 void UserManagerImpl::NotifyActiveUserHashChanged(const std::string& hash) {
1926   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1927   FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
1928                     session_state_observer_list_,
1929                     ActiveUserHashChanged(hash));
1930 }
1931
1932 void UserManagerImpl::NotifyPendingUserSessionsRestoreFinished() {
1933   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1934   user_sessions_restored_ = true;
1935   FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
1936                     session_state_observer_list_,
1937                     PendingUserSessionsRestoreFinished());
1938 }
1939
1940 void UserManagerImpl::UpdateLoginState() {
1941   if (!LoginState::IsInitialized())
1942     return;  // LoginState may not be intialized in tests.
1943   LoginState::LoggedInState logged_in_state;
1944   logged_in_state = active_user_ ? LoginState::LOGGED_IN_ACTIVE
1945       : LoginState::LOGGED_IN_NONE;
1946
1947   LoginState::LoggedInUserType login_user_type;
1948   if (logged_in_state == LoginState::LOGGED_IN_NONE)
1949     login_user_type = LoginState::LOGGED_IN_USER_NONE;
1950   else if (is_current_user_owner_)
1951     login_user_type = LoginState::LOGGED_IN_USER_OWNER;
1952   else if (active_user_->GetType() == User::USER_TYPE_GUEST)
1953     login_user_type = LoginState::LOGGED_IN_USER_GUEST;
1954   else if (active_user_->GetType() == User::USER_TYPE_RETAIL_MODE)
1955     login_user_type = LoginState::LOGGED_IN_USER_RETAIL_MODE;
1956   else if (active_user_->GetType() == User::USER_TYPE_PUBLIC_ACCOUNT)
1957     login_user_type = LoginState::LOGGED_IN_USER_PUBLIC_ACCOUNT;
1958   else if (active_user_->GetType() == User::USER_TYPE_LOCALLY_MANAGED)
1959     login_user_type = LoginState::LOGGED_IN_USER_LOCALLY_MANAGED;
1960   else if (active_user_->GetType() == User::USER_TYPE_KIOSK_APP)
1961     login_user_type = LoginState::LOGGED_IN_USER_KIOSK_APP;
1962   else
1963     login_user_type = LoginState::LOGGED_IN_USER_REGULAR;
1964
1965   LoginState::Get()->SetLoggedInState(logged_in_state, login_user_type);
1966 }
1967
1968 void UserManagerImpl::SetLRUUser(User* user) {
1969   UserList::iterator it = std::find(lru_logged_in_users_.begin(),
1970                                     lru_logged_in_users_.end(),
1971                                     user);
1972   if (it != lru_logged_in_users_.end())
1973     lru_logged_in_users_.erase(it);
1974   lru_logged_in_users_.insert(lru_logged_in_users_.begin(), user);
1975 }
1976
1977 void UserManagerImpl::OnRestoreActiveSessions(
1978     const SessionManagerClient::ActiveSessionsMap& sessions,
1979     bool success) {
1980   if (!success) {
1981     LOG(ERROR) << "Could not get list of active user sessions after crash.";
1982     // If we could not get list of active user sessions it is safer to just
1983     // sign out so that we don't get in the inconsistent state.
1984     DBusThreadManager::Get()->GetSessionManagerClient()->StopSession();
1985     return;
1986   }
1987
1988   // One profile has been already loaded on browser start.
1989   DCHECK(GetLoggedInUsers().size() == 1);
1990   DCHECK(GetActiveUser());
1991   std::string active_user_id = GetActiveUser()->email();
1992
1993   SessionManagerClient::ActiveSessionsMap::const_iterator it;
1994   for (it = sessions.begin(); it != sessions.end(); ++it) {
1995     if (active_user_id == it->first)
1996       continue;
1997     pending_user_sessions_[it->first] = it->second;
1998   }
1999   RestorePendingUserSessions();
2000 }
2001
2002 void UserManagerImpl::RestorePendingUserSessions() {
2003   if (pending_user_sessions_.empty()) {
2004     NotifyPendingUserSessionsRestoreFinished();
2005     return;
2006   }
2007
2008   // Get next user to restore sessions and delete it from list.
2009   SessionManagerClient::ActiveSessionsMap::const_iterator it =
2010       pending_user_sessions_.begin();
2011   std::string user_id = it->first;
2012   std::string user_id_hash = it->second;
2013   DCHECK(!user_id.empty());
2014   DCHECK(!user_id_hash.empty());
2015   pending_user_sessions_.erase(user_id);
2016
2017   // Check that this user is not logged in yet.
2018   UserList logged_in_users = GetLoggedInUsers();
2019   bool user_already_logged_in = false;
2020   for (UserList::const_iterator it = logged_in_users.begin();
2021        it != logged_in_users.end(); ++it) {
2022     const User* user = (*it);
2023     if (user->email() == user_id) {
2024       user_already_logged_in = true;
2025       break;
2026     }
2027   }
2028   DCHECK(!user_already_logged_in);
2029
2030   if (!user_already_logged_in) {
2031     // Will call OnProfilePrepared() once profile has been loaded.
2032     LoginUtils::Get()->PrepareProfile(
2033         UserContext(user_id,
2034                     std::string(),  // password
2035                     std::string(),  // auth_code
2036                     user_id_hash,
2037                     false,         // using_oauth
2038                     UserContext::AUTH_FLOW_OFFLINE),
2039         std::string(),  // display_email
2040         false,          // has_cookies
2041         true,           // has_active_session
2042         this);
2043   } else {
2044     RestorePendingUserSessions();
2045   }
2046 }
2047
2048 void UserManagerImpl::SendRegularUserLoginMetrics(const std::string& user_id) {
2049   // If this isn't the first time Chrome was run after the system booted,
2050   // assume that Chrome was restarted because a previous session ended.
2051   if (!CommandLine::ForCurrentProcess()->HasSwitch(
2052           switches::kFirstExecAfterBoot)) {
2053     const std::string last_email =
2054         g_browser_process->local_state()->GetString(kLastLoggedInRegularUser);
2055     const base::TimeDelta time_to_login =
2056         base::TimeTicks::Now() - manager_creation_time_;
2057     if (!last_email.empty() && user_id != last_email &&
2058         time_to_login.InSeconds() <= kLogoutToLoginDelayMaxSec) {
2059       UMA_HISTOGRAM_CUSTOM_COUNTS("UserManager.LogoutToLoginDelay",
2060           time_to_login.InSeconds(), 0, kLogoutToLoginDelayMaxSec, 50);
2061     }
2062   }
2063 }
2064
2065 void UserManagerImpl::OnUserNotAllowed(const std::string& user_email) {
2066   LOG(ERROR) << "Shutdown session because a user is not allowed to be in the "
2067                 "current session";
2068   chromeos::ShowMultiprofilesSessionAbortedDialog(user_email);
2069 }
2070
2071 void UserManagerImpl::UpdateUserAccountLocale(const std::string& user_id,
2072                                               const std::string& locale) {
2073   if (!locale.empty() &&
2074       locale != g_browser_process->GetApplicationLocale()) {
2075     BrowserThread::PostBlockingPoolTask(
2076         FROM_HERE,
2077         base::Bind(ResolveLocale, locale,
2078             base::Bind(&UserManagerImpl::DoUpdateAccountLocale,
2079                        base::Unretained(this),
2080                        user_id)));
2081   } else {
2082     DoUpdateAccountLocale(user_id, locale);
2083   }
2084 }
2085
2086 void UserManagerImpl::DoUpdateAccountLocale(
2087     const std::string& user_id,
2088     const std::string& resolved_locale) {
2089   if (User* user = FindUserAndModify(user_id))
2090     user->SetAccountLocale(resolved_locale);
2091 }
2092
2093 void UserManagerImpl::UpdateNumberOfUsers() {
2094   size_t users = GetLoggedInUsers().size();
2095   if (users) {
2096     // Write the user number as UMA stat when a multi user session is possible.
2097     if ((users + GetUsersAdmittedForMultiProfile().size()) > 1)
2098       ash::MultiProfileUMA::RecordUserCount(users);
2099   }
2100
2101   base::debug::SetCrashKeyValue(crash_keys::kNumberOfUsers,
2102       base::StringPrintf("%" PRIuS, GetLoggedInUsers().size()));
2103 }
2104
2105 void UserManagerImpl::DeleteUser(User* user) {
2106   const bool is_active_user = (user == active_user_);
2107   delete user;
2108   if (is_active_user)
2109     active_user_ = NULL;
2110 }
2111
2112 }  // namespace chromeos