Home | History | Annotate | Download | only in login
      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 "base/bind.h"
     11 #include "base/bind_helpers.h"
     12 #include "base/chromeos/chromeos_version.h"
     13 #include "base/command_line.h"
     14 #include "base/compiler_specific.h"
     15 #include "base/files/file_path.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/rand_util.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/values.h"
     25 #include "chrome/browser/app_mode/app_mode_utils.h"
     26 #include "chrome/browser/browser_process.h"
     27 #include "chrome/browser/chrome_notification_types.h"
     28 #include "chrome/browser/chromeos/cros/cert_library.h"
     29 #include "chrome/browser/chromeos/login/default_pinned_apps_field_trial.h"
     30 #include "chrome/browser/chromeos/login/login_display.h"
     31 #include "chrome/browser/chromeos/login/login_utils.h"
     32 #include "chrome/browser/chromeos/login/remove_user_delegate.h"
     33 #include "chrome/browser/chromeos/login/user_image_manager_impl.h"
     34 #include "chrome/browser/chromeos/login/wizard_controller.h"
     35 #include "chrome/browser/chromeos/policy/device_local_account.h"
     36 #include "chrome/browser/chromeos/session_length_limiter.h"
     37 #include "chrome/browser/chromeos/settings/cros_settings_names.h"
     38 #include "chrome/browser/managed_mode/managed_user_service.h"
     39 #include "chrome/browser/policy/browser_policy_connector.h"
     40 #include "chrome/browser/prefs/scoped_user_pref_update.h"
     41 #include "chrome/browser/profiles/profile_manager.h"
     42 #include "chrome/browser/sync/profile_sync_service.h"
     43 #include "chrome/browser/sync/profile_sync_service_factory.h"
     44 #include "chrome/common/chrome_switches.h"
     45 #include "chrome/common/pref_names.h"
     46 #include "chromeos/chromeos_switches.h"
     47 #include "chromeos/cryptohome/async_method_caller.h"
     48 #include "chromeos/dbus/dbus_thread_manager.h"
     49 #include "chromeos/ime/input_method_manager.h"
     50 #include "chromeos/login/login_state.h"
     51 #include "content/public/browser/browser_thread.h"
     52 #include "content/public/browser/notification_service.h"
     53 #include "google_apis/gaia/gaia_auth_util.h"
     54 #include "google_apis/gaia/google_service_auth_error.h"
     55 #include "policy/policy_constants.h"
     56 #include "ui/views/corewm/corewm_switches.h"
     57 
     58 using content::BrowserThread;
     59 
     60 namespace chromeos {
     61 
     62 namespace {
     63 
     64 // A vector pref of the the regular users known on this device, arranged in LRU
     65 // order.
     66 const char kRegularUsers[] = "LoggedInUsers";
     67 
     68 // A vector pref of the public accounts defined on this device.
     69 const char kPublicAccounts[] = "PublicAccounts";
     70 
     71 // A map from locally managed user local user id to sync user id.
     72 const char kManagedUserSyncId[] =
     73     "ManagedUserSyncId";
     74 
     75 // A map from locally managed user id to manager user id.
     76 const char kManagedUserManagers[] =
     77     "ManagedUserManagers";
     78 
     79 // A map from locally managed user id to manager display name.
     80 const char kManagedUserManagerNames[] =
     81     "ManagedUserManagerNames";
     82 
     83 // A map from locally managed user id to manager display e-mail.
     84 const char kManagedUserManagerDisplayEmails[] =
     85     "ManagedUserManagerDisplayEmails";
     86 
     87 // A vector pref of the locally managed accounts defined on this device, that
     88 // had not logged in yet.
     89 const char kLocallyManagedUsersFirstRun[] = "LocallyManagedUsersFirstRun";
     90 
     91 // A pref of the next id for locally managed users generation.
     92 const char kLocallyManagedUsersNextId[] =
     93     "LocallyManagedUsersNextId";
     94 
     95 // A pref of the next id for locally managed users generation.
     96 const char kLocallyManagedUserCreationTransactionDisplayName[] =
     97     "LocallyManagedUserCreationTransactionDisplayName";
     98 
     99 // A pref of the next id for locally managed users generation.
    100 const char kLocallyManagedUserCreationTransactionUserId[] =
    101     "LocallyManagedUserCreationTransactionUserId";
    102 
    103 // A string pref that gets set when a public account is removed but a user is
    104 // currently logged into that account, requiring the account's data to be
    105 // removed after logout.
    106 const char kPublicAccountPendingDataRemoval[] =
    107     "PublicAccountPendingDataRemoval";
    108 
    109 // A dictionary that maps usernames to the displayed name.
    110 const char kUserDisplayName[] = "UserDisplayName";
    111 
    112 // A dictionary that maps usernames to the displayed (non-canonical) emails.
    113 const char kUserDisplayEmail[] = "UserDisplayEmail";
    114 
    115 // A dictionary that maps usernames to OAuth token presence flag.
    116 const char kUserOAuthTokenStatus[] = "OAuthTokenStatus";
    117 
    118 // A string pref containing the ID of the last user who logged in if it was
    119 // a regular user or an empty string if it was another type of user (guest,
    120 // kiosk, public account, etc.).
    121 const char kLastLoggedInRegularUser[] = "LastLoggedInRegularUser";
    122 
    123 // Upper bound for a histogram metric reporting the amount of time between
    124 // one regular user logging out and a different regular user logging in.
    125 const int kLogoutToLoginDelayMaxSec = 1800;
    126 
    127 // Callback that is called after user removal is complete.
    128 void OnRemoveUserComplete(const std::string& user_email,
    129                           bool success,
    130                           cryptohome::MountError return_code) {
    131   // Log the error, but there's not much we can do.
    132   if (!success) {
    133     LOG(ERROR) << "Removal of cryptohome for " << user_email
    134                << " failed, return code: " << return_code;
    135   }
    136 }
    137 
    138 // This method is used to implement UserManager::RemoveUser.
    139 void RemoveUserInternal(const std::string& user_email,
    140                         chromeos::RemoveUserDelegate* delegate) {
    141   CrosSettings* cros_settings = CrosSettings::Get();
    142 
    143   // Ensure the value of owner email has been fetched.
    144   if (CrosSettingsProvider::TRUSTED != cros_settings->PrepareTrustedValues(
    145           base::Bind(&RemoveUserInternal, user_email, delegate))) {
    146     // Value of owner email is not fetched yet.  RemoveUserInternal will be
    147     // called again after fetch completion.
    148     return;
    149   }
    150   std::string owner;
    151   cros_settings->GetString(kDeviceOwner, &owner);
    152   if (user_email == owner) {
    153     // Owner is not allowed to be removed from the device.
    154     return;
    155   }
    156 
    157   if (delegate)
    158     delegate->OnBeforeUserRemoved(user_email);
    159 
    160   chromeos::UserManager::Get()->RemoveUserFromList(user_email);
    161   cryptohome::AsyncMethodCaller::GetInstance()->AsyncRemove(
    162       user_email, base::Bind(&OnRemoveUserComplete, user_email));
    163 
    164   if (delegate)
    165     delegate->OnUserRemoved(user_email);
    166 }
    167 
    168 // Helper function that copies users from |users_list| to |users_vector| and
    169 // |users_set|. Duplicates and users already present in |existing_users| are
    170 // skipped.
    171 void ParseUserList(const ListValue& users_list,
    172                    const std::set<std::string>& existing_users,
    173                    std::vector<std::string>* users_vector,
    174                    std::set<std::string>* users_set) {
    175   users_vector->clear();
    176   users_set->clear();
    177   for (size_t i = 0; i < users_list.GetSize(); ++i) {
    178     std::string email;
    179     if (!users_list.GetString(i, &email) || email.empty()) {
    180       LOG(ERROR) << "Corrupt entry in user list at index " << i << ".";
    181       continue;
    182     }
    183     if (existing_users.find(email) != existing_users.end() ||
    184         !users_set->insert(email).second) {
    185       LOG(ERROR) << "Duplicate user: " << email;
    186       continue;
    187     }
    188     users_vector->push_back(email);
    189   }
    190 }
    191 
    192 }  // namespace
    193 
    194 // static
    195 void UserManager::RegisterPrefs(PrefRegistrySimple* registry) {
    196   registry->RegisterListPref(kRegularUsers);
    197   registry->RegisterListPref(kPublicAccounts);
    198   registry->RegisterListPref(kLocallyManagedUsersFirstRun);
    199   registry->RegisterIntegerPref(kLocallyManagedUsersNextId, 0);
    200   registry->RegisterStringPref(kPublicAccountPendingDataRemoval, "");
    201   registry->RegisterStringPref(
    202       kLocallyManagedUserCreationTransactionDisplayName, "");
    203   registry->RegisterStringPref(
    204       kLocallyManagedUserCreationTransactionUserId, "");
    205   registry->RegisterStringPref(kLastLoggedInRegularUser, "");
    206   registry->RegisterDictionaryPref(kUserOAuthTokenStatus);
    207   registry->RegisterDictionaryPref(kUserDisplayName);
    208   registry->RegisterDictionaryPref(kUserDisplayEmail);
    209   registry->RegisterDictionaryPref(kManagedUserSyncId);
    210   registry->RegisterDictionaryPref(kManagedUserManagers);
    211   registry->RegisterDictionaryPref(kManagedUserManagerNames);
    212   registry->RegisterDictionaryPref(kManagedUserManagerDisplayEmails);
    213 
    214   SessionLengthLimiter::RegisterPrefs(registry);
    215 }
    216 
    217 UserManagerImpl::UserManagerImpl()
    218     : cros_settings_(CrosSettings::Get()),
    219       device_local_account_policy_service_(NULL),
    220       users_loaded_(false),
    221       active_user_(NULL),
    222       session_started_(false),
    223       user_sessions_restored_(false),
    224       is_current_user_owner_(false),
    225       is_current_user_new_(false),
    226       is_current_user_ephemeral_regular_user_(false),
    227       ephemeral_users_enabled_(false),
    228       locally_managed_users_enabled_by_policy_(false),
    229       merge_session_state_(MERGE_STATUS_NOT_STARTED),
    230       observed_sync_service_(NULL),
    231       user_image_manager_(new UserImageManagerImpl),
    232       manager_creation_time_(base::TimeTicks::Now()) {
    233   // UserManager instance should be used only on UI thread.
    234   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    235   registrar_.Add(this, chrome::NOTIFICATION_OWNERSHIP_STATUS_CHANGED,
    236       content::NotificationService::AllSources());
    237   registrar_.Add(this, chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED,
    238       content::NotificationService::AllSources());
    239   RetrieveTrustedDevicePolicies();
    240   cros_settings_->AddSettingsObserver(kAccountsPrefDeviceLocalAccounts,
    241                                       this);
    242   cros_settings_->AddSettingsObserver(kAccountsPrefSupervisedUsersEnabled,
    243                                       this);
    244   UpdateLoginState();
    245 }
    246 
    247 UserManagerImpl::~UserManagerImpl() {
    248   // Can't use STLDeleteElements because of the private destructor of User.
    249   for (UserList::iterator it = users_.begin(); it != users_.end();
    250        it = users_.erase(it)) {
    251     if (active_user_ == *it)
    252       active_user_ = NULL;
    253     delete *it;
    254   }
    255   // These are pointers to the same User instances that were in users_ list.
    256   logged_in_users_.clear();
    257   lru_logged_in_users_.clear();
    258 
    259   delete active_user_;
    260 }
    261 
    262 void UserManagerImpl::Shutdown() {
    263   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    264   cros_settings_->RemoveSettingsObserver(kAccountsPrefDeviceLocalAccounts,
    265                                          this);
    266   cros_settings_->RemoveSettingsObserver(
    267       kAccountsPrefSupervisedUsersEnabled,
    268       this);
    269   // Stop the session length limiter.
    270   session_length_limiter_.reset();
    271 
    272   if (device_local_account_policy_service_)
    273     device_local_account_policy_service_->RemoveObserver(this);
    274 
    275   if (observed_sync_service_)
    276     observed_sync_service_->RemoveObserver(this);
    277   user_image_manager_->Shutdown();
    278 }
    279 
    280 UserImageManager* UserManagerImpl::GetUserImageManager() {
    281   return user_image_manager_.get();
    282 }
    283 
    284 const UserList& UserManagerImpl::GetUsers() const {
    285   const_cast<UserManagerImpl*>(this)->EnsureUsersLoaded();
    286   return users_;
    287 }
    288 
    289 UserList UserManagerImpl::GetUsersAdmittedForMultiProfile() const {
    290   UserList result;
    291   const UserList& users = GetUsers();
    292   for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) {
    293     if ((*it)->GetType() == User::USER_TYPE_REGULAR && !(*it)->is_logged_in())
    294       result.push_back(*it);
    295   }
    296   return result;
    297 }
    298 
    299 const UserList& UserManagerImpl::GetLoggedInUsers() const {
    300   return logged_in_users_;
    301 }
    302 
    303 const UserList& UserManagerImpl::GetLRULoggedInUsers() {
    304   // If there is no user logged in, we return the active user as the only one.
    305   if (lru_logged_in_users_.empty() && active_user_) {
    306     temp_single_logged_in_users_.clear();
    307     temp_single_logged_in_users_.insert(temp_single_logged_in_users_.begin(),
    308                                         active_user_);
    309     return temp_single_logged_in_users_;
    310   }
    311   return lru_logged_in_users_;
    312 }
    313 
    314 void UserManagerImpl::UserLoggedIn(const std::string& email,
    315                                    const std::string& username_hash,
    316                                    bool browser_restart) {
    317   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    318 
    319   if (!CommandLine::ForCurrentProcess()->HasSwitch(::switches::kMultiProfiles))
    320     DCHECK(!IsUserLoggedIn());
    321 
    322   if (active_user_)
    323     active_user_->set_is_active(false);
    324 
    325   if (email == UserManager::kGuestUserName) {
    326     GuestUserLoggedIn();
    327   } else if (email == UserManager::kRetailModeUserName) {
    328     RetailModeUserLoggedIn();
    329   } else if (policy::IsKioskAppUser(email)) {
    330     KioskAppLoggedIn(email);
    331   } else {
    332     EnsureUsersLoaded();
    333 
    334     User* user = FindUserInListAndModify(email);
    335     if (user && user->GetType() == User::USER_TYPE_PUBLIC_ACCOUNT) {
    336       PublicAccountUserLoggedIn(user);
    337     } else if ((user && user->GetType() == User::USER_TYPE_LOCALLY_MANAGED) ||
    338                (!user && gaia::ExtractDomainName(email) ==
    339                     UserManager::kLocallyManagedUserDomain)) {
    340       LocallyManagedUserLoggedIn(email);
    341     } else if (browser_restart && email == g_browser_process->local_state()->
    342                    GetString(kPublicAccountPendingDataRemoval)) {
    343       PublicAccountUserLoggedIn(User::CreatePublicAccountUser(email));
    344     } else if (email != owner_email_ && !user &&
    345                (AreEphemeralUsersEnabled() || browser_restart)) {
    346       RegularUserLoggedInAsEphemeral(email);
    347     } else {
    348       RegularUserLoggedIn(email, browser_restart);
    349     }
    350 
    351     // Initialize the session length limiter and start it only if
    352     // session limit is defined by the policy.
    353     session_length_limiter_.reset(new SessionLengthLimiter(NULL,
    354                                                            browser_restart));
    355   }
    356   DCHECK(active_user_);
    357   active_user_->set_is_logged_in(true);
    358   active_user_->set_is_active(true);
    359   active_user_->set_username_hash(username_hash);
    360 
    361   // Place user who just signed in to the top of the logged in users.
    362   logged_in_users_.insert(logged_in_users_.begin(), active_user_);
    363   SetLRUUser(active_user_);
    364 
    365   UMA_HISTOGRAM_ENUMERATION("UserManager.LoginUserType",
    366                             active_user_->GetType(), User::NUM_USER_TYPES);
    367 
    368   if (active_user_->GetType() == User::USER_TYPE_REGULAR)
    369     SendRegularUserLoginMetrics(email);
    370   g_browser_process->local_state()->SetString(kLastLoggedInRegularUser,
    371     (active_user_->GetType() == User::USER_TYPE_REGULAR) ? email : "");
    372 
    373   NotifyOnLogin();
    374 }
    375 
    376 void UserManagerImpl::SwitchActiveUser(const std::string& email) {
    377   if (!CommandLine::ForCurrentProcess()->HasSwitch(::switches::kMultiProfiles))
    378     return;
    379 
    380   User* user = FindUserAndModify(email);
    381   if (!user) {
    382     NOTREACHED() << "Switching to a non-existing user";
    383     return;
    384   }
    385   if (user == active_user_) {
    386     NOTREACHED() << "Switching to a user who is already active";
    387     return;
    388   }
    389   if (!user->is_logged_in()) {
    390     NOTREACHED() << "Switching to a user that is not logged in";
    391     return;
    392   }
    393   if (user->GetType() != User::USER_TYPE_REGULAR) {
    394     NOTREACHED() << "Switching to a non-regular user";
    395     return;
    396   }
    397   if (user->username_hash().empty()) {
    398     NOTREACHED() << "Switching to a user that doesn't have username_hash set";
    399     return;
    400   }
    401 
    402   DCHECK(active_user_);
    403   active_user_->set_is_active(false);
    404   user->set_is_active(true);
    405   active_user_ = user;
    406 
    407   // Move the user to the front.
    408   SetLRUUser(active_user_);
    409 
    410   NotifyActiveUserHashChanged(active_user_->username_hash());
    411   NotifyActiveUserChanged(active_user_);
    412 }
    413 
    414 void UserManagerImpl::RestoreActiveSessions() {
    415   DBusThreadManager::Get()->GetSessionManagerClient()->RetrieveActiveSessions(
    416       base::Bind(&UserManagerImpl::OnRestoreActiveSessions,
    417                  base::Unretained(this)));
    418 }
    419 
    420 void UserManagerImpl::SessionStarted() {
    421   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    422   session_started_ = true;
    423   UpdateLoginState();
    424   content::NotificationService::current()->Notify(
    425       chrome::NOTIFICATION_SESSION_STARTED,
    426       content::Source<UserManager>(this),
    427       content::Details<const User>(active_user_));
    428   if (is_current_user_new_) {
    429     // Make sure that the new user's data is persisted to Local State.
    430     g_browser_process->local_state()->CommitPendingWrite();
    431   }
    432 }
    433 
    434 std::string UserManagerImpl::GenerateUniqueLocallyManagedUserId() {
    435   int counter = g_browser_process->local_state()->
    436       GetInteger(kLocallyManagedUsersNextId);
    437   std::string id;
    438   bool user_exists;
    439   do {
    440     id = base::StringPrintf("%d@%s", counter, kLocallyManagedUserDomain);
    441     counter++;
    442     user_exists = (NULL != FindUser(id));
    443     DCHECK(!user_exists);
    444     if (user_exists) {
    445       LOG(ERROR) << "Locally managed user with id " << id << " already exists.";
    446     }
    447   } while (user_exists);
    448 
    449   g_browser_process->local_state()->
    450       SetInteger(kLocallyManagedUsersNextId, counter);
    451 
    452   g_browser_process->local_state()->CommitPendingWrite();
    453   return id;
    454 }
    455 
    456 const User* UserManagerImpl::CreateLocallyManagedUserRecord(
    457       const std::string& manager_id,
    458       const std::string& local_user_id,
    459       const std::string& sync_user_id,
    460       const string16& display_name) {
    461   const User* user = FindLocallyManagedUser(display_name);
    462   DCHECK(!user);
    463   if (user)
    464     return user;
    465 
    466   PrefService* local_state = g_browser_process->local_state();
    467 
    468   User* new_user = User::CreateLocallyManagedUser(local_user_id);
    469   ListPrefUpdate prefs_users_update(local_state, kRegularUsers);
    470   prefs_users_update->Insert(0, new base::StringValue(local_user_id));
    471   ListPrefUpdate prefs_new_users_update(local_state,
    472                                         kLocallyManagedUsersFirstRun);
    473   prefs_new_users_update->Insert(0, new base::StringValue(local_user_id));
    474   users_.insert(users_.begin(), new_user);
    475 
    476   const User* manager = FindUser(manager_id);
    477   CHECK(manager);
    478 
    479   DictionaryPrefUpdate sync_id_update(local_state, kManagedUserSyncId);
    480   DictionaryPrefUpdate manager_update(local_state, kManagedUserManagers);
    481   DictionaryPrefUpdate manager_name_update(local_state,
    482                                            kManagedUserManagerNames);
    483   DictionaryPrefUpdate manager_email_update(local_state,
    484                                             kManagedUserManagerDisplayEmails);
    485   sync_id_update->SetWithoutPathExpansion(local_user_id,
    486       new base::StringValue(sync_user_id));
    487   manager_update->SetWithoutPathExpansion(local_user_id,
    488       new base::StringValue(manager->email()));
    489   manager_name_update->SetWithoutPathExpansion(local_user_id,
    490       new base::StringValue(manager->GetDisplayName()));
    491   manager_email_update->SetWithoutPathExpansion(local_user_id,
    492       new base::StringValue(manager->display_email()));
    493 
    494   SaveUserDisplayName(local_user_id, display_name);
    495   g_browser_process->local_state()->CommitPendingWrite();
    496   return new_user;
    497 }
    498 
    499 std::string UserManagerImpl::GetManagedUserSyncId(
    500     const std::string& managed_user_id) const {
    501   PrefService* local_state = g_browser_process->local_state();
    502   const DictionaryValue* sync_user_ids =
    503       local_state->GetDictionary(kManagedUserSyncId);
    504   std::string result;
    505   sync_user_ids->GetStringWithoutPathExpansion(managed_user_id, &result);
    506   return result;
    507 }
    508 
    509 string16 UserManagerImpl::GetManagerDisplayNameForManagedUser(
    510     const std::string& managed_user_id) const {
    511   PrefService* local_state = g_browser_process->local_state();
    512 
    513   const DictionaryValue* manager_names =
    514       local_state->GetDictionary(kManagedUserManagerNames);
    515   string16 result;
    516   if (manager_names->GetStringWithoutPathExpansion(managed_user_id, &result) &&
    517       !result.empty())
    518     return result;
    519   return UTF8ToUTF16(GetManagerDisplayEmailForManagedUser(managed_user_id));
    520 }
    521 
    522 std::string UserManagerImpl::GetManagerUserIdForManagedUser(
    523       const std::string& managed_user_id) const {
    524   PrefService* local_state = g_browser_process->local_state();
    525   const DictionaryValue* manager_ids =
    526       local_state->GetDictionary(kManagedUserManagers);
    527   std::string result;
    528   manager_ids->GetStringWithoutPathExpansion(managed_user_id, &result);
    529   return result;
    530 }
    531 
    532 std::string UserManagerImpl::GetManagerDisplayEmailForManagedUser(
    533       const std::string& managed_user_id) const {
    534   PrefService* local_state = g_browser_process->local_state();
    535   const DictionaryValue* manager_mails =
    536       local_state->GetDictionary(kManagedUserManagerDisplayEmails);
    537   std::string result;
    538   if (manager_mails->GetStringWithoutPathExpansion(managed_user_id, &result) &&
    539       !result.empty()) {
    540     return result;
    541   }
    542   return GetManagerUserIdForManagedUser(managed_user_id);
    543 }
    544 
    545 void UserManagerImpl::RemoveUser(const std::string& email,
    546                                  RemoveUserDelegate* delegate) {
    547   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    548 
    549   const User* user = FindUser(email);
    550   if (!user || (user->GetType() != User::USER_TYPE_REGULAR &&
    551                 user->GetType() != User::USER_TYPE_LOCALLY_MANAGED))
    552     return;
    553 
    554   // Sanity check: we must not remove single user. This check may seem
    555   // redundant at a first sight because this single user must be an owner and
    556   // we perform special check later in order not to remove an owner.  However
    557   // due to non-instant nature of ownership assignment this later check may
    558   // sometimes fail. See http://crosbug.com/12723
    559   if (users_.size() < 2)
    560     return;
    561 
    562   // Sanity check: do not allow any of the the logged in users to be removed.
    563   for (UserList::const_iterator it = logged_in_users_.begin();
    564        it != logged_in_users_.end(); ++it) {
    565     if ((*it)->email() == email)
    566       return;
    567   }
    568 
    569   RemoveUserInternal(email, delegate);
    570 }
    571 
    572 void UserManagerImpl::RemoveUserFromList(const std::string& email) {
    573   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    574   EnsureUsersLoaded();
    575   RemoveNonCryptohomeData(email);
    576   delete RemoveRegularOrLocallyManagedUserFromList(email);
    577   // Make sure that new data is persisted to Local State.
    578   g_browser_process->local_state()->CommitPendingWrite();
    579 }
    580 
    581 bool UserManagerImpl::IsKnownUser(const std::string& email) const {
    582   return FindUser(email) != NULL;
    583 }
    584 
    585 const User* UserManagerImpl::FindUser(const std::string& email) const {
    586   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    587   if (active_user_ && active_user_->email() == email)
    588     return active_user_;
    589   return FindUserInList(email);
    590 }
    591 
    592 const User* UserManagerImpl::FindLocallyManagedUser(
    593     const string16& display_name) const {
    594   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    595   const UserList& users = GetUsers();
    596   for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) {
    597     if (((*it)->GetType() == User::USER_TYPE_LOCALLY_MANAGED) &&
    598         ((*it)->display_name() == display_name)) {
    599       return *it;
    600     }
    601   }
    602   return NULL;
    603 }
    604 
    605 const User* UserManagerImpl::GetLoggedInUser() const {
    606   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    607   return active_user_;
    608 }
    609 
    610 User* UserManagerImpl::GetLoggedInUser() {
    611   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    612   return active_user_;
    613 }
    614 
    615 const User* UserManagerImpl::GetActiveUser() const {
    616   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    617   return active_user_;
    618 }
    619 
    620 User* UserManagerImpl::GetActiveUser() {
    621   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    622   return active_user_;
    623 }
    624 
    625 void UserManagerImpl::SaveUserOAuthStatus(
    626     const std::string& username,
    627     User::OAuthTokenStatus oauth_token_status) {
    628   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    629 
    630   DVLOG(1) << "Saving user OAuth token status in Local State";
    631   User* user = FindUserAndModify(username);
    632   if (user)
    633     user->set_oauth_token_status(oauth_token_status);
    634 
    635   GetUserFlow(username)->HandleOAuthTokenStatusChange(oauth_token_status);
    636 
    637   // Do not update local store if data stored or cached outside the user's
    638   // cryptohome is to be treated as ephemeral.
    639   if (IsUserNonCryptohomeDataEphemeral(username))
    640     return;
    641 
    642   PrefService* local_state = g_browser_process->local_state();
    643 
    644   DictionaryPrefUpdate oauth_status_update(local_state, kUserOAuthTokenStatus);
    645   oauth_status_update->SetWithoutPathExpansion(username,
    646       new base::FundamentalValue(static_cast<int>(oauth_token_status)));
    647 }
    648 
    649 User::OAuthTokenStatus UserManagerImpl::LoadUserOAuthStatus(
    650     const std::string& username) const {
    651   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    652 
    653   PrefService* local_state = g_browser_process->local_state();
    654   const DictionaryValue* prefs_oauth_status =
    655       local_state->GetDictionary(kUserOAuthTokenStatus);
    656   int oauth_token_status = User::OAUTH_TOKEN_STATUS_UNKNOWN;
    657   if (prefs_oauth_status &&
    658       prefs_oauth_status->GetIntegerWithoutPathExpansion(
    659           username, &oauth_token_status)) {
    660     User::OAuthTokenStatus result =
    661         static_cast<User::OAuthTokenStatus>(oauth_token_status);
    662     if (result == User::OAUTH2_TOKEN_STATUS_INVALID)
    663       GetUserFlow(username)->HandleOAuthTokenStatusChange(result);
    664     return result;
    665   }
    666   return User::OAUTH_TOKEN_STATUS_UNKNOWN;
    667 }
    668 
    669 void UserManagerImpl::SaveUserDisplayName(const std::string& username,
    670                                           const string16& display_name) {
    671   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    672 
    673   User* user = FindUserAndModify(username);
    674   if (!user)
    675     return;  // Ignore if there is no such user.
    676 
    677   user->set_display_name(display_name);
    678 
    679   // Do not update local store if data stored or cached outside the user's
    680   // cryptohome is to be treated as ephemeral.
    681   if (IsUserNonCryptohomeDataEphemeral(username))
    682     return;
    683 
    684   PrefService* local_state = g_browser_process->local_state();
    685 
    686   DictionaryPrefUpdate display_name_update(local_state, kUserDisplayName);
    687   display_name_update->SetWithoutPathExpansion(
    688       username,
    689       new base::StringValue(display_name));
    690 
    691   // Update name if this user is manager of some managed users.
    692   const DictionaryValue* manager_ids =
    693       local_state->GetDictionary(kManagedUserManagers);
    694 
    695   DictionaryPrefUpdate manager_name_update(local_state,
    696                                            kManagedUserManagerNames);
    697   for (DictionaryValue::Iterator it(*manager_ids); !it.IsAtEnd();
    698       it.Advance()) {
    699     std::string manager_id;
    700     bool has_manager_id = it.value().GetAsString(&manager_id);
    701     DCHECK(has_manager_id);
    702     if (manager_id == username) {
    703       manager_name_update->SetWithoutPathExpansion(
    704           it.key(),
    705           new base::StringValue(display_name));
    706     }
    707   }
    708 }
    709 
    710 string16 UserManagerImpl::GetUserDisplayName(
    711     const std::string& username) const {
    712   const User* user = FindUser(username);
    713   return user ? user->display_name() : string16();
    714 }
    715 
    716 void UserManagerImpl::SaveUserDisplayEmail(const std::string& username,
    717                                            const std::string& display_email) {
    718   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    719 
    720   User* user = FindUserAndModify(username);
    721   if (!user)
    722     return;  // Ignore if there is no such user.
    723 
    724   user->set_display_email(display_email);
    725 
    726   // Do not update local store if data stored or cached outside the user's
    727   // cryptohome is to be treated as ephemeral.
    728   if (IsUserNonCryptohomeDataEphemeral(username))
    729     return;
    730 
    731   PrefService* local_state = g_browser_process->local_state();
    732 
    733   DictionaryPrefUpdate display_email_update(local_state, kUserDisplayEmail);
    734   display_email_update->SetWithoutPathExpansion(
    735       username,
    736       new base::StringValue(display_email));
    737 }
    738 
    739 std::string UserManagerImpl::GetUserDisplayEmail(
    740     const std::string& username) const {
    741   const User* user = FindUser(username);
    742   return user ? user->display_email() : username;
    743 }
    744 
    745 void UserManagerImpl::Observe(int type,
    746                               const content::NotificationSource& source,
    747                               const content::NotificationDetails& details) {
    748   switch (type) {
    749     case chrome::NOTIFICATION_OWNERSHIP_STATUS_CHANGED:
    750       if (!device_local_account_policy_service_) {
    751         device_local_account_policy_service_ =
    752             g_browser_process->browser_policy_connector()->
    753                 GetDeviceLocalAccountPolicyService();
    754         if (device_local_account_policy_service_)
    755           device_local_account_policy_service_->AddObserver(this);
    756       }
    757       CheckOwnership();
    758       RetrieveTrustedDevicePolicies();
    759       break;
    760     case chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED:
    761       if (IsUserLoggedIn() &&
    762           !IsLoggedInAsGuest() &&
    763           !IsLoggedInAsLocallyManagedUser() &&
    764           !IsLoggedInAsKioskApp()) {
    765         Profile* profile = content::Details<Profile>(details).ptr();
    766         if (!profile->IsOffTheRecord() &&
    767             profile == ProfileManager::GetDefaultProfile()) {
    768           // TODO(nkostylev): We should observe all logged in user's profiles.
    769           // http://crbug.com/230860
    770           if (!CommandLine::ForCurrentProcess()->
    771                   HasSwitch(::switches::kMultiProfiles)) {
    772             DCHECK(NULL == observed_sync_service_);
    773             observed_sync_service_ =
    774                 ProfileSyncServiceFactory::GetForProfile(profile);
    775             if (observed_sync_service_)
    776               observed_sync_service_->AddObserver(this);
    777           }
    778         }
    779       }
    780       break;
    781     case chrome::NOTIFICATION_SYSTEM_SETTING_CHANGED: {
    782       std::string changed_setting =
    783           *content::Details<const std::string>(details).ptr();
    784       DCHECK(changed_setting == kAccountsPrefDeviceLocalAccounts ||
    785              changed_setting == kAccountsPrefSupervisedUsersEnabled);
    786       RetrieveTrustedDevicePolicies();
    787       break;
    788     }
    789     default:
    790       NOTREACHED();
    791   }
    792 }
    793 
    794 void UserManagerImpl::OnStateChanged() {
    795   DCHECK(IsLoggedInAsRegularUser());
    796   GoogleServiceAuthError::State state =
    797       observed_sync_service_->GetAuthError().state();
    798   if (state != GoogleServiceAuthError::NONE &&
    799       state != GoogleServiceAuthError::CONNECTION_FAILED &&
    800       state != GoogleServiceAuthError::SERVICE_UNAVAILABLE &&
    801       state != GoogleServiceAuthError::REQUEST_CANCELED) {
    802     // Invalidate OAuth token to force Gaia sign-in flow. This is needed
    803     // because sign-out/sign-in solution is suggested to the user.
    804     // TODO(altimofeev): this code isn't needed after crosbug.com/25978 is
    805     // implemented.
    806     DVLOG(1) << "Invalidate OAuth token because of a sync error.";
    807     // http://crbug.com/230860
    808     // TODO(nkostylev): Figure out whether we want to have observers
    809     // for each logged in user.
    810     // TODO(nkostyelv): Change observer after active user has changed.
    811     SaveUserOAuthStatus(
    812         active_user_->email(),
    813         User::OAUTH2_TOKEN_STATUS_INVALID);
    814   }
    815 }
    816 
    817 void UserManagerImpl::OnPolicyUpdated(const std::string& user_id) {
    818   UpdatePublicAccountDisplayName(user_id);
    819   NotifyUserListChanged();
    820 }
    821 
    822 void UserManagerImpl::OnDeviceLocalAccountsChanged() {
    823   // No action needed here, changes to the list of device-local accounts get
    824   // handled via the kAccountsPrefDeviceLocalAccounts device setting observer.
    825 }
    826 
    827 bool UserManagerImpl::IsCurrentUserOwner() const {
    828   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    829   base::AutoLock lk(is_current_user_owner_lock_);
    830   return is_current_user_owner_;
    831 }
    832 
    833 void UserManagerImpl::SetCurrentUserIsOwner(bool is_current_user_owner) {
    834   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    835   {
    836     base::AutoLock lk(is_current_user_owner_lock_);
    837     is_current_user_owner_ = is_current_user_owner;
    838   }
    839   UpdateLoginState();
    840 }
    841 
    842 bool UserManagerImpl::IsCurrentUserNew() const {
    843   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    844   return is_current_user_new_;
    845 }
    846 
    847 bool UserManagerImpl::IsCurrentUserNonCryptohomeDataEphemeral() const {
    848   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    849   return IsUserLoggedIn() &&
    850          IsUserNonCryptohomeDataEphemeral(GetLoggedInUser()->email());
    851 }
    852 
    853 bool UserManagerImpl::CanCurrentUserLock() const {
    854   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    855   return IsUserLoggedIn() && active_user_->can_lock();
    856 }
    857 
    858 bool UserManagerImpl::IsUserLoggedIn() const {
    859   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    860   return active_user_;
    861 }
    862 
    863 bool UserManagerImpl::IsLoggedInAsRegularUser() const {
    864   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    865   return IsUserLoggedIn() &&
    866          active_user_->GetType() == User::USER_TYPE_REGULAR;
    867 }
    868 
    869 bool UserManagerImpl::IsLoggedInAsDemoUser() const {
    870   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    871   return IsUserLoggedIn() &&
    872          active_user_->GetType() == User::USER_TYPE_RETAIL_MODE;
    873 }
    874 
    875 bool UserManagerImpl::IsLoggedInAsPublicAccount() const {
    876   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    877   return IsUserLoggedIn() &&
    878       active_user_->GetType() == User::USER_TYPE_PUBLIC_ACCOUNT;
    879 }
    880 
    881 bool UserManagerImpl::IsLoggedInAsGuest() const {
    882   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    883   return IsUserLoggedIn() &&
    884          active_user_->GetType() == User::USER_TYPE_GUEST;
    885 }
    886 
    887 bool UserManagerImpl::IsLoggedInAsLocallyManagedUser() const {
    888   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    889   return IsUserLoggedIn() &&
    890       active_user_->GetType() == User::USER_TYPE_LOCALLY_MANAGED;
    891 }
    892 
    893 bool UserManagerImpl::IsLoggedInAsKioskApp() const {
    894   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    895   return IsUserLoggedIn() &&
    896       active_user_->GetType() == User::USER_TYPE_KIOSK_APP;
    897 }
    898 
    899 bool UserManagerImpl::IsLoggedInAsStub() const {
    900   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    901   return IsUserLoggedIn() && active_user_->email() == kStubUser;
    902 }
    903 
    904 bool UserManagerImpl::IsSessionStarted() const {
    905   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    906   return session_started_;
    907 }
    908 
    909 bool UserManagerImpl::UserSessionsRestored() const {
    910   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    911   return user_sessions_restored_;
    912 }
    913 
    914 UserManager::MergeSessionState UserManagerImpl::GetMergeSessionState() const {
    915   return merge_session_state_;
    916 }
    917 
    918 void UserManagerImpl::SetMergeSessionState(
    919     UserManager::MergeSessionState state) {
    920   if (merge_session_state_ == state)
    921     return;
    922 
    923   merge_session_state_ = state;
    924   NotifyMergeSessionStateChanged();
    925 }
    926 
    927 bool UserManagerImpl::HasBrowserRestarted() const {
    928   CommandLine* command_line = CommandLine::ForCurrentProcess();
    929   return base::chromeos::IsRunningOnChromeOS() &&
    930          command_line->HasSwitch(switches::kLoginUser) &&
    931          !command_line->HasSwitch(switches::kLoginPassword);
    932 }
    933 
    934 bool UserManagerImpl::IsUserNonCryptohomeDataEphemeral(
    935     const std::string& email) const {
    936   // Data belonging to the guest, retail mode and stub users is always
    937   // ephemeral.
    938   if (email == UserManager::kGuestUserName ||
    939       email == UserManager::kRetailModeUserName ||
    940       email == kStubUser) {
    941     return true;
    942   }
    943 
    944   // Data belonging to the owner, anyone found on the user list and obsolete
    945   // public accounts whose data has not been removed yet is not ephemeral.
    946   if (email == owner_email_  || FindUserInList(email) ||
    947       email == g_browser_process->local_state()->
    948           GetString(kPublicAccountPendingDataRemoval)) {
    949     return false;
    950   }
    951 
    952   // Data belonging to the currently logged-in user is ephemeral when:
    953   // a) The user logged into a regular account while the ephemeral users policy
    954   //    was enabled.
    955   //    - or -
    956   // b) The user logged into any other account type.
    957   if (IsUserLoggedIn() && (email == GetLoggedInUser()->email()) &&
    958       (is_current_user_ephemeral_regular_user_ || !IsLoggedInAsRegularUser())) {
    959     return true;
    960   }
    961 
    962   // Data belonging to any other user is ephemeral when:
    963   // a) Going through the regular login flow and the ephemeral users policy is
    964   //    enabled.
    965   //    - or -
    966   // b) The browser is restarting after a crash.
    967   return AreEphemeralUsersEnabled() || HasBrowserRestarted();
    968 }
    969 
    970 void UserManagerImpl::AddObserver(UserManager::Observer* obs) {
    971   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    972   observer_list_.AddObserver(obs);
    973 }
    974 
    975 void UserManagerImpl::RemoveObserver(UserManager::Observer* obs) {
    976   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    977   observer_list_.RemoveObserver(obs);
    978 }
    979 
    980 void UserManagerImpl::AddSessionStateObserver(
    981     UserManager::UserSessionStateObserver* obs) {
    982   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    983   session_state_observer_list_.AddObserver(obs);
    984 }
    985 
    986 void UserManagerImpl::RemoveSessionStateObserver(
    987     UserManager::UserSessionStateObserver* obs) {
    988   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    989   session_state_observer_list_.RemoveObserver(obs);
    990 }
    991 
    992 void UserManagerImpl::NotifyLocalStateChanged() {
    993   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    994   FOR_EACH_OBSERVER(UserManager::Observer, observer_list_,
    995                     LocalStateChanged(this));
    996 }
    997 
    998 void UserManagerImpl::OnProfilePrepared(Profile* profile) {
    999   LoginUtils::Get()->DoBrowserLaunch(profile,
   1000                                      NULL);     // host_, not needed here
   1001 
   1002   if (!CommandLine::ForCurrentProcess()->HasSwitch(::switches::kTestName)) {
   1003     // Did not log in (we crashed or are debugging), need to restore Sync.
   1004     // TODO(nkostylev): Make sure that OAuth state is restored correctly for all
   1005     // users once it is fully multi-profile aware. http://crbug.com/238987
   1006     // For now if we have other user pending sessions they'll override OAuth
   1007     // session restore for previous users.
   1008     LoginUtils::Get()->RestoreAuthenticationSession(profile);
   1009   }
   1010 
   1011   // Restore other user sessions if any.
   1012   RestorePendingUserSessions();
   1013 }
   1014 
   1015 void UserManagerImpl::EnsureUsersLoaded() {
   1016   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
   1017   if (!g_browser_process || !g_browser_process->local_state())
   1018     return;
   1019 
   1020   if (users_loaded_)
   1021     return;
   1022   users_loaded_ = true;
   1023 
   1024   // Clean up user list first.
   1025   if (HasFailedLocallyManagedUserCreationTransaction())
   1026     RollbackLocallyManagedUserCreationTransaction();
   1027 
   1028   PrefService* local_state = g_browser_process->local_state();
   1029   const ListValue* prefs_regular_users = local_state->GetList(kRegularUsers);
   1030   const ListValue* prefs_public_accounts =
   1031       local_state->GetList(kPublicAccounts);
   1032   const DictionaryValue* prefs_display_names =
   1033       local_state->GetDictionary(kUserDisplayName);
   1034   const DictionaryValue* prefs_display_emails =
   1035       local_state->GetDictionary(kUserDisplayEmail);
   1036 
   1037   // Load regular users and locally managed users.
   1038   std::vector<std::string> regular_users;
   1039   std::set<std::string> regular_users_set;
   1040   ParseUserList(*prefs_regular_users, std::set<std::string>(),
   1041                 &regular_users, &regular_users_set);
   1042   for (std::vector<std::string>::const_iterator it = regular_users.begin();
   1043        it != regular_users.end(); ++it) {
   1044     User* user = NULL;
   1045     const std::string domain = gaia::ExtractDomainName(*it);
   1046     if (domain == UserManager::kLocallyManagedUserDomain) {
   1047       user = User::CreateLocallyManagedUser(*it);
   1048     } else {
   1049       user = User::CreateRegularUser(*it);
   1050       user->set_oauth_token_status(LoadUserOAuthStatus(*it));
   1051     }
   1052     users_.push_back(user);
   1053 
   1054     string16 display_name;
   1055     if (prefs_display_names->GetStringWithoutPathExpansion(*it,
   1056                                                            &display_name)) {
   1057       user->set_display_name(display_name);
   1058     }
   1059 
   1060     std::string display_email;
   1061     if (prefs_display_emails->GetStringWithoutPathExpansion(*it,
   1062                                                             &display_email)) {
   1063       user->set_display_email(display_email);
   1064     }
   1065   }
   1066 
   1067   // Load public accounts.
   1068   std::vector<std::string> public_accounts;
   1069   std::set<std::string> public_accounts_set;
   1070   ParseUserList(*prefs_public_accounts, regular_users_set,
   1071                 &public_accounts, &public_accounts_set);
   1072   for (std::vector<std::string>::const_iterator it = public_accounts.begin();
   1073        it != public_accounts.end(); ++it) {
   1074     users_.push_back(User::CreatePublicAccountUser(*it));
   1075     UpdatePublicAccountDisplayName(*it);
   1076   }
   1077 
   1078   user_image_manager_->LoadUserImages(users_);
   1079 }
   1080 
   1081 void UserManagerImpl::RetrieveTrustedDevicePolicies() {
   1082   ephemeral_users_enabled_ = false;
   1083   locally_managed_users_enabled_by_policy_ = false;
   1084   owner_email_ = "";
   1085 
   1086   // Schedule a callback if device policy has not yet been verified.
   1087   if (CrosSettingsProvider::TRUSTED != cros_settings_->PrepareTrustedValues(
   1088       base::Bind(&UserManagerImpl::RetrieveTrustedDevicePolicies,
   1089                  base::Unretained(this)))) {
   1090     return;
   1091   }
   1092 
   1093   cros_settings_->GetBoolean(kAccountsPrefEphemeralUsersEnabled,
   1094                              &ephemeral_users_enabled_);
   1095   cros_settings_->GetBoolean(kAccountsPrefSupervisedUsersEnabled,
   1096                              &locally_managed_users_enabled_by_policy_);
   1097   cros_settings_->GetString(kDeviceOwner, &owner_email_);
   1098 
   1099   EnsureUsersLoaded();
   1100 
   1101   bool changed = UpdateAndCleanUpPublicAccounts(
   1102       policy::GetDeviceLocalAccounts(cros_settings_));
   1103 
   1104   // If ephemeral users are enabled and we are on the login screen, take this
   1105   // opportunity to clean up by removing all regular users except the owner.
   1106   if (ephemeral_users_enabled_ && !IsUserLoggedIn()) {
   1107     ListPrefUpdate prefs_users_update(g_browser_process->local_state(),
   1108                                       kRegularUsers);
   1109     prefs_users_update->Clear();
   1110     for (UserList::iterator it = users_.begin(); it != users_.end(); ) {
   1111       const std::string user_email = (*it)->email();
   1112       if ((*it)->GetType() == User::USER_TYPE_REGULAR &&
   1113           user_email != owner_email_) {
   1114         RemoveNonCryptohomeData(user_email);
   1115         delete *it;
   1116         it = users_.erase(it);
   1117         changed = true;
   1118       } else {
   1119         if ((*it)->GetType() != User::USER_TYPE_PUBLIC_ACCOUNT)
   1120           prefs_users_update->Append(new base::StringValue(user_email));
   1121         ++it;
   1122       }
   1123     }
   1124   }
   1125 
   1126   if (changed)
   1127     NotifyUserListChanged();
   1128 }
   1129 
   1130 bool UserManagerImpl::AreEphemeralUsersEnabled() const {
   1131   return ephemeral_users_enabled_ &&
   1132       (g_browser_process->browser_policy_connector()->IsEnterpriseManaged() ||
   1133       !owner_email_.empty());
   1134 }
   1135 
   1136 UserList& UserManagerImpl::GetUsersAndModify() {
   1137   EnsureUsersLoaded();
   1138   return users_;
   1139 }
   1140 
   1141 User* UserManagerImpl::FindUserAndModify(const std::string& email) {
   1142   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
   1143   if (active_user_ && active_user_->email() == email)
   1144     return active_user_;
   1145   return FindUserInListAndModify(email);
   1146 }
   1147 
   1148 const User* UserManagerImpl::FindUserInList(const std::string& email) const {
   1149   const UserList& users = GetUsers();
   1150   for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) {
   1151     if ((*it)->email() == email)
   1152       return *it;
   1153   }
   1154   return NULL;
   1155 }
   1156 
   1157 User* UserManagerImpl::FindUserInListAndModify(const std::string& email) {
   1158   UserList& users = GetUsersAndModify();
   1159   for (UserList::iterator it = users.begin(); it != users.end(); ++it) {
   1160     if ((*it)->email() == email)
   1161       return *it;
   1162   }
   1163   return NULL;
   1164 }
   1165 
   1166 void UserManagerImpl::GuestUserLoggedIn() {
   1167   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
   1168   active_user_ = User::CreateGuestUser();
   1169   // TODO(nkostylev): Add support for passing guest session cryptohome
   1170   // mount point. Legacy (--login-profile) value will be used for now.
   1171   // http://crosbug.com/230859
   1172   active_user_->SetStubImage(User::kInvalidImageIndex, false);
   1173   // Initializes wallpaper after active_user_ is set.
   1174   WallpaperManager::Get()->SetInitialUserWallpaper(UserManager::kGuestUserName,
   1175                                                    false);
   1176 }
   1177 
   1178 void UserManagerImpl::RegularUserLoggedIn(const std::string& email,
   1179                                           bool browser_restart) {
   1180   // Remove the user from the user list.
   1181   active_user_ = RemoveRegularOrLocallyManagedUserFromList(email);
   1182 
   1183   // If the user was not found on the user list, create a new user.
   1184   is_current_user_new_ = !active_user_;
   1185   if (!active_user_) {
   1186     active_user_ = User::CreateRegularUser(email);
   1187     active_user_->set_oauth_token_status(LoadUserOAuthStatus(email));
   1188     SaveUserDisplayName(active_user_->email(),
   1189                         UTF8ToUTF16(active_user_->GetAccountName(true)));
   1190     WallpaperManager::Get()->SetInitialUserWallpaper(email, true);
   1191   }
   1192 
   1193   // Add the user to the front of the user list.
   1194   ListPrefUpdate prefs_users_update(g_browser_process->local_state(),
   1195                                     kRegularUsers);
   1196   prefs_users_update->Insert(0, new base::StringValue(email));
   1197   users_.insert(users_.begin(), active_user_);
   1198 
   1199   user_image_manager_->UserLoggedIn(email, is_current_user_new_, false);
   1200 
   1201   if (!browser_restart) {
   1202     // For GAIA login flow, logged in user wallpaper may not be loaded.
   1203     WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded();
   1204   }
   1205 
   1206   default_pinned_apps_field_trial::SetupForUser(email, is_current_user_new_);
   1207 
   1208   // Make sure that new data is persisted to Local State.
   1209   g_browser_process->local_state()->CommitPendingWrite();
   1210 }
   1211 
   1212 void UserManagerImpl::RegularUserLoggedInAsEphemeral(const std::string& email) {
   1213   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
   1214   is_current_user_new_ = true;
   1215   is_current_user_ephemeral_regular_user_ = true;
   1216   active_user_ = User::CreateRegularUser(email);
   1217   user_image_manager_->UserLoggedIn(email, is_current_user_new_, false);
   1218   WallpaperManager::Get()->SetInitialUserWallpaper(email, false);
   1219 }
   1220 
   1221 void UserManagerImpl::LocallyManagedUserLoggedIn(
   1222     const std::string& username) {
   1223   // TODO(nkostylev): Refactor, share code with RegularUserLoggedIn().
   1224 
   1225   // Remove the user from the user list.
   1226   active_user_ = RemoveRegularOrLocallyManagedUserFromList(username);
   1227   // If the user was not found on the user list, create a new user.
   1228   if (!active_user_) {
   1229     is_current_user_new_ = true;
   1230     active_user_ = User::CreateLocallyManagedUser(username);
   1231     // Leaving OAuth token status at the default state = unknown.
   1232     WallpaperManager::Get()->SetInitialUserWallpaper(username, true);
   1233   } else {
   1234     ListPrefUpdate prefs_new_users_update(g_browser_process->local_state(),
   1235                                           kLocallyManagedUsersFirstRun);
   1236     if (prefs_new_users_update->Remove(base::StringValue(username), NULL)) {
   1237       is_current_user_new_ = true;
   1238       WallpaperManager::Get()->SetInitialUserWallpaper(username, true);
   1239     } else {
   1240       is_current_user_new_ = false;
   1241     }
   1242   }
   1243 
   1244   // Add the user to the front of the user list.
   1245   ListPrefUpdate prefs_users_update(g_browser_process->local_state(),
   1246                                     kRegularUsers);
   1247   prefs_users_update->Insert(0, new base::StringValue(username));
   1248   users_.insert(users_.begin(), active_user_);
   1249 
   1250   // Now that user is in the list, save display name.
   1251   if (is_current_user_new_) {
   1252     SaveUserDisplayName(active_user_->email(),
   1253                         active_user_->GetDisplayName());
   1254   }
   1255 
   1256   user_image_manager_->UserLoggedIn(username, is_current_user_new_, true);
   1257   WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded();
   1258 
   1259   // Make sure that new data is persisted to Local State.
   1260   g_browser_process->local_state()->CommitPendingWrite();
   1261 }
   1262 
   1263 void UserManagerImpl::PublicAccountUserLoggedIn(User* user) {
   1264   is_current_user_new_ = true;
   1265   active_user_ = user;
   1266   // The UserImageManager chooses a random avatar picture when a user logs in
   1267   // for the first time. Tell the UserImageManager that this user is not new to
   1268   // prevent the avatar from getting changed.
   1269   user_image_manager_->UserLoggedIn(user->email(), false, true);
   1270   WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded();
   1271 }
   1272 
   1273 void UserManagerImpl::KioskAppLoggedIn(const std::string& username) {
   1274   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
   1275   DCHECK(policy::IsKioskAppUser(username));
   1276 
   1277   active_user_ = User::CreateKioskAppUser(username);
   1278   active_user_->SetStubImage(User::kInvalidImageIndex, false);
   1279   WallpaperManager::Get()->SetInitialUserWallpaper(username, false);
   1280 
   1281   // TODO(bartfab): Add KioskAppUsers to the users_ list and keep metadata like
   1282   // the kiosk_app_id in these objects, removing the need to re-parse the
   1283   // device-local account list here to extract the kiosk_app_id.
   1284   const std::vector<policy::DeviceLocalAccount> device_local_accounts =
   1285       policy::GetDeviceLocalAccounts(cros_settings_);
   1286   const policy::DeviceLocalAccount* account = NULL;
   1287   for (std::vector<policy::DeviceLocalAccount>::const_iterator
   1288            it = device_local_accounts.begin();
   1289        it != device_local_accounts.end(); ++it) {
   1290     if (it->user_id == username) {
   1291       account = &*it;
   1292       break;
   1293     }
   1294   }
   1295   std::string kiosk_app_id;
   1296   if (account) {
   1297     kiosk_app_id = account->kiosk_app_id;
   1298   } else {
   1299     LOG(ERROR) << "Logged into nonexistent kiosk-app account: " << username;
   1300     NOTREACHED();
   1301   }
   1302 
   1303   CommandLine* command_line = CommandLine::ForCurrentProcess();
   1304   command_line->AppendSwitch(::switches::kForceAppMode);
   1305   command_line->AppendSwitchASCII(::switches::kAppId, kiosk_app_id);
   1306 
   1307   // Disable window animation since kiosk app runs in a single full screen
   1308   // window and window animation causes start-up janks.
   1309   command_line->AppendSwitch(
   1310       views::corewm::switches::kWindowAnimationsDisabled);
   1311 }
   1312 
   1313 void UserManagerImpl::RetailModeUserLoggedIn() {
   1314   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
   1315   is_current_user_new_ = true;
   1316   active_user_ = User::CreateRetailModeUser();
   1317   user_image_manager_->UserLoggedIn(UserManager::kRetailModeUserName,
   1318                                     is_current_user_new_,
   1319                                     true);
   1320   WallpaperManager::Get()->SetInitialUserWallpaper(
   1321       UserManager::kRetailModeUserName, false);
   1322 }
   1323 
   1324 void UserManagerImpl::NotifyOnLogin() {
   1325   CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
   1326   NotifyActiveUserHashChanged(active_user_->username_hash());
   1327   NotifyActiveUserChanged(active_user_);
   1328 
   1329   UpdateLoginState();
   1330   // TODO(nkostylev): Deprecate this notification in favor of
   1331   // ActiveUserChanged() observer call.
   1332   content::NotificationService::current()->Notify(
   1333       chrome::NOTIFICATION_LOGIN_USER_CHANGED,
   1334       content::Source<UserManager>(this),
   1335       content::Details<const User>(active_user_));
   1336 
   1337   // Indicate to DeviceSettingsService that the owner key may have become
   1338   // available.
   1339   DeviceSettingsService::Get()->SetUsername(active_user_->email());
   1340 }
   1341 
   1342 void UserManagerImpl::UpdateOwnership(
   1343     DeviceSettingsService::OwnershipStatus status,
   1344     bool is_owner) {
   1345   VLOG(1) << "Current user " << (is_owner ? "is owner" : "is not owner");
   1346 
   1347   SetCurrentUserIsOwner(is_owner);
   1348 }
   1349 
   1350 void UserManagerImpl::CheckOwnership() {
   1351   DeviceSettingsService::Get()->GetOwnershipStatusAsync(
   1352       base::Bind(&UserManagerImpl::UpdateOwnership,
   1353                  base::Unretained(this)));
   1354 }
   1355 
   1356 void UserManagerImpl::RemoveNonCryptohomeData(const std::string& email) {
   1357   WallpaperManager::Get()->RemoveUserWallpaperInfo(email);
   1358   user_image_manager_->DeleteUserImage(email);
   1359 
   1360   PrefService* prefs = g_browser_process->local_state();
   1361   DictionaryPrefUpdate prefs_oauth_update(prefs, kUserOAuthTokenStatus);
   1362   int oauth_status;
   1363   prefs_oauth_update->GetIntegerWithoutPathExpansion(email, &oauth_status);
   1364   prefs_oauth_update->RemoveWithoutPathExpansion(email, NULL);
   1365 
   1366   DictionaryPrefUpdate prefs_display_name_update(prefs, kUserDisplayName);
   1367   prefs_display_name_update->RemoveWithoutPathExpansion(email, NULL);
   1368 
   1369   DictionaryPrefUpdate prefs_display_email_update(prefs, kUserDisplayEmail);
   1370   prefs_display_email_update->RemoveWithoutPathExpansion(email, NULL);
   1371 
   1372   ListPrefUpdate prefs_new_users_update(prefs, kLocallyManagedUsersFirstRun);
   1373   prefs_new_users_update->Remove(base::StringValue(email), NULL);
   1374 
   1375   DictionaryPrefUpdate managers_update(prefs, kManagedUserManagers);
   1376   managers_update->RemoveWithoutPathExpansion(email, NULL);
   1377 
   1378   DictionaryPrefUpdate manager_names_update(prefs,
   1379                                             kManagedUserManagerNames);
   1380   manager_names_update->RemoveWithoutPathExpansion(email, NULL);
   1381 
   1382   DictionaryPrefUpdate manager_emails_update(prefs,
   1383                                              kManagedUserManagerDisplayEmails);
   1384   manager_emails_update->RemoveWithoutPathExpansion(email, NULL);
   1385 }
   1386 
   1387 User* UserManagerImpl::RemoveRegularOrLocallyManagedUserFromList(
   1388     const std::string& username) {
   1389   ListPrefUpdate prefs_users_update(g_browser_process->local_state(),
   1390                                     kRegularUsers);
   1391   prefs_users_update->Clear();
   1392   User* user = NULL;
   1393   for (UserList::iterator it = users_.begin(); it != users_.end(); ) {
   1394     const std::string user_email = (*it)->email();
   1395     if (user_email == username) {
   1396       user = *it;
   1397       it = users_.erase(it);
   1398     } else {
   1399       if ((*it)->GetType() == User::USER_TYPE_REGULAR ||
   1400           (*it)->GetType() == User::USER_TYPE_LOCALLY_MANAGED) {
   1401         prefs_users_update->Append(new base::StringValue(user_email));
   1402       }
   1403       ++it;
   1404     }
   1405   }
   1406   return user;
   1407 }
   1408 
   1409 void UserManagerImpl::CleanUpPublicAccountNonCryptohomeDataPendingRemoval() {
   1410   PrefService* local_state = g_browser_process->local_state();
   1411   const std::string public_account_pending_data_removal =
   1412       local_state->GetString(kPublicAccountPendingDataRemoval);
   1413   if (public_account_pending_data_removal.empty() ||
   1414       (IsUserLoggedIn() &&
   1415        public_account_pending_data_removal == GetActiveUser()->email())) {
   1416     return;
   1417   }
   1418 
   1419   RemoveNonCryptohomeData(public_account_pending_data_removal);
   1420   local_state->ClearPref(kPublicAccountPendingDataRemoval);
   1421 }
   1422 
   1423 void UserManagerImpl::CleanUpPublicAccountNonCryptohomeData(
   1424     const std::vector<std::string>& old_public_accounts) {
   1425   std::set<std::string> users;
   1426   for (UserList::const_iterator it = users_.begin(); it != users_.end(); ++it)
   1427     users.insert((*it)->email());
   1428 
   1429   // If the user is logged into a public account that has been removed from the
   1430   // user list, mark the account's data as pending removal after logout.
   1431   if (IsLoggedInAsPublicAccount()) {
   1432     const std::string active_user_id = GetActiveUser()->email();
   1433     if (users.find(active_user_id) == users.end()) {
   1434       g_browser_process->local_state()->SetString(
   1435           kPublicAccountPendingDataRemoval, active_user_id);
   1436       users.insert(active_user_id);
   1437     }
   1438   }
   1439 
   1440   // Remove the data belonging to any other public accounts that are no longer
   1441   // found on the user list.
   1442   for (std::vector<std::string>::const_iterator
   1443            it = old_public_accounts.begin();
   1444        it != old_public_accounts.end(); ++it) {
   1445     if (users.find(*it) == users.end())
   1446       RemoveNonCryptohomeData(*it);
   1447   }
   1448 }
   1449 
   1450 bool UserManagerImpl::UpdateAndCleanUpPublicAccounts(
   1451     const std::vector<policy::DeviceLocalAccount>& device_local_accounts) {
   1452   // Try to remove any public account data marked as pending removal.
   1453   CleanUpPublicAccountNonCryptohomeDataPendingRemoval();
   1454 
   1455   // Get the current list of public accounts.
   1456   std::vector<std::string> old_public_accounts;
   1457   for (UserList::const_iterator it = users_.begin(); it != users_.end(); ++it) {
   1458     if ((*it)->GetType() == User::USER_TYPE_PUBLIC_ACCOUNT)
   1459       old_public_accounts.push_back((*it)->email());
   1460   }
   1461 
   1462   // Get the new list of public accounts from policy.
   1463   std::vector<std::string> new_public_accounts;
   1464   for (std::vector<policy::DeviceLocalAccount>::const_iterator it =
   1465            device_local_accounts.begin();
   1466        it != device_local_accounts.end(); ++it) {
   1467     // TODO(mnissler, nkostylev, bartfab): Process Kiosk Apps within the
   1468     // standard login framework: http://crbug.com/234694
   1469     if (it->type == policy::DeviceLocalAccount::TYPE_PUBLIC_SESSION)
   1470       new_public_accounts.push_back(it->user_id);
   1471   }
   1472 
   1473   // If the list of public accounts has not changed, return.
   1474   if (new_public_accounts.size() == old_public_accounts.size()) {
   1475     bool changed = false;
   1476     for (size_t i = 0; i < new_public_accounts.size(); ++i) {
   1477       if (new_public_accounts[i] != old_public_accounts[i]) {
   1478         changed = true;
   1479         break;
   1480       }
   1481     }
   1482     if (!changed)
   1483       return false;
   1484   }
   1485 
   1486   // Persist the new list of public accounts in a pref.
   1487   ListPrefUpdate prefs_public_accounts_update(g_browser_process->local_state(),
   1488                                               kPublicAccounts);
   1489   prefs_public_accounts_update->Clear();
   1490   for (std::vector<std::string>::const_iterator
   1491            it = new_public_accounts.begin();
   1492        it != new_public_accounts.end(); ++it) {
   1493     prefs_public_accounts_update->AppendString(*it);
   1494   }
   1495 
   1496   // Remove the old public accounts from the user list.
   1497   for (UserList::iterator it = users_.begin(); it != users_.end(); ) {
   1498     if ((*it)->GetType() == User::USER_TYPE_PUBLIC_ACCOUNT) {
   1499       if (*it != GetLoggedInUser())
   1500         delete *it;
   1501       it = users_.erase(it);
   1502     } else {
   1503       ++it;
   1504     }
   1505   }
   1506 
   1507   // Add the new public accounts to the front of the user list.
   1508   for (std::vector<std::string>::const_reverse_iterator
   1509            it = new_public_accounts.rbegin();
   1510        it != new_public_accounts.rend(); ++it) {
   1511     if (IsLoggedInAsPublicAccount() && *it == GetActiveUser()->email())
   1512       users_.insert(users_.begin(), GetLoggedInUser());
   1513     else
   1514       users_.insert(users_.begin(), User::CreatePublicAccountUser(*it));
   1515     UpdatePublicAccountDisplayName(*it);
   1516   }
   1517 
   1518   user_image_manager_->LoadUserImages(
   1519       UserList(users_.begin(), users_.begin() + new_public_accounts.size()));
   1520 
   1521   // Remove data belonging to public accounts that are no longer found on the
   1522   // user list.
   1523   CleanUpPublicAccountNonCryptohomeData(old_public_accounts);
   1524 
   1525   return true;
   1526 }
   1527 
   1528 void UserManagerImpl::UpdatePublicAccountDisplayName(
   1529     const std::string& username) {
   1530   std::string display_name;
   1531 
   1532   if (device_local_account_policy_service_) {
   1533     policy::DeviceLocalAccountPolicyBroker* broker =
   1534         device_local_account_policy_service_->GetBrokerForUser(username);
   1535     if (broker)
   1536       display_name = broker->GetDisplayName();
   1537   }
   1538 
   1539   // Set or clear the display name.
   1540   SaveUserDisplayName(username, UTF8ToUTF16(display_name));
   1541 }
   1542 
   1543 void UserManagerImpl::StartLocallyManagedUserCreationTransaction(
   1544       const string16& display_name) {
   1545   g_browser_process->local_state()->
   1546       SetString(kLocallyManagedUserCreationTransactionDisplayName,
   1547            UTF16ToASCII(display_name));
   1548   g_browser_process->local_state()->CommitPendingWrite();
   1549 }
   1550 
   1551 void UserManagerImpl::SetLocallyManagedUserCreationTransactionUserId(
   1552       const std::string& email) {
   1553   g_browser_process->local_state()->
   1554       SetString(kLocallyManagedUserCreationTransactionUserId,
   1555                 email);
   1556   g_browser_process->local_state()->CommitPendingWrite();
   1557 }
   1558 
   1559 void UserManagerImpl::CommitLocallyManagedUserCreationTransaction() {
   1560   g_browser_process->local_state()->
   1561       ClearPref(kLocallyManagedUserCreationTransactionDisplayName);
   1562   g_browser_process->local_state()->
   1563       ClearPref(kLocallyManagedUserCreationTransactionUserId);
   1564   g_browser_process->local_state()->CommitPendingWrite();
   1565 }
   1566 
   1567 bool UserManagerImpl::HasFailedLocallyManagedUserCreationTransaction() {
   1568   return !(g_browser_process->local_state()->
   1569                GetString(kLocallyManagedUserCreationTransactionDisplayName).
   1570                    empty());
   1571 }
   1572 
   1573 void UserManagerImpl::RollbackLocallyManagedUserCreationTransaction() {
   1574   PrefService* prefs = g_browser_process->local_state();
   1575 
   1576   std::string display_name = prefs->
   1577       GetString(kLocallyManagedUserCreationTransactionDisplayName);
   1578   std::string user_id = prefs->
   1579       GetString(kLocallyManagedUserCreationTransactionUserId);
   1580 
   1581   LOG(WARNING) << "Cleaning up transaction for "
   1582                << display_name << "/" << user_id;
   1583 
   1584   if (user_id.empty()) {
   1585     // Not much to do - just remove transaction.
   1586     prefs->ClearPref(kLocallyManagedUserCreationTransactionDisplayName);
   1587     return;
   1588   }
   1589 
   1590   if (gaia::ExtractDomainName(user_id) != kLocallyManagedUserDomain) {
   1591     LOG(WARNING) << "Clean up transaction for  non-locally managed user found :"
   1592                  << user_id << ", will not remove data";
   1593     prefs->ClearPref(kLocallyManagedUserCreationTransactionDisplayName);
   1594     prefs->ClearPref(kLocallyManagedUserCreationTransactionUserId);
   1595     return;
   1596   }
   1597 
   1598   ListPrefUpdate prefs_users_update(prefs, kRegularUsers);
   1599   prefs_users_update->Remove(base::StringValue(user_id), NULL);
   1600 
   1601   RemoveNonCryptohomeData(user_id);
   1602 
   1603   cryptohome::AsyncMethodCaller::GetInstance()->AsyncRemove(
   1604       user_id, base::Bind(&OnRemoveUserComplete, user_id));
   1605 
   1606   prefs->ClearPref(kLocallyManagedUserCreationTransactionDisplayName);
   1607   prefs->ClearPref(kLocallyManagedUserCreationTransactionUserId);
   1608   prefs->CommitPendingWrite();
   1609 }
   1610 
   1611 UserFlow* UserManagerImpl::GetCurrentUserFlow() const {
   1612   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
   1613   if (!IsUserLoggedIn())
   1614     return GetDefaultUserFlow();
   1615   return GetUserFlow(GetLoggedInUser()->email());
   1616 }
   1617 
   1618 UserFlow* UserManagerImpl::GetUserFlow(const std::string& email) const {
   1619   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
   1620   FlowMap::const_iterator it = specific_flows_.find(email);
   1621   if (it != specific_flows_.end())
   1622     return it->second;
   1623   return GetDefaultUserFlow();
   1624 }
   1625 
   1626 void UserManagerImpl::SetUserFlow(const std::string& email, UserFlow* flow) {
   1627   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
   1628   ResetUserFlow(email);
   1629   specific_flows_[email] = flow;
   1630 }
   1631 
   1632 void UserManagerImpl::ResetUserFlow(const std::string& email) {
   1633   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
   1634   FlowMap::iterator it = specific_flows_.find(email);
   1635   if (it != specific_flows_.end()) {
   1636     delete it->second;
   1637     specific_flows_.erase(it);
   1638   }
   1639 }
   1640 
   1641 bool UserManagerImpl::GetAppModeChromeClientOAuthInfo(
   1642     std::string* chrome_client_id, std::string* chrome_client_secret) {
   1643   if (!chrome::IsRunningInForcedAppMode() ||
   1644       chrome_client_id_.empty() ||
   1645       chrome_client_secret_.empty()) {
   1646     return false;
   1647   }
   1648 
   1649   *chrome_client_id = chrome_client_id_;
   1650   *chrome_client_secret = chrome_client_secret_;
   1651   return true;
   1652 }
   1653 
   1654 void UserManagerImpl::SetAppModeChromeClientOAuthInfo(
   1655     const std::string& chrome_client_id,
   1656     const std::string& chrome_client_secret) {
   1657   if (!chrome::IsRunningInForcedAppMode())
   1658     return;
   1659 
   1660   chrome_client_id_ = chrome_client_id;
   1661   chrome_client_secret_ = chrome_client_secret;
   1662 }
   1663 
   1664 bool UserManagerImpl::AreLocallyManagedUsersAllowed() const {
   1665   return ManagedUserService::AreManagedUsersEnabled() &&
   1666         (locally_managed_users_enabled_by_policy_ ||
   1667          !g_browser_process->browser_policy_connector()->IsEnterpriseManaged());
   1668 }
   1669 
   1670 UserFlow* UserManagerImpl::GetDefaultUserFlow() const {
   1671   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
   1672   if (!default_flow_.get())
   1673     default_flow_.reset(new DefaultUserFlow());
   1674   return default_flow_.get();
   1675 }
   1676 
   1677 void UserManagerImpl::NotifyUserListChanged() {
   1678   content::NotificationService::current()->Notify(
   1679       chrome::NOTIFICATION_USER_LIST_CHANGED,
   1680       content::Source<UserManager>(this),
   1681       content::NotificationService::NoDetails());
   1682 }
   1683 
   1684 void UserManagerImpl::NotifyMergeSessionStateChanged() {
   1685   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
   1686   FOR_EACH_OBSERVER(UserManager::Observer, observer_list_,
   1687                     MergeSessionStateChanged(merge_session_state_));
   1688 }
   1689 
   1690 void UserManagerImpl::NotifyActiveUserChanged(const User* active_user) {
   1691   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
   1692   FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
   1693                     session_state_observer_list_,
   1694                     ActiveUserChanged(active_user));
   1695 }
   1696 
   1697 void UserManagerImpl::NotifyActiveUserHashChanged(const std::string& hash) {
   1698   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
   1699   FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
   1700                     session_state_observer_list_,
   1701                     ActiveUserHashChanged(hash));
   1702 }
   1703 
   1704 void UserManagerImpl::NotifyPendingUserSessionsRestoreFinished() {
   1705   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
   1706   user_sessions_restored_ = true;
   1707   FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
   1708                     session_state_observer_list_,
   1709                     PendingUserSessionsRestoreFinished());
   1710 }
   1711 
   1712 void UserManagerImpl::UpdateLoginState() {
   1713   if (!LoginState::IsInitialized())
   1714     return;  // LoginState may not be intialized in tests.
   1715   LoginState::LoggedInState logged_in_state;
   1716   logged_in_state = active_user_ ? LoginState::LOGGED_IN_ACTIVE
   1717       : LoginState::LOGGED_IN_NONE;
   1718 
   1719   LoginState::LoggedInUserType login_user_type;
   1720   if (logged_in_state == LoginState::LOGGED_IN_NONE)
   1721     login_user_type = LoginState::LOGGED_IN_USER_NONE;
   1722   else if (is_current_user_owner_)
   1723     login_user_type = LoginState::LOGGED_IN_USER_OWNER;
   1724   else if (active_user_->GetType() == User::USER_TYPE_GUEST)
   1725     login_user_type = LoginState::LOGGED_IN_USER_GUEST;
   1726   else if (active_user_->GetType() == User::USER_TYPE_RETAIL_MODE)
   1727     login_user_type = LoginState::LOGGED_IN_USER_RETAIL_MODE;
   1728   else if (active_user_->GetType() == User::USER_TYPE_PUBLIC_ACCOUNT)
   1729     login_user_type = LoginState::LOGGED_IN_USER_PUBLIC_ACCOUNT;
   1730   else if (active_user_->GetType() == User::USER_TYPE_LOCALLY_MANAGED)
   1731     login_user_type = LoginState::LOGGED_IN_USER_LOCALLY_MANAGED;
   1732   else if (active_user_->GetType() == User::USER_TYPE_KIOSK_APP)
   1733     login_user_type = LoginState::LOGGED_IN_USER_KIOSK_APP;
   1734   else
   1735     login_user_type = LoginState::LOGGED_IN_USER_REGULAR;
   1736 
   1737   LoginState::Get()->SetLoggedInState(logged_in_state, login_user_type);
   1738 }
   1739 
   1740 void UserManagerImpl::SetLRUUser(User* user) {
   1741   UserList::iterator it = std::find(lru_logged_in_users_.begin(),
   1742                                     lru_logged_in_users_.end(),
   1743                                     user);
   1744   if (it != lru_logged_in_users_.end())
   1745     lru_logged_in_users_.erase(it);
   1746   lru_logged_in_users_.insert(lru_logged_in_users_.begin(), user);
   1747 }
   1748 
   1749 void UserManagerImpl::OnRestoreActiveSessions(
   1750     const SessionManagerClient::ActiveSessionsMap& sessions,
   1751     bool success) {
   1752   if (!success) {
   1753     LOG(ERROR) << "Could not get list of active user sessions after crash.";
   1754     // If we could not get list of active user sessions it is safer to just
   1755     // sign out so that we don't get in the inconsistent state.
   1756     DBusThreadManager::Get()->GetSessionManagerClient()->StopSession();
   1757     return;
   1758   }
   1759 
   1760   // One profile has been already loaded on browser start.
   1761   DCHECK(GetLoggedInUsers().size() == 1);
   1762   DCHECK(GetActiveUser());
   1763   std::string active_user_id = GetActiveUser()->email();
   1764 
   1765   SessionManagerClient::ActiveSessionsMap::const_iterator it;
   1766   for (it = sessions.begin(); it != sessions.end(); ++it) {
   1767     if (active_user_id == it->first)
   1768       continue;
   1769     pending_user_sessions_[it->first] = it->second;
   1770   }
   1771   RestorePendingUserSessions();
   1772 }
   1773 
   1774 void UserManagerImpl::RestorePendingUserSessions() {
   1775   if (pending_user_sessions_.empty()) {
   1776     NotifyPendingUserSessionsRestoreFinished();
   1777     return;
   1778   }
   1779 
   1780   // Get next user to restore sessions and delete it from list.
   1781   SessionManagerClient::ActiveSessionsMap::const_iterator it =
   1782       pending_user_sessions_.begin();
   1783   std::string user_id = it->first;
   1784   std::string user_id_hash = it->second;
   1785   DCHECK(!user_id.empty());
   1786   DCHECK(!user_id_hash.empty());
   1787   pending_user_sessions_.erase(user_id);
   1788 
   1789   // Check that this user is not logged in yet.
   1790   UserList logged_in_users = GetLoggedInUsers();
   1791   bool user_already_logged_in = false;
   1792   for (UserList::const_iterator it = logged_in_users.begin();
   1793        it != logged_in_users.end(); ++it) {
   1794     const User* user = (*it);
   1795     if (user->email() == user_id) {
   1796       user_already_logged_in = true;
   1797       break;
   1798     }
   1799   }
   1800   DCHECK(!user_already_logged_in);
   1801 
   1802   if (!user_already_logged_in) {
   1803     // Will call OnProfilePrepared() once profile has been loaded.
   1804     LoginUtils::Get()->PrepareProfile(UserContext(user_id,
   1805                                                   std::string(),  // password
   1806                                                   std::string(),  // auth_code
   1807                                                   user_id_hash),
   1808                                       std::string(),  // display_email
   1809                                       false,          // using_oauth
   1810                                       false,          // has_cookies
   1811                                       true,           // has_active_session
   1812                                       this);
   1813   } else {
   1814     RestorePendingUserSessions();
   1815   }
   1816 }
   1817 
   1818 void UserManagerImpl::SendRegularUserLoginMetrics(const std::string& email) {
   1819   // If this isn't the first time Chrome was run after the system booted,
   1820   // assume that Chrome was restarted because a previous session ended.
   1821   if (!CommandLine::ForCurrentProcess()->HasSwitch(
   1822           switches::kFirstExecAfterBoot)) {
   1823     const std::string last_email =
   1824         g_browser_process->local_state()->GetString(kLastLoggedInRegularUser);
   1825     const base::TimeDelta time_to_login =
   1826         base::TimeTicks::Now() - manager_creation_time_;
   1827     if (!last_email.empty() && email != last_email &&
   1828         time_to_login.InSeconds() <= kLogoutToLoginDelayMaxSec) {
   1829       UMA_HISTOGRAM_CUSTOM_COUNTS("UserManager.LogoutToLoginDelay",
   1830           time_to_login.InSeconds(), 0, kLogoutToLoginDelayMaxSec, 50);
   1831     }
   1832   }
   1833 }
   1834 
   1835 }  // namespace chromeos
   1836