1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/user_manager/user_manager_base.h"
10 #include "base/bind.h"
11 #include "base/bind_helpers.h"
12 #include "base/command_line.h"
13 #include "base/compiler_specific.h"
14 #include "base/format_macros.h"
15 #include "base/location.h"
16 #include "base/logging.h"
17 #include "base/macros.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/strings/string_util.h"
23 #include "base/strings/stringprintf.h"
24 #include "base/strings/utf_string_conversions.h"
25 #include "base/task_runner.h"
26 #include "base/values.h"
27 #include "chromeos/chromeos_switches.h"
28 #include "chromeos/cryptohome/async_method_caller.h"
29 #include "chromeos/login/login_state.h"
30 #include "chromeos/login/user_names.h"
31 #include "components/session_manager/core/session_manager.h"
32 #include "components/user_manager/remove_user_delegate.h"
33 #include "components/user_manager/user_type.h"
34 #include "google_apis/gaia/gaia_auth_util.h"
35 #include "ui/base/l10n/l10n_util.h"
37 namespace user_manager {
40 // A vector pref of the the regular users known on this device, arranged in LRU
42 const char kRegularUsers[] = "LoggedInUsers";
44 // A dictionary that maps user IDs to the displayed name.
45 const char kUserDisplayName[] = "UserDisplayName";
47 // A dictionary that maps user IDs to the user's given name.
48 const char kUserGivenName[] = "UserGivenName";
50 // A dictionary that maps user IDs to the displayed (non-canonical) emails.
51 const char kUserDisplayEmail[] = "UserDisplayEmail";
53 // A dictionary that maps user IDs to OAuth token presence flag.
54 const char kUserOAuthTokenStatus[] = "OAuthTokenStatus";
56 // A dictionary that maps user IDs to a flag indicating whether online
57 // authentication against GAIA should be enforced during the next sign-in.
58 const char kUserForceOnlineSignin[] = "UserForceOnlineSignin";
60 // A string pref containing the ID of the last user who logged in if it was
61 // a regular user or an empty string if it was another type of user (guest,
62 // kiosk, public account, etc.).
63 const char kLastLoggedInRegularUser[] = "LastLoggedInRegularUser";
65 // Upper bound for a histogram metric reporting the amount of time between
66 // one regular user logging out and a different regular user logging in.
67 const int kLogoutToLoginDelayMaxSec = 1800;
69 // Callback that is called after user removal is complete.
70 void OnRemoveUserComplete(const std::string& user_email,
72 cryptohome::MountError return_code) {
73 // Log the error, but there's not much we can do.
75 LOG(ERROR) << "Removal of cryptohome for " << user_email
76 << " failed, return code: " << return_code;
83 void UserManagerBase::RegisterPrefs(PrefRegistrySimple* registry) {
84 registry->RegisterListPref(kRegularUsers);
85 registry->RegisterStringPref(kLastLoggedInRegularUser, std::string());
86 registry->RegisterDictionaryPref(kUserDisplayName);
87 registry->RegisterDictionaryPref(kUserGivenName);
88 registry->RegisterDictionaryPref(kUserDisplayEmail);
89 registry->RegisterDictionaryPref(kUserOAuthTokenStatus);
90 registry->RegisterDictionaryPref(kUserForceOnlineSignin);
93 UserManagerBase::UserManagerBase(
94 scoped_refptr<base::TaskRunner> task_runner,
95 scoped_refptr<base::TaskRunner> blocking_task_runner)
98 user_loading_stage_(STAGE_NOT_LOADED),
99 session_started_(false),
100 is_current_user_owner_(false),
101 is_current_user_new_(false),
102 is_current_user_ephemeral_regular_user_(false),
103 ephemeral_users_enabled_(false),
104 manager_creation_time_(base::TimeTicks::Now()),
105 task_runner_(task_runner),
106 blocking_task_runner_(blocking_task_runner),
107 weak_factory_(this) {
111 UserManagerBase::~UserManagerBase() {
112 // Can't use STLDeleteElements because of the private destructor of User.
113 for (UserList::iterator it = users_.begin(); it != users_.end();
114 it = users_.erase(it)) {
117 // These are pointers to the same User instances that were in users_ list.
118 logged_in_users_.clear();
119 lru_logged_in_users_.clear();
121 DeleteUser(active_user_);
124 void UserManagerBase::Shutdown() {
125 DCHECK(task_runner_->RunsTasksOnCurrentThread());
128 const UserList& UserManagerBase::GetUsers() const {
129 const_cast<UserManagerBase*>(this)->EnsureUsersLoaded();
133 const UserList& UserManagerBase::GetLoggedInUsers() const {
134 return logged_in_users_;
137 const UserList& UserManagerBase::GetLRULoggedInUsers() const {
138 return lru_logged_in_users_;
141 const std::string& UserManagerBase::GetOwnerEmail() const {
145 void UserManagerBase::UserLoggedIn(const std::string& user_id,
146 const std::string& username_hash,
147 bool browser_restart) {
148 DCHECK(task_runner_->RunsTasksOnCurrentThread());
150 User* user = FindUserInListAndModify(user_id);
151 if (active_user_ && user) {
152 user->set_is_logged_in(true);
153 user->set_username_hash(username_hash);
154 logged_in_users_.push_back(user);
155 lru_logged_in_users_.push_back(user);
157 // Reset the new user flag if the user already exists.
158 SetIsCurrentUserNew(false);
159 NotifyUserAddedToSession(user, true /* user switch pending */);
164 if (user_id == chromeos::login::kGuestUserName) {
166 } else if (user_id == chromeos::login::kRetailModeUserName) {
167 RetailModeUserLoggedIn();
168 } else if (IsKioskApp(user_id)) {
169 KioskAppLoggedIn(user_id);
170 } else if (IsDemoApp(user_id)) {
171 DemoAccountLoggedIn();
175 if (user && user->GetType() == USER_TYPE_PUBLIC_ACCOUNT) {
176 PublicAccountUserLoggedIn(user);
177 } else if ((user && user->GetType() == USER_TYPE_SUPERVISED) ||
179 gaia::ExtractDomainName(user_id) ==
180 chromeos::login::kSupervisedUserDomain)) {
181 SupervisedUserLoggedIn(user_id);
182 } else if (browser_restart && IsPublicAccountMarkedForRemoval(user_id)) {
183 PublicAccountUserLoggedIn(User::CreatePublicAccountUser(user_id));
184 } else if (user_id != GetOwnerEmail() && !user &&
185 (AreEphemeralUsersEnabled() || browser_restart)) {
186 RegularUserLoggedInAsEphemeral(user_id);
188 RegularUserLoggedIn(user_id);
192 DCHECK(active_user_);
193 active_user_->set_is_logged_in(true);
194 active_user_->set_is_active(true);
195 active_user_->set_username_hash(username_hash);
197 // Place user who just signed in to the top of the logged in users.
198 logged_in_users_.insert(logged_in_users_.begin(), active_user_);
199 SetLRUUser(active_user_);
201 if (!primary_user_) {
202 primary_user_ = active_user_;
203 if (primary_user_->GetType() == USER_TYPE_REGULAR)
204 SendRegularUserLoginMetrics(user_id);
207 UMA_HISTOGRAM_ENUMERATION(
208 "UserManager.LoginUserType", active_user_->GetType(), NUM_USER_TYPES);
210 GetLocalState()->SetString(
211 kLastLoggedInRegularUser,
212 (active_user_->GetType() == USER_TYPE_REGULAR) ? user_id : "");
215 PerformPostUserLoggedInActions(browser_restart);
218 void UserManagerBase::SwitchActiveUser(const std::string& user_id) {
219 User* user = FindUserAndModify(user_id);
221 NOTREACHED() << "Switching to a non-existing user";
224 if (user == active_user_) {
225 NOTREACHED() << "Switching to a user who is already active";
228 if (!user->is_logged_in()) {
229 NOTREACHED() << "Switching to a user that is not logged in";
232 if (user->GetType() != USER_TYPE_REGULAR) {
233 NOTREACHED() << "Switching to a non-regular user";
236 if (user->username_hash().empty()) {
237 NOTREACHED() << "Switching to a user that doesn't have username_hash set";
241 DCHECK(active_user_);
242 active_user_->set_is_active(false);
243 user->set_is_active(true);
246 // Move the user to the front.
247 SetLRUUser(active_user_);
249 NotifyActiveUserHashChanged(active_user_->username_hash());
250 NotifyActiveUserChanged(active_user_);
253 void UserManagerBase::SessionStarted() {
254 DCHECK(task_runner_->RunsTasksOnCurrentThread());
255 session_started_ = true;
258 session_manager::SessionManager::Get()->SetSessionState(
259 session_manager::SESSION_STATE_ACTIVE);
261 if (IsCurrentUserNew()) {
262 // Make sure that the new user's data is persisted to Local State.
263 GetLocalState()->CommitPendingWrite();
267 void UserManagerBase::RemoveUser(const std::string& user_id,
268 RemoveUserDelegate* delegate) {
269 DCHECK(task_runner_->RunsTasksOnCurrentThread());
271 if (!CanUserBeRemoved(FindUser(user_id)))
274 RemoveUserInternal(user_id, delegate);
277 void UserManagerBase::RemoveUserInternal(const std::string& user_email,
278 RemoveUserDelegate* delegate) {
279 RemoveNonOwnerUserInternal(user_email, delegate);
282 void UserManagerBase::RemoveNonOwnerUserInternal(const std::string& user_email,
283 RemoveUserDelegate* delegate) {
285 delegate->OnBeforeUserRemoved(user_email);
286 RemoveUserFromList(user_email);
287 cryptohome::AsyncMethodCaller::GetInstance()->AsyncRemove(
288 user_email, base::Bind(&OnRemoveUserComplete, user_email));
291 delegate->OnUserRemoved(user_email);
294 void UserManagerBase::RemoveUserFromList(const std::string& user_id) {
295 DCHECK(task_runner_->RunsTasksOnCurrentThread());
296 RemoveNonCryptohomeData(user_id);
297 if (user_loading_stage_ == STAGE_LOADED) {
298 DeleteUser(RemoveRegularOrSupervisedUserFromList(user_id));
299 } else if (user_loading_stage_ == STAGE_LOADING) {
300 DCHECK(gaia::ExtractDomainName(user_id) ==
301 chromeos::login::kSupervisedUserDomain);
302 // Special case, removing partially-constructed supervised user during user
304 ListPrefUpdate users_update(GetLocalState(), kRegularUsers);
305 users_update->Remove(base::StringValue(user_id), NULL);
307 NOTREACHED() << "Users are not loaded yet.";
311 // Make sure that new data is persisted to Local State.
312 GetLocalState()->CommitPendingWrite();
315 bool UserManagerBase::IsKnownUser(const std::string& user_id) const {
316 return FindUser(user_id) != NULL;
319 const User* UserManagerBase::FindUser(const std::string& user_id) const {
320 DCHECK(task_runner_->RunsTasksOnCurrentThread());
321 if (active_user_ && active_user_->email() == user_id)
323 return FindUserInList(user_id);
326 User* UserManagerBase::FindUserAndModify(const std::string& user_id) {
327 DCHECK(task_runner_->RunsTasksOnCurrentThread());
328 if (active_user_ && active_user_->email() == user_id)
330 return FindUserInListAndModify(user_id);
333 const User* UserManagerBase::GetLoggedInUser() const {
334 DCHECK(task_runner_->RunsTasksOnCurrentThread());
338 User* UserManagerBase::GetLoggedInUser() {
339 DCHECK(task_runner_->RunsTasksOnCurrentThread());
343 const User* UserManagerBase::GetActiveUser() const {
344 DCHECK(task_runner_->RunsTasksOnCurrentThread());
348 User* UserManagerBase::GetActiveUser() {
349 DCHECK(task_runner_->RunsTasksOnCurrentThread());
353 const User* UserManagerBase::GetPrimaryUser() const {
354 DCHECK(task_runner_->RunsTasksOnCurrentThread());
355 return primary_user_;
358 void UserManagerBase::SaveUserOAuthStatus(
359 const std::string& user_id,
360 User::OAuthTokenStatus oauth_token_status) {
361 DCHECK(task_runner_->RunsTasksOnCurrentThread());
363 DVLOG(1) << "Saving user OAuth token status in Local State";
364 User* user = FindUserAndModify(user_id);
366 user->set_oauth_token_status(oauth_token_status);
368 // Do not update local state if data stored or cached outside the user's
369 // cryptohome is to be treated as ephemeral.
370 if (IsUserNonCryptohomeDataEphemeral(user_id))
373 DictionaryPrefUpdate oauth_status_update(GetLocalState(),
374 kUserOAuthTokenStatus);
375 oauth_status_update->SetWithoutPathExpansion(
377 new base::FundamentalValue(static_cast<int>(oauth_token_status)));
380 void UserManagerBase::SaveForceOnlineSignin(const std::string& user_id,
381 bool force_online_signin) {
382 DCHECK(task_runner_->RunsTasksOnCurrentThread());
384 // Do not update local state if data stored or cached outside the user's
385 // cryptohome is to be treated as ephemeral.
386 if (IsUserNonCryptohomeDataEphemeral(user_id))
389 DictionaryPrefUpdate force_online_update(GetLocalState(),
390 kUserForceOnlineSignin);
391 force_online_update->SetBooleanWithoutPathExpansion(user_id,
392 force_online_signin);
395 void UserManagerBase::SaveUserDisplayName(const std::string& user_id,
396 const base::string16& display_name) {
397 DCHECK(task_runner_->RunsTasksOnCurrentThread());
399 if (User* user = FindUserAndModify(user_id)) {
400 user->set_display_name(display_name);
402 // Do not update local state if data stored or cached outside the user's
403 // cryptohome is to be treated as ephemeral.
404 if (!IsUserNonCryptohomeDataEphemeral(user_id)) {
405 DictionaryPrefUpdate display_name_update(GetLocalState(),
407 display_name_update->SetWithoutPathExpansion(
408 user_id, new base::StringValue(display_name));
413 base::string16 UserManagerBase::GetUserDisplayName(
414 const std::string& user_id) const {
415 const User* user = FindUser(user_id);
416 return user ? user->display_name() : base::string16();
419 void UserManagerBase::SaveUserDisplayEmail(const std::string& user_id,
420 const std::string& display_email) {
421 DCHECK(task_runner_->RunsTasksOnCurrentThread());
423 User* user = FindUserAndModify(user_id);
425 LOG(ERROR) << "User not found: " << user_id;
426 return; // Ignore if there is no such user.
429 user->set_display_email(display_email);
431 // Do not update local state if data stored or cached outside the user's
432 // cryptohome is to be treated as ephemeral.
433 if (IsUserNonCryptohomeDataEphemeral(user_id))
436 DictionaryPrefUpdate display_email_update(GetLocalState(), kUserDisplayEmail);
437 display_email_update->SetWithoutPathExpansion(
438 user_id, new base::StringValue(display_email));
441 std::string UserManagerBase::GetUserDisplayEmail(
442 const std::string& user_id) const {
443 const User* user = FindUser(user_id);
444 return user ? user->display_email() : user_id;
447 void UserManagerBase::UpdateUserAccountData(
448 const std::string& user_id,
449 const UserAccountData& account_data) {
450 DCHECK(task_runner_->RunsTasksOnCurrentThread());
452 SaveUserDisplayName(user_id, account_data.display_name());
454 if (User* user = FindUserAndModify(user_id)) {
455 base::string16 given_name = account_data.given_name();
456 user->set_given_name(given_name);
457 if (!IsUserNonCryptohomeDataEphemeral(user_id)) {
458 DictionaryPrefUpdate given_name_update(GetLocalState(), kUserGivenName);
459 given_name_update->SetWithoutPathExpansion(
460 user_id, new base::StringValue(given_name));
464 UpdateUserAccountLocale(user_id, account_data.locale());
468 void UserManagerBase::ParseUserList(const base::ListValue& users_list,
469 const std::set<std::string>& existing_users,
470 std::vector<std::string>* users_vector,
471 std::set<std::string>* users_set) {
472 users_vector->clear();
474 for (size_t i = 0; i < users_list.GetSize(); ++i) {
476 if (!users_list.GetString(i, &email) || email.empty()) {
477 LOG(ERROR) << "Corrupt entry in user list at index " << i << ".";
480 if (existing_users.find(email) != existing_users.end() ||
481 !users_set->insert(email).second) {
482 LOG(ERROR) << "Duplicate user: " << email;
485 users_vector->push_back(email);
489 bool UserManagerBase::IsCurrentUserOwner() const {
490 DCHECK(task_runner_->RunsTasksOnCurrentThread());
491 base::AutoLock lk(is_current_user_owner_lock_);
492 return is_current_user_owner_;
495 void UserManagerBase::SetCurrentUserIsOwner(bool is_current_user_owner) {
496 DCHECK(task_runner_->RunsTasksOnCurrentThread());
498 base::AutoLock lk(is_current_user_owner_lock_);
499 is_current_user_owner_ = is_current_user_owner;
504 bool UserManagerBase::IsCurrentUserNew() const {
505 DCHECK(task_runner_->RunsTasksOnCurrentThread());
506 return is_current_user_new_;
509 bool UserManagerBase::IsCurrentUserNonCryptohomeDataEphemeral() const {
510 DCHECK(task_runner_->RunsTasksOnCurrentThread());
511 return IsUserLoggedIn() &&
512 IsUserNonCryptohomeDataEphemeral(GetLoggedInUser()->email());
515 bool UserManagerBase::CanCurrentUserLock() const {
516 DCHECK(task_runner_->RunsTasksOnCurrentThread());
517 return IsUserLoggedIn() && active_user_->can_lock();
520 bool UserManagerBase::IsUserLoggedIn() const {
521 DCHECK(task_runner_->RunsTasksOnCurrentThread());
525 bool UserManagerBase::IsLoggedInAsRegularUser() const {
526 DCHECK(task_runner_->RunsTasksOnCurrentThread());
527 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_REGULAR;
530 bool UserManagerBase::IsLoggedInAsDemoUser() const {
531 DCHECK(task_runner_->RunsTasksOnCurrentThread());
532 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_RETAIL_MODE;
535 bool UserManagerBase::IsLoggedInAsPublicAccount() const {
536 DCHECK(task_runner_->RunsTasksOnCurrentThread());
537 return IsUserLoggedIn() &&
538 active_user_->GetType() == USER_TYPE_PUBLIC_ACCOUNT;
541 bool UserManagerBase::IsLoggedInAsGuest() const {
542 DCHECK(task_runner_->RunsTasksOnCurrentThread());
543 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_GUEST;
546 bool UserManagerBase::IsLoggedInAsSupervisedUser() const {
547 DCHECK(task_runner_->RunsTasksOnCurrentThread());
548 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_SUPERVISED;
551 bool UserManagerBase::IsLoggedInAsKioskApp() const {
552 DCHECK(task_runner_->RunsTasksOnCurrentThread());
553 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_KIOSK_APP;
556 bool UserManagerBase::IsLoggedInAsStub() const {
557 DCHECK(task_runner_->RunsTasksOnCurrentThread());
558 return IsUserLoggedIn() &&
559 active_user_->email() == chromeos::login::kStubUser;
562 bool UserManagerBase::IsSessionStarted() const {
563 DCHECK(task_runner_->RunsTasksOnCurrentThread());
564 return session_started_;
567 bool UserManagerBase::IsUserNonCryptohomeDataEphemeral(
568 const std::string& user_id) const {
569 // Data belonging to the guest, retail mode and stub users is always
571 if (user_id == chromeos::login::kGuestUserName ||
572 user_id == chromeos::login::kRetailModeUserName ||
573 user_id == chromeos::login::kStubUser) {
577 // Data belonging to the owner, anyone found on the user list and obsolete
578 // public accounts whose data has not been removed yet is not ephemeral.
579 if (user_id == GetOwnerEmail() || UserExistsInList(user_id) ||
580 IsPublicAccountMarkedForRemoval(user_id)) {
584 // Data belonging to the currently logged-in user is ephemeral when:
585 // a) The user logged into a regular account while the ephemeral users policy
588 // b) The user logged into any other account type.
589 if (IsUserLoggedIn() && (user_id == GetLoggedInUser()->email()) &&
590 (is_current_user_ephemeral_regular_user_ || !IsLoggedInAsRegularUser())) {
594 // Data belonging to any other user is ephemeral when:
595 // a) Going through the regular login flow and the ephemeral users policy is
598 // b) The browser is restarting after a crash.
599 return AreEphemeralUsersEnabled() ||
600 session_manager::SessionManager::HasBrowserRestarted();
603 void UserManagerBase::AddObserver(UserManager::Observer* obs) {
604 DCHECK(task_runner_->RunsTasksOnCurrentThread());
605 observer_list_.AddObserver(obs);
608 void UserManagerBase::RemoveObserver(UserManager::Observer* obs) {
609 DCHECK(task_runner_->RunsTasksOnCurrentThread());
610 observer_list_.RemoveObserver(obs);
613 void UserManagerBase::AddSessionStateObserver(
614 UserManager::UserSessionStateObserver* obs) {
615 DCHECK(task_runner_->RunsTasksOnCurrentThread());
616 session_state_observer_list_.AddObserver(obs);
619 void UserManagerBase::RemoveSessionStateObserver(
620 UserManager::UserSessionStateObserver* obs) {
621 DCHECK(task_runner_->RunsTasksOnCurrentThread());
622 session_state_observer_list_.RemoveObserver(obs);
625 void UserManagerBase::NotifyLocalStateChanged() {
626 DCHECK(task_runner_->RunsTasksOnCurrentThread());
628 UserManager::Observer, observer_list_, LocalStateChanged(this));
631 bool UserManagerBase::CanUserBeRemoved(const User* user) const {
632 // Only regular and supervised users are allowed to be manually removed.
633 if (!user || (user->GetType() != USER_TYPE_REGULAR &&
634 user->GetType() != USER_TYPE_SUPERVISED)) {
638 // Sanity check: we must not remove single user unless it's an enterprise
639 // device. This check may seem redundant at a first sight because
640 // this single user must be an owner and we perform special check later
641 // in order not to remove an owner. However due to non-instant nature of
642 // ownership assignment this later check may sometimes fail.
643 // See http://crosbug.com/12723
644 if (users_.size() < 2 && !IsEnterpriseManaged())
647 // Sanity check: do not allow any of the the logged in users to be removed.
648 for (UserList::const_iterator it = logged_in_users_.begin();
649 it != logged_in_users_.end();
651 if ((*it)->email() == user->email())
658 bool UserManagerBase::GetEphemeralUsersEnabled() const {
659 return ephemeral_users_enabled_;
662 void UserManagerBase::SetEphemeralUsersEnabled(bool enabled) {
663 ephemeral_users_enabled_ = enabled;
666 void UserManagerBase::SetIsCurrentUserNew(bool is_new) {
667 is_current_user_new_ = is_new;
670 void UserManagerBase::SetOwnerEmail(std::string owner_user_id) {
671 owner_email_ = owner_user_id;
674 const std::string& UserManagerBase::GetPendingUserSwitchID() const {
675 return pending_user_switch_;
678 void UserManagerBase::SetPendingUserSwitchID(std::string user_id) {
679 pending_user_switch_ = user_id;
682 void UserManagerBase::EnsureUsersLoaded() {
683 DCHECK(task_runner_->RunsTasksOnCurrentThread());
684 if (!GetLocalState())
687 if (user_loading_stage_ != STAGE_NOT_LOADED)
689 user_loading_stage_ = STAGE_LOADING;
691 PerformPreUserListLoadingActions();
693 PrefService* local_state = GetLocalState();
694 const base::ListValue* prefs_regular_users =
695 local_state->GetList(kRegularUsers);
697 const base::DictionaryValue* prefs_display_names =
698 local_state->GetDictionary(kUserDisplayName);
699 const base::DictionaryValue* prefs_given_names =
700 local_state->GetDictionary(kUserGivenName);
701 const base::DictionaryValue* prefs_display_emails =
702 local_state->GetDictionary(kUserDisplayEmail);
704 // Load public sessions first.
705 std::set<std::string> public_sessions_set;
706 LoadPublicAccounts(&public_sessions_set);
708 // Load regular users and supervised users.
709 std::vector<std::string> regular_users;
710 std::set<std::string> regular_users_set;
711 ParseUserList(*prefs_regular_users,
715 for (std::vector<std::string>::const_iterator it = regular_users.begin();
716 it != regular_users.end();
719 const std::string domain = gaia::ExtractDomainName(*it);
720 if (domain == chromeos::login::kSupervisedUserDomain)
721 user = User::CreateSupervisedUser(*it);
723 user = User::CreateRegularUser(*it);
724 user->set_oauth_token_status(LoadUserOAuthStatus(*it));
725 user->set_force_online_signin(LoadForceOnlineSignin(*it));
726 users_.push_back(user);
728 base::string16 display_name;
729 if (prefs_display_names->GetStringWithoutPathExpansion(*it,
731 user->set_display_name(display_name);
734 base::string16 given_name;
735 if (prefs_given_names->GetStringWithoutPathExpansion(*it, &given_name)) {
736 user->set_given_name(given_name);
739 std::string display_email;
740 if (prefs_display_emails->GetStringWithoutPathExpansion(*it,
742 user->set_display_email(display_email);
746 user_loading_stage_ = STAGE_LOADED;
748 PerformPostUserListLoadingActions();
751 UserList& UserManagerBase::GetUsersAndModify() {
756 const User* UserManagerBase::FindUserInList(const std::string& user_id) const {
757 const UserList& users = GetUsers();
758 for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) {
759 if ((*it)->email() == user_id)
765 const bool UserManagerBase::UserExistsInList(const std::string& user_id) const {
766 const base::ListValue* user_list = GetLocalState()->GetList(kRegularUsers);
767 for (size_t i = 0; i < user_list->GetSize(); ++i) {
769 if (user_list->GetString(i, &email) && (user_id == email))
775 User* UserManagerBase::FindUserInListAndModify(const std::string& user_id) {
776 UserList& users = GetUsersAndModify();
777 for (UserList::iterator it = users.begin(); it != users.end(); ++it) {
778 if ((*it)->email() == user_id)
784 void UserManagerBase::GuestUserLoggedIn() {
785 DCHECK(task_runner_->RunsTasksOnCurrentThread());
786 active_user_ = User::CreateGuestUser();
789 void UserManagerBase::AddUserRecord(User* user) {
790 // Add the user to the front of the user list.
791 ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers);
792 prefs_users_update->Insert(0, new base::StringValue(user->email()));
793 users_.insert(users_.begin(), user);
796 void UserManagerBase::RegularUserLoggedIn(const std::string& user_id) {
797 // Remove the user from the user list.
798 active_user_ = RemoveRegularOrSupervisedUserFromList(user_id);
800 // If the user was not found on the user list, create a new user.
801 SetIsCurrentUserNew(!active_user_);
802 if (IsCurrentUserNew()) {
803 active_user_ = User::CreateRegularUser(user_id);
804 active_user_->set_oauth_token_status(LoadUserOAuthStatus(user_id));
805 SaveUserDisplayName(active_user_->email(),
806 base::UTF8ToUTF16(active_user_->GetAccountName(true)));
809 AddUserRecord(active_user_);
811 // Make sure that new data is persisted to Local State.
812 GetLocalState()->CommitPendingWrite();
815 void UserManagerBase::RegularUserLoggedInAsEphemeral(
816 const std::string& user_id) {
817 DCHECK(task_runner_->RunsTasksOnCurrentThread());
818 SetIsCurrentUserNew(true);
819 is_current_user_ephemeral_regular_user_ = true;
820 active_user_ = User::CreateRegularUser(user_id);
823 void UserManagerBase::NotifyOnLogin() {
824 DCHECK(task_runner_->RunsTasksOnCurrentThread());
826 NotifyActiveUserHashChanged(active_user_->username_hash());
827 NotifyActiveUserChanged(active_user_);
831 User::OAuthTokenStatus UserManagerBase::LoadUserOAuthStatus(
832 const std::string& user_id) const {
833 DCHECK(task_runner_->RunsTasksOnCurrentThread());
835 const base::DictionaryValue* prefs_oauth_status =
836 GetLocalState()->GetDictionary(kUserOAuthTokenStatus);
837 int oauth_token_status = User::OAUTH_TOKEN_STATUS_UNKNOWN;
838 if (prefs_oauth_status &&
839 prefs_oauth_status->GetIntegerWithoutPathExpansion(user_id,
840 &oauth_token_status)) {
841 User::OAuthTokenStatus status =
842 static_cast<User::OAuthTokenStatus>(oauth_token_status);
843 HandleUserOAuthTokenStatusChange(user_id, status);
847 return User::OAUTH_TOKEN_STATUS_UNKNOWN;
850 bool UserManagerBase::LoadForceOnlineSignin(const std::string& user_id) const {
851 DCHECK(task_runner_->RunsTasksOnCurrentThread());
853 const base::DictionaryValue* prefs_force_online =
854 GetLocalState()->GetDictionary(kUserForceOnlineSignin);
855 bool force_online_signin = false;
856 if (prefs_force_online) {
857 prefs_force_online->GetBooleanWithoutPathExpansion(user_id,
858 &force_online_signin);
860 return force_online_signin;
863 void UserManagerBase::RemoveNonCryptohomeData(const std::string& user_id) {
864 PrefService* prefs = GetLocalState();
865 DictionaryPrefUpdate prefs_display_name_update(prefs, kUserDisplayName);
866 prefs_display_name_update->RemoveWithoutPathExpansion(user_id, NULL);
868 DictionaryPrefUpdate prefs_given_name_update(prefs, kUserGivenName);
869 prefs_given_name_update->RemoveWithoutPathExpansion(user_id, NULL);
871 DictionaryPrefUpdate prefs_display_email_update(prefs, kUserDisplayEmail);
872 prefs_display_email_update->RemoveWithoutPathExpansion(user_id, NULL);
874 DictionaryPrefUpdate prefs_oauth_update(prefs, kUserOAuthTokenStatus);
875 prefs_oauth_update->RemoveWithoutPathExpansion(user_id, NULL);
877 DictionaryPrefUpdate prefs_force_online_update(prefs, kUserForceOnlineSignin);
878 prefs_force_online_update->RemoveWithoutPathExpansion(user_id, NULL);
881 User* UserManagerBase::RemoveRegularOrSupervisedUserFromList(
882 const std::string& user_id) {
883 ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers);
884 prefs_users_update->Clear();
886 for (UserList::iterator it = users_.begin(); it != users_.end();) {
887 const std::string user_email = (*it)->email();
888 if (user_email == user_id) {
890 it = users_.erase(it);
892 if ((*it)->GetType() == USER_TYPE_REGULAR ||
893 (*it)->GetType() == USER_TYPE_SUPERVISED) {
894 prefs_users_update->Append(new base::StringValue(user_email));
902 void UserManagerBase::NotifyActiveUserChanged(const User* active_user) {
903 DCHECK(task_runner_->RunsTasksOnCurrentThread());
904 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
905 session_state_observer_list_,
906 ActiveUserChanged(active_user));
909 void UserManagerBase::NotifyUserAddedToSession(const User* added_user,
910 bool user_switch_pending) {
911 DCHECK(task_runner_->RunsTasksOnCurrentThread());
912 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
913 session_state_observer_list_,
914 UserAddedToSession(added_user));
917 void UserManagerBase::NotifyActiveUserHashChanged(const std::string& hash) {
918 DCHECK(task_runner_->RunsTasksOnCurrentThread());
919 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
920 session_state_observer_list_,
921 ActiveUserHashChanged(hash));
924 void UserManagerBase::UpdateLoginState() {
925 if (!chromeos::LoginState::IsInitialized())
926 return; // LoginState may not be intialized in tests.
928 chromeos::LoginState::LoggedInState logged_in_state;
929 logged_in_state = active_user_ ? chromeos::LoginState::LOGGED_IN_ACTIVE
930 : chromeos::LoginState::LOGGED_IN_NONE;
932 chromeos::LoginState::LoggedInUserType login_user_type;
933 if (logged_in_state == chromeos::LoginState::LOGGED_IN_NONE)
934 login_user_type = chromeos::LoginState::LOGGED_IN_USER_NONE;
935 else if (is_current_user_owner_)
936 login_user_type = chromeos::LoginState::LOGGED_IN_USER_OWNER;
937 else if (active_user_->GetType() == USER_TYPE_GUEST)
938 login_user_type = chromeos::LoginState::LOGGED_IN_USER_GUEST;
939 else if (active_user_->GetType() == USER_TYPE_RETAIL_MODE)
940 login_user_type = chromeos::LoginState::LOGGED_IN_USER_RETAIL_MODE;
941 else if (active_user_->GetType() == USER_TYPE_PUBLIC_ACCOUNT)
942 login_user_type = chromeos::LoginState::LOGGED_IN_USER_PUBLIC_ACCOUNT;
943 else if (active_user_->GetType() == USER_TYPE_SUPERVISED)
944 login_user_type = chromeos::LoginState::LOGGED_IN_USER_SUPERVISED;
945 else if (active_user_->GetType() == USER_TYPE_KIOSK_APP)
946 login_user_type = chromeos::LoginState::LOGGED_IN_USER_KIOSK_APP;
948 login_user_type = chromeos::LoginState::LOGGED_IN_USER_REGULAR;
951 chromeos::LoginState::Get()->SetLoggedInStateAndPrimaryUser(
952 logged_in_state, login_user_type, primary_user_->username_hash());
954 chromeos::LoginState::Get()->SetLoggedInState(logged_in_state,
959 void UserManagerBase::SetLRUUser(User* user) {
960 UserList::iterator it =
961 std::find(lru_logged_in_users_.begin(), lru_logged_in_users_.end(), user);
962 if (it != lru_logged_in_users_.end())
963 lru_logged_in_users_.erase(it);
964 lru_logged_in_users_.insert(lru_logged_in_users_.begin(), user);
967 void UserManagerBase::SendRegularUserLoginMetrics(const std::string& user_id) {
968 // If this isn't the first time Chrome was run after the system booted,
969 // assume that Chrome was restarted because a previous session ended.
970 if (!CommandLine::ForCurrentProcess()->HasSwitch(
971 chromeos::switches::kFirstExecAfterBoot)) {
972 const std::string last_email =
973 GetLocalState()->GetString(kLastLoggedInRegularUser);
974 const base::TimeDelta time_to_login =
975 base::TimeTicks::Now() - manager_creation_time_;
976 if (!last_email.empty() && user_id != last_email &&
977 time_to_login.InSeconds() <= kLogoutToLoginDelayMaxSec) {
978 UMA_HISTOGRAM_CUSTOM_COUNTS("UserManager.LogoutToLoginDelay",
979 time_to_login.InSeconds(),
981 kLogoutToLoginDelayMaxSec,
987 void UserManagerBase::UpdateUserAccountLocale(const std::string& user_id,
988 const std::string& locale) {
989 if (!locale.empty() && locale != GetApplicationLocale()) {
990 base::Callback<void(const std::string&)> on_resolve_callback =
991 base::Bind(&UserManagerBase::DoUpdateAccountLocale,
992 weak_factory_.GetWeakPtr(),
994 blocking_task_runner_->PostTask(FROM_HERE,
995 base::Bind(&UserManagerBase::ResolveLocale,
996 weak_factory_.GetWeakPtr(),
998 on_resolve_callback));
1000 DoUpdateAccountLocale(user_id, locale);
1004 void UserManagerBase::ResolveLocale(
1005 const std::string& raw_locale,
1006 base::Callback<void(const std::string&)> on_resolve_callback) {
1007 DCHECK(task_runner_->RunsTasksOnCurrentThread());
1008 std::string resolved_locale;
1009 ignore_result(l10n_util::CheckAndResolveLocale(raw_locale, &resolved_locale));
1010 task_runner_->PostTask(FROM_HERE,
1011 base::Bind(on_resolve_callback, resolved_locale));
1014 void UserManagerBase::DoUpdateAccountLocale(
1015 const std::string& user_id,
1016 const std::string& resolved_locale) {
1017 if (User* user = FindUserAndModify(user_id))
1018 user->SetAccountLocale(resolved_locale);
1021 void UserManagerBase::DeleteUser(User* user) {
1022 const bool is_active_user = (user == active_user_);
1025 active_user_ = NULL;
1028 } // namespace user_manager