Use appropriate EXPECT_EQ argument order for BookmarkModelTest assertions
[chromium-blink-merge.git] / components / user_manager / user_manager_base.cc
blobe289fadb0a18bae4ca5996c48411673d2d0c1ae5
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"
7 #include <cstddef>
8 #include <set>
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 {
38 namespace {
40 // A vector pref of the the regular users known on this device, arranged in LRU
41 // order.
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 dictionary that maps user ID to the user type.
61 const char kUserType[] = "UserType";
63 // A string pref containing the ID of the last user who logged in if it was
64 // a user with gaia account (regular) or an empty string if it was another type
65 // of user (guest, kiosk, public account, etc.).
66 const char kLastLoggedInGaiaUser[] = "LastLoggedInRegularUser";
68 // A string pref containing the ID of the last active user.
69 // In case of browser crash, this pref will be used to set active user after
70 // session restore.
71 const char kLastActiveUser[] = "LastActiveUser";
73 // Upper bound for a histogram metric reporting the amount of time between
74 // one regular user logging out and a different regular user logging in.
75 const int kLogoutToLoginDelayMaxSec = 1800;
77 // Callback that is called after user removal is complete.
78 void OnRemoveUserComplete(const std::string& user_email,
79 bool success,
80 cryptohome::MountError return_code) {
81 // Log the error, but there's not much we can do.
82 if (!success) {
83 LOG(ERROR) << "Removal of cryptohome for " << user_email
84 << " failed, return code: " << return_code;
88 // Runs on SequencedWorkerPool thread. Passes resolved locale to UI thread.
89 void ResolveLocale(const std::string& raw_locale,
90 std::string* resolved_locale) {
91 ignore_result(l10n_util::CheckAndResolveLocale(raw_locale, resolved_locale));
94 } // namespace
96 // static
97 void UserManagerBase::RegisterPrefs(PrefRegistrySimple* registry) {
98 registry->RegisterListPref(kRegularUsers);
99 registry->RegisterStringPref(kLastLoggedInGaiaUser, std::string());
100 registry->RegisterDictionaryPref(kUserDisplayName);
101 registry->RegisterDictionaryPref(kUserGivenName);
102 registry->RegisterDictionaryPref(kUserDisplayEmail);
103 registry->RegisterDictionaryPref(kUserOAuthTokenStatus);
104 registry->RegisterDictionaryPref(kUserForceOnlineSignin);
105 registry->RegisterDictionaryPref(kUserType);
106 registry->RegisterStringPref(kLastActiveUser, std::string());
109 UserManagerBase::UserManagerBase(
110 scoped_refptr<base::TaskRunner> task_runner,
111 scoped_refptr<base::TaskRunner> blocking_task_runner)
112 : active_user_(NULL),
113 primary_user_(NULL),
114 user_loading_stage_(STAGE_NOT_LOADED),
115 session_started_(false),
116 is_current_user_owner_(false),
117 is_current_user_new_(false),
118 is_current_user_ephemeral_regular_user_(false),
119 ephemeral_users_enabled_(false),
120 manager_creation_time_(base::TimeTicks::Now()),
121 last_session_active_user_initialized_(false),
122 task_runner_(task_runner),
123 blocking_task_runner_(blocking_task_runner),
124 weak_factory_(this) {
125 UpdateLoginState();
128 UserManagerBase::~UserManagerBase() {
129 // Can't use STLDeleteElements because of the private destructor of User.
130 for (UserList::iterator it = users_.begin(); it != users_.end();
131 it = users_.erase(it)) {
132 DeleteUser(*it);
134 // These are pointers to the same User instances that were in users_ list.
135 logged_in_users_.clear();
136 lru_logged_in_users_.clear();
138 DeleteUser(active_user_);
141 void UserManagerBase::Shutdown() {
142 DCHECK(task_runner_->RunsTasksOnCurrentThread());
145 const UserList& UserManagerBase::GetUsers() const {
146 const_cast<UserManagerBase*>(this)->EnsureUsersLoaded();
147 return users_;
150 const UserList& UserManagerBase::GetLoggedInUsers() const {
151 return logged_in_users_;
154 const UserList& UserManagerBase::GetLRULoggedInUsers() const {
155 return lru_logged_in_users_;
158 const std::string& UserManagerBase::GetOwnerEmail() const {
159 return owner_email_;
162 void UserManagerBase::UserLoggedIn(const std::string& user_id,
163 const std::string& username_hash,
164 bool browser_restart) {
165 DCHECK(task_runner_->RunsTasksOnCurrentThread());
167 if (!last_session_active_user_initialized_) {
168 last_session_active_user_ = GetLocalState()->GetString(kLastActiveUser);
169 last_session_active_user_initialized_ = true;
172 User* user = FindUserInListAndModify(user_id);
173 if (active_user_ && user) {
174 user->set_is_logged_in(true);
175 user->set_username_hash(username_hash);
176 logged_in_users_.push_back(user);
177 lru_logged_in_users_.push_back(user);
179 // Reset the new user flag if the user already exists.
180 SetIsCurrentUserNew(false);
181 NotifyUserAddedToSession(user, true /* user switch pending */);
183 return;
186 if (user_id == chromeos::login::kGuestUserName) {
187 GuestUserLoggedIn();
188 } else if (user_id == chromeos::login::kRetailModeUserName) {
189 RetailModeUserLoggedIn();
190 } else if (IsKioskApp(user_id)) {
191 KioskAppLoggedIn(user_id);
192 } else if (IsDemoApp(user_id)) {
193 DemoAccountLoggedIn();
194 } else {
195 EnsureUsersLoaded();
197 if (user && user->GetType() == USER_TYPE_PUBLIC_ACCOUNT) {
198 PublicAccountUserLoggedIn(user);
199 } else if ((user && user->GetType() == USER_TYPE_SUPERVISED) ||
200 (!user &&
201 gaia::ExtractDomainName(user_id) ==
202 chromeos::login::kSupervisedUserDomain)) {
203 SupervisedUserLoggedIn(user_id);
204 } else if (browser_restart && IsPublicAccountMarkedForRemoval(user_id)) {
205 PublicAccountUserLoggedIn(User::CreatePublicAccountUser(user_id));
206 } else if (user_id != GetOwnerEmail() && !user &&
207 (AreEphemeralUsersEnabled() || browser_restart)) {
208 RegularUserLoggedInAsEphemeral(user_id);
209 } else {
210 RegularUserLoggedIn(user_id);
214 DCHECK(active_user_);
215 active_user_->set_is_logged_in(true);
216 active_user_->set_is_active(true);
217 active_user_->set_username_hash(username_hash);
219 // Place user who just signed in to the top of the logged in users.
220 logged_in_users_.insert(logged_in_users_.begin(), active_user_);
221 SetLRUUser(active_user_);
223 if (!primary_user_) {
224 primary_user_ = active_user_;
225 if (primary_user_->HasGaiaAccount())
226 SendGaiaUserLoginMetrics(user_id);
229 UMA_HISTOGRAM_ENUMERATION(
230 "UserManager.LoginUserType", active_user_->GetType(), NUM_USER_TYPES);
232 GetLocalState()->SetString(
233 kLastLoggedInGaiaUser, active_user_->HasGaiaAccount() ? user_id : "");
235 NotifyOnLogin();
236 PerformPostUserLoggedInActions(browser_restart);
239 void UserManagerBase::SwitchActiveUser(const std::string& user_id) {
240 User* user = FindUserAndModify(user_id);
241 if (!user) {
242 NOTREACHED() << "Switching to a non-existing user";
243 return;
245 if (user == active_user_) {
246 NOTREACHED() << "Switching to a user who is already active";
247 return;
249 if (!user->is_logged_in()) {
250 NOTREACHED() << "Switching to a user that is not logged in";
251 return;
253 if (!user->HasGaiaAccount()) {
254 NOTREACHED() <<
255 "Switching to a user without gaia account (non-regular one)";
256 return;
258 if (user->username_hash().empty()) {
259 NOTREACHED() << "Switching to a user that doesn't have username_hash set";
260 return;
263 DCHECK(active_user_);
264 active_user_->set_is_active(false);
265 user->set_is_active(true);
266 active_user_ = user;
268 // Move the user to the front.
269 SetLRUUser(active_user_);
271 NotifyActiveUserHashChanged(active_user_->username_hash());
272 NotifyActiveUserChanged(active_user_);
275 void UserManagerBase::SwitchToLastActiveUser() {
276 if (last_session_active_user_.empty())
277 return;
279 if (GetActiveUser()->email() != last_session_active_user_)
280 SwitchActiveUser(last_session_active_user_);
282 // Make sure that this function gets run only once.
283 last_session_active_user_.clear();
286 void UserManagerBase::SessionStarted() {
287 DCHECK(task_runner_->RunsTasksOnCurrentThread());
288 session_started_ = true;
290 UpdateLoginState();
291 session_manager::SessionManager::Get()->SetSessionState(
292 session_manager::SESSION_STATE_ACTIVE);
294 if (IsCurrentUserNew()) {
295 // Make sure that the new user's data is persisted to Local State.
296 GetLocalState()->CommitPendingWrite();
300 void UserManagerBase::RemoveUser(const std::string& user_id,
301 RemoveUserDelegate* delegate) {
302 DCHECK(task_runner_->RunsTasksOnCurrentThread());
304 if (!CanUserBeRemoved(FindUser(user_id)))
305 return;
307 RemoveUserInternal(user_id, delegate);
310 void UserManagerBase::RemoveUserInternal(const std::string& user_email,
311 RemoveUserDelegate* delegate) {
312 RemoveNonOwnerUserInternal(user_email, delegate);
315 void UserManagerBase::RemoveNonOwnerUserInternal(const std::string& user_email,
316 RemoveUserDelegate* delegate) {
317 if (delegate)
318 delegate->OnBeforeUserRemoved(user_email);
319 RemoveUserFromList(user_email);
320 cryptohome::AsyncMethodCaller::GetInstance()->AsyncRemove(
321 user_email, base::Bind(&OnRemoveUserComplete, user_email));
323 if (delegate)
324 delegate->OnUserRemoved(user_email);
327 void UserManagerBase::RemoveUserFromList(const std::string& user_id) {
328 DCHECK(task_runner_->RunsTasksOnCurrentThread());
329 RemoveNonCryptohomeData(user_id);
330 if (user_loading_stage_ == STAGE_LOADED) {
331 DeleteUser(RemoveRegularOrSupervisedUserFromList(user_id));
332 } else if (user_loading_stage_ == STAGE_LOADING) {
333 DCHECK(gaia::ExtractDomainName(user_id) ==
334 chromeos::login::kSupervisedUserDomain);
335 // Special case, removing partially-constructed supervised user during user
336 // list loading.
337 ListPrefUpdate users_update(GetLocalState(), kRegularUsers);
338 users_update->Remove(base::StringValue(user_id), NULL);
339 } else {
340 NOTREACHED() << "Users are not loaded yet.";
341 return;
344 // Make sure that new data is persisted to Local State.
345 GetLocalState()->CommitPendingWrite();
348 bool UserManagerBase::IsKnownUser(const std::string& user_id) const {
349 return FindUser(user_id) != NULL;
352 const User* UserManagerBase::FindUser(const std::string& user_id) const {
353 DCHECK(task_runner_->RunsTasksOnCurrentThread());
354 if (active_user_ && active_user_->email() == user_id)
355 return active_user_;
356 return FindUserInList(user_id);
359 User* UserManagerBase::FindUserAndModify(const std::string& user_id) {
360 DCHECK(task_runner_->RunsTasksOnCurrentThread());
361 if (active_user_ && active_user_->email() == user_id)
362 return active_user_;
363 return FindUserInListAndModify(user_id);
366 const User* UserManagerBase::GetLoggedInUser() const {
367 DCHECK(task_runner_->RunsTasksOnCurrentThread());
368 return active_user_;
371 User* UserManagerBase::GetLoggedInUser() {
372 DCHECK(task_runner_->RunsTasksOnCurrentThread());
373 return active_user_;
376 const User* UserManagerBase::GetActiveUser() const {
377 DCHECK(task_runner_->RunsTasksOnCurrentThread());
378 return active_user_;
381 User* UserManagerBase::GetActiveUser() {
382 DCHECK(task_runner_->RunsTasksOnCurrentThread());
383 return active_user_;
386 const User* UserManagerBase::GetPrimaryUser() const {
387 DCHECK(task_runner_->RunsTasksOnCurrentThread());
388 return primary_user_;
391 void UserManagerBase::SaveUserOAuthStatus(
392 const std::string& user_id,
393 User::OAuthTokenStatus oauth_token_status) {
394 DCHECK(task_runner_->RunsTasksOnCurrentThread());
396 DVLOG(1) << "Saving user OAuth token status in Local State";
397 User* user = FindUserAndModify(user_id);
398 if (user)
399 user->set_oauth_token_status(oauth_token_status);
401 // Do not update local state if data stored or cached outside the user's
402 // cryptohome is to be treated as ephemeral.
403 if (IsUserNonCryptohomeDataEphemeral(user_id))
404 return;
406 DictionaryPrefUpdate oauth_status_update(GetLocalState(),
407 kUserOAuthTokenStatus);
408 oauth_status_update->SetWithoutPathExpansion(
409 user_id,
410 new base::FundamentalValue(static_cast<int>(oauth_token_status)));
413 void UserManagerBase::SaveForceOnlineSignin(const std::string& user_id,
414 bool force_online_signin) {
415 DCHECK(task_runner_->RunsTasksOnCurrentThread());
417 // Do not update local state if data stored or cached outside the user's
418 // cryptohome is to be treated as ephemeral.
419 if (IsUserNonCryptohomeDataEphemeral(user_id))
420 return;
422 DictionaryPrefUpdate force_online_update(GetLocalState(),
423 kUserForceOnlineSignin);
424 force_online_update->SetBooleanWithoutPathExpansion(user_id,
425 force_online_signin);
428 void UserManagerBase::SaveUserDisplayName(const std::string& user_id,
429 const base::string16& display_name) {
430 DCHECK(task_runner_->RunsTasksOnCurrentThread());
432 if (User* user = FindUserAndModify(user_id)) {
433 user->set_display_name(display_name);
435 // Do not update local state if data stored or cached outside the user's
436 // cryptohome is to be treated as ephemeral.
437 if (!IsUserNonCryptohomeDataEphemeral(user_id)) {
438 DictionaryPrefUpdate display_name_update(GetLocalState(),
439 kUserDisplayName);
440 display_name_update->SetWithoutPathExpansion(
441 user_id, new base::StringValue(display_name));
446 base::string16 UserManagerBase::GetUserDisplayName(
447 const std::string& user_id) const {
448 const User* user = FindUser(user_id);
449 return user ? user->display_name() : base::string16();
452 void UserManagerBase::SaveUserDisplayEmail(const std::string& user_id,
453 const std::string& display_email) {
454 DCHECK(task_runner_->RunsTasksOnCurrentThread());
456 User* user = FindUserAndModify(user_id);
457 if (!user) {
458 LOG(ERROR) << "User not found: " << user_id;
459 return; // Ignore if there is no such user.
462 user->set_display_email(display_email);
464 // Do not update local state if data stored or cached outside the user's
465 // cryptohome is to be treated as ephemeral.
466 if (IsUserNonCryptohomeDataEphemeral(user_id))
467 return;
469 DictionaryPrefUpdate display_email_update(GetLocalState(), kUserDisplayEmail);
470 display_email_update->SetWithoutPathExpansion(
471 user_id, new base::StringValue(display_email));
474 std::string UserManagerBase::GetUserDisplayEmail(
475 const std::string& user_id) const {
476 const User* user = FindUser(user_id);
477 return user ? user->display_email() : user_id;
480 void UserManagerBase::SaveUserType(const std::string& user_id,
481 const UserType& user_type) {
482 DCHECK(task_runner_->RunsTasksOnCurrentThread());
484 User* user = FindUserAndModify(user_id);
485 if (!user) {
486 LOG(ERROR) << "User not found: " << user_id;
487 return; // Ignore if there is no such user.
490 // Do not update local state if data stored or cached outside the user's
491 // cryptohome is to be treated as ephemeral.
492 if (IsUserNonCryptohomeDataEphemeral(user_id))
493 return;
495 DictionaryPrefUpdate user_type_update(GetLocalState(), kUserType);
496 user_type_update->SetWithoutPathExpansion(
497 user_id, new base::FundamentalValue(static_cast<int>(user_type)));
498 GetLocalState()->CommitPendingWrite();
501 void UserManagerBase::UpdateUserAccountData(
502 const std::string& user_id,
503 const UserAccountData& account_data) {
504 DCHECK(task_runner_->RunsTasksOnCurrentThread());
506 SaveUserDisplayName(user_id, account_data.display_name());
508 if (User* user = FindUserAndModify(user_id)) {
509 base::string16 given_name = account_data.given_name();
510 user->set_given_name(given_name);
511 if (!IsUserNonCryptohomeDataEphemeral(user_id)) {
512 DictionaryPrefUpdate given_name_update(GetLocalState(), kUserGivenName);
513 given_name_update->SetWithoutPathExpansion(
514 user_id, new base::StringValue(given_name));
518 UpdateUserAccountLocale(user_id, account_data.locale());
521 // static
522 void UserManagerBase::ParseUserList(const base::ListValue& users_list,
523 const std::set<std::string>& existing_users,
524 std::vector<std::string>* users_vector,
525 std::set<std::string>* users_set) {
526 users_vector->clear();
527 users_set->clear();
528 for (size_t i = 0; i < users_list.GetSize(); ++i) {
529 std::string email;
530 if (!users_list.GetString(i, &email) || email.empty()) {
531 LOG(ERROR) << "Corrupt entry in user list at index " << i << ".";
532 continue;
534 if (existing_users.find(email) != existing_users.end() ||
535 !users_set->insert(email).second) {
536 LOG(ERROR) << "Duplicate user: " << email;
537 continue;
539 users_vector->push_back(email);
543 bool UserManagerBase::IsCurrentUserOwner() const {
544 DCHECK(task_runner_->RunsTasksOnCurrentThread());
545 base::AutoLock lk(is_current_user_owner_lock_);
546 return is_current_user_owner_;
549 void UserManagerBase::SetCurrentUserIsOwner(bool is_current_user_owner) {
550 DCHECK(task_runner_->RunsTasksOnCurrentThread());
552 base::AutoLock lk(is_current_user_owner_lock_);
553 is_current_user_owner_ = is_current_user_owner;
555 UpdateLoginState();
558 bool UserManagerBase::IsCurrentUserNew() const {
559 DCHECK(task_runner_->RunsTasksOnCurrentThread());
560 return is_current_user_new_;
563 bool UserManagerBase::IsCurrentUserNonCryptohomeDataEphemeral() const {
564 DCHECK(task_runner_->RunsTasksOnCurrentThread());
565 return IsUserLoggedIn() &&
566 IsUserNonCryptohomeDataEphemeral(GetLoggedInUser()->email());
569 bool UserManagerBase::CanCurrentUserLock() const {
570 DCHECK(task_runner_->RunsTasksOnCurrentThread());
571 return IsUserLoggedIn() && active_user_->can_lock();
574 bool UserManagerBase::IsUserLoggedIn() const {
575 DCHECK(task_runner_->RunsTasksOnCurrentThread());
576 return active_user_;
579 bool UserManagerBase::IsLoggedInAsUserWithGaiaAccount() const {
580 DCHECK(task_runner_->RunsTasksOnCurrentThread());
581 return IsUserLoggedIn() && active_user_->HasGaiaAccount();
584 bool UserManagerBase::IsLoggedInAsRegularSupervisedUser() const {
585 DCHECK(task_runner_->RunsTasksOnCurrentThread());
586 return IsUserLoggedIn() && active_user_->GetType() ==
587 USER_TYPE_REGULAR_SUPERVISED;
590 bool UserManagerBase::IsLoggedInAsDemoUser() const {
591 DCHECK(task_runner_->RunsTasksOnCurrentThread());
592 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_RETAIL_MODE;
595 bool UserManagerBase::IsLoggedInAsPublicAccount() const {
596 DCHECK(task_runner_->RunsTasksOnCurrentThread());
597 return IsUserLoggedIn() &&
598 active_user_->GetType() == USER_TYPE_PUBLIC_ACCOUNT;
601 bool UserManagerBase::IsLoggedInAsGuest() const {
602 DCHECK(task_runner_->RunsTasksOnCurrentThread());
603 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_GUEST;
606 bool UserManagerBase::IsLoggedInAsSupervisedUser() const {
607 DCHECK(task_runner_->RunsTasksOnCurrentThread());
608 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_SUPERVISED;
611 bool UserManagerBase::IsLoggedInAsKioskApp() const {
612 DCHECK(task_runner_->RunsTasksOnCurrentThread());
613 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_KIOSK_APP;
616 bool UserManagerBase::IsLoggedInAsStub() const {
617 DCHECK(task_runner_->RunsTasksOnCurrentThread());
618 return IsUserLoggedIn() &&
619 active_user_->email() == chromeos::login::kStubUser;
622 bool UserManagerBase::IsSessionStarted() const {
623 DCHECK(task_runner_->RunsTasksOnCurrentThread());
624 return session_started_;
627 bool UserManagerBase::IsUserNonCryptohomeDataEphemeral(
628 const std::string& user_id) const {
629 // Data belonging to the guest, retail mode and stub users is always
630 // ephemeral.
631 if (user_id == chromeos::login::kGuestUserName ||
632 user_id == chromeos::login::kRetailModeUserName ||
633 user_id == chromeos::login::kStubUser) {
634 return true;
637 // Data belonging to the owner, anyone found on the user list and obsolete
638 // public accounts whose data has not been removed yet is not ephemeral.
639 if (user_id == GetOwnerEmail() || UserExistsInList(user_id) ||
640 IsPublicAccountMarkedForRemoval(user_id)) {
641 return false;
644 // Data belonging to the currently logged-in user is ephemeral when:
645 // a) The user logged into a regular gaia account while the ephemeral users
646 // policy was enabled.
647 // - or -
648 // b) The user logged into any other account type.
649 if (IsUserLoggedIn() && (user_id == GetLoggedInUser()->email()) &&
650 (is_current_user_ephemeral_regular_user_ ||
651 !IsLoggedInAsUserWithGaiaAccount())) {
652 return true;
655 // Data belonging to any other user is ephemeral when:
656 // a) Going through the regular login flow and the ephemeral users policy is
657 // enabled.
658 // - or -
659 // b) The browser is restarting after a crash.
660 return AreEphemeralUsersEnabled() ||
661 session_manager::SessionManager::HasBrowserRestarted();
664 void UserManagerBase::AddObserver(UserManager::Observer* obs) {
665 DCHECK(task_runner_->RunsTasksOnCurrentThread());
666 observer_list_.AddObserver(obs);
669 void UserManagerBase::RemoveObserver(UserManager::Observer* obs) {
670 DCHECK(task_runner_->RunsTasksOnCurrentThread());
671 observer_list_.RemoveObserver(obs);
674 void UserManagerBase::AddSessionStateObserver(
675 UserManager::UserSessionStateObserver* obs) {
676 DCHECK(task_runner_->RunsTasksOnCurrentThread());
677 session_state_observer_list_.AddObserver(obs);
680 void UserManagerBase::RemoveSessionStateObserver(
681 UserManager::UserSessionStateObserver* obs) {
682 DCHECK(task_runner_->RunsTasksOnCurrentThread());
683 session_state_observer_list_.RemoveObserver(obs);
686 void UserManagerBase::NotifyLocalStateChanged() {
687 DCHECK(task_runner_->RunsTasksOnCurrentThread());
688 FOR_EACH_OBSERVER(
689 UserManager::Observer, observer_list_, LocalStateChanged(this));
692 bool UserManagerBase::CanUserBeRemoved(const User* user) const {
693 // Only regular and supervised users are allowed to be manually removed.
694 if (!user || !(user->HasGaiaAccount() || user->IsSupervised()))
695 return false;
697 // Sanity check: we must not remove single user unless it's an enterprise
698 // device. This check may seem redundant at a first sight because
699 // this single user must be an owner and we perform special check later
700 // in order not to remove an owner. However due to non-instant nature of
701 // ownership assignment this later check may sometimes fail.
702 // See http://crosbug.com/12723
703 if (users_.size() < 2 && !IsEnterpriseManaged())
704 return false;
706 // Sanity check: do not allow any of the the logged in users to be removed.
707 for (UserList::const_iterator it = logged_in_users_.begin();
708 it != logged_in_users_.end();
709 ++it) {
710 if ((*it)->email() == user->email())
711 return false;
714 return true;
717 bool UserManagerBase::GetEphemeralUsersEnabled() const {
718 return ephemeral_users_enabled_;
721 void UserManagerBase::SetEphemeralUsersEnabled(bool enabled) {
722 ephemeral_users_enabled_ = enabled;
725 void UserManagerBase::SetIsCurrentUserNew(bool is_new) {
726 is_current_user_new_ = is_new;
729 void UserManagerBase::SetOwnerEmail(std::string owner_user_id) {
730 owner_email_ = owner_user_id;
733 const std::string& UserManagerBase::GetPendingUserSwitchID() const {
734 return pending_user_switch_;
737 void UserManagerBase::SetPendingUserSwitchID(std::string user_id) {
738 pending_user_switch_ = user_id;
741 void UserManagerBase::EnsureUsersLoaded() {
742 DCHECK(task_runner_->RunsTasksOnCurrentThread());
743 if (!GetLocalState())
744 return;
746 if (user_loading_stage_ != STAGE_NOT_LOADED)
747 return;
748 user_loading_stage_ = STAGE_LOADING;
750 PerformPreUserListLoadingActions();
752 PrefService* local_state = GetLocalState();
753 const base::ListValue* prefs_regular_users =
754 local_state->GetList(kRegularUsers);
756 const base::DictionaryValue* prefs_display_names =
757 local_state->GetDictionary(kUserDisplayName);
758 const base::DictionaryValue* prefs_given_names =
759 local_state->GetDictionary(kUserGivenName);
760 const base::DictionaryValue* prefs_display_emails =
761 local_state->GetDictionary(kUserDisplayEmail);
762 const base::DictionaryValue* prefs_user_types =
763 local_state->GetDictionary(kUserType);
765 // Load public sessions first.
766 std::set<std::string> public_sessions_set;
767 LoadPublicAccounts(&public_sessions_set);
769 // Load regular users and supervised users.
770 std::vector<std::string> regular_users;
771 std::set<std::string> regular_users_set;
772 ParseUserList(*prefs_regular_users,
773 public_sessions_set,
774 &regular_users,
775 &regular_users_set);
776 for (std::vector<std::string>::const_iterator it = regular_users.begin();
777 it != regular_users.end();
778 ++it) {
779 User* user = NULL;
780 const std::string domain = gaia::ExtractDomainName(*it);
781 if (domain == chromeos::login::kSupervisedUserDomain) {
782 user = User::CreateSupervisedUser(*it);
783 } else {
784 user = User::CreateRegularUser(*it);
785 int user_type;
786 if (prefs_user_types->GetIntegerWithoutPathExpansion(*it, &user_type) &&
787 user_type == USER_TYPE_REGULAR_SUPERVISED) {
788 ChangeUserSupervisedStatus(user, true /* is supervised */);
791 user->set_oauth_token_status(LoadUserOAuthStatus(*it));
792 user->set_force_online_signin(LoadForceOnlineSignin(*it));
793 users_.push_back(user);
795 base::string16 display_name;
796 if (prefs_display_names->GetStringWithoutPathExpansion(*it,
797 &display_name)) {
798 user->set_display_name(display_name);
801 base::string16 given_name;
802 if (prefs_given_names->GetStringWithoutPathExpansion(*it, &given_name)) {
803 user->set_given_name(given_name);
806 std::string display_email;
807 if (prefs_display_emails->GetStringWithoutPathExpansion(*it,
808 &display_email)) {
809 user->set_display_email(display_email);
813 user_loading_stage_ = STAGE_LOADED;
815 PerformPostUserListLoadingActions();
818 UserList& UserManagerBase::GetUsersAndModify() {
819 EnsureUsersLoaded();
820 return users_;
823 const User* UserManagerBase::FindUserInList(const std::string& user_id) const {
824 const UserList& users = GetUsers();
825 for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) {
826 if ((*it)->email() == user_id)
827 return *it;
829 return NULL;
832 bool UserManagerBase::UserExistsInList(const std::string& user_id) const {
833 const base::ListValue* user_list = GetLocalState()->GetList(kRegularUsers);
834 for (size_t i = 0; i < user_list->GetSize(); ++i) {
835 std::string email;
836 if (user_list->GetString(i, &email) && (user_id == email))
837 return true;
839 return false;
842 User* UserManagerBase::FindUserInListAndModify(const std::string& user_id) {
843 UserList& users = GetUsersAndModify();
844 for (UserList::iterator it = users.begin(); it != users.end(); ++it) {
845 if ((*it)->email() == user_id)
846 return *it;
848 return NULL;
851 void UserManagerBase::GuestUserLoggedIn() {
852 DCHECK(task_runner_->RunsTasksOnCurrentThread());
853 active_user_ = User::CreateGuestUser();
856 void UserManagerBase::AddUserRecord(User* user) {
857 // Add the user to the front of the user list.
858 ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers);
859 prefs_users_update->Insert(0, new base::StringValue(user->email()));
860 users_.insert(users_.begin(), user);
863 void UserManagerBase::RegularUserLoggedIn(const std::string& user_id) {
864 // Remove the user from the user list.
865 active_user_ = RemoveRegularOrSupervisedUserFromList(user_id);
867 // If the user was not found on the user list, create a new user.
868 SetIsCurrentUserNew(!active_user_);
869 if (IsCurrentUserNew()) {
870 active_user_ = User::CreateRegularUser(user_id);
871 active_user_->set_oauth_token_status(LoadUserOAuthStatus(user_id));
872 SaveUserDisplayName(active_user_->email(),
873 base::UTF8ToUTF16(active_user_->GetAccountName(true)));
876 AddUserRecord(active_user_);
878 // Make sure that new data is persisted to Local State.
879 GetLocalState()->CommitPendingWrite();
882 void UserManagerBase::RegularUserLoggedInAsEphemeral(
883 const std::string& user_id) {
884 DCHECK(task_runner_->RunsTasksOnCurrentThread());
885 SetIsCurrentUserNew(true);
886 is_current_user_ephemeral_regular_user_ = true;
887 active_user_ = User::CreateRegularUser(user_id);
890 void UserManagerBase::NotifyOnLogin() {
891 DCHECK(task_runner_->RunsTasksOnCurrentThread());
893 NotifyActiveUserHashChanged(active_user_->username_hash());
894 NotifyActiveUserChanged(active_user_);
895 UpdateLoginState();
898 User::OAuthTokenStatus UserManagerBase::LoadUserOAuthStatus(
899 const std::string& user_id) const {
900 DCHECK(task_runner_->RunsTasksOnCurrentThread());
902 const base::DictionaryValue* prefs_oauth_status =
903 GetLocalState()->GetDictionary(kUserOAuthTokenStatus);
904 int oauth_token_status = User::OAUTH_TOKEN_STATUS_UNKNOWN;
905 if (prefs_oauth_status &&
906 prefs_oauth_status->GetIntegerWithoutPathExpansion(user_id,
907 &oauth_token_status)) {
908 User::OAuthTokenStatus status =
909 static_cast<User::OAuthTokenStatus>(oauth_token_status);
910 HandleUserOAuthTokenStatusChange(user_id, status);
912 return status;
914 return User::OAUTH_TOKEN_STATUS_UNKNOWN;
917 bool UserManagerBase::LoadForceOnlineSignin(const std::string& user_id) const {
918 DCHECK(task_runner_->RunsTasksOnCurrentThread());
920 const base::DictionaryValue* prefs_force_online =
921 GetLocalState()->GetDictionary(kUserForceOnlineSignin);
922 bool force_online_signin = false;
923 if (prefs_force_online) {
924 prefs_force_online->GetBooleanWithoutPathExpansion(user_id,
925 &force_online_signin);
927 return force_online_signin;
930 void UserManagerBase::RemoveNonCryptohomeData(const std::string& user_id) {
931 PrefService* prefs = GetLocalState();
932 DictionaryPrefUpdate prefs_display_name_update(prefs, kUserDisplayName);
933 prefs_display_name_update->RemoveWithoutPathExpansion(user_id, NULL);
935 DictionaryPrefUpdate prefs_given_name_update(prefs, kUserGivenName);
936 prefs_given_name_update->RemoveWithoutPathExpansion(user_id, NULL);
938 DictionaryPrefUpdate prefs_display_email_update(prefs, kUserDisplayEmail);
939 prefs_display_email_update->RemoveWithoutPathExpansion(user_id, NULL);
941 DictionaryPrefUpdate prefs_oauth_update(prefs, kUserOAuthTokenStatus);
942 prefs_oauth_update->RemoveWithoutPathExpansion(user_id, NULL);
944 DictionaryPrefUpdate prefs_force_online_update(prefs, kUserForceOnlineSignin);
945 prefs_force_online_update->RemoveWithoutPathExpansion(user_id, NULL);
947 std::string last_active_user = GetLocalState()->GetString(kLastActiveUser);
948 if (user_id == last_active_user)
949 GetLocalState()->SetString(kLastActiveUser, std::string());
952 User* UserManagerBase::RemoveRegularOrSupervisedUserFromList(
953 const std::string& user_id) {
954 ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers);
955 prefs_users_update->Clear();
956 User* user = NULL;
957 for (UserList::iterator it = users_.begin(); it != users_.end();) {
958 const std::string user_email = (*it)->email();
959 if (user_email == user_id) {
960 user = *it;
961 it = users_.erase(it);
962 } else {
963 if ((*it)->HasGaiaAccount() || (*it)->IsSupervised())
964 prefs_users_update->Append(new base::StringValue(user_email));
965 ++it;
968 return user;
971 void UserManagerBase::NotifyActiveUserChanged(const User* active_user) {
972 DCHECK(task_runner_->RunsTasksOnCurrentThread());
973 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
974 session_state_observer_list_,
975 ActiveUserChanged(active_user));
978 void UserManagerBase::NotifyUserAddedToSession(const User* added_user,
979 bool user_switch_pending) {
980 DCHECK(task_runner_->RunsTasksOnCurrentThread());
981 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
982 session_state_observer_list_,
983 UserAddedToSession(added_user));
986 void UserManagerBase::NotifyActiveUserHashChanged(const std::string& hash) {
987 DCHECK(task_runner_->RunsTasksOnCurrentThread());
988 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
989 session_state_observer_list_,
990 ActiveUserHashChanged(hash));
993 void UserManagerBase::ChangeUserSupervisedStatus(User* user,
994 bool is_supervised) {
995 DCHECK(task_runner_->RunsTasksOnCurrentThread());
996 user->SetIsSupervised(is_supervised);
997 SaveUserType(user->email(), is_supervised
998 ? user_manager::USER_TYPE_REGULAR_SUPERVISED
999 : user_manager::USER_TYPE_REGULAR);
1000 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
1001 session_state_observer_list_,
1002 UserChangedSupervisedStatus(user));
1005 void UserManagerBase::UpdateLoginState() {
1006 if (!chromeos::LoginState::IsInitialized())
1007 return; // LoginState may not be initialized in tests.
1009 chromeos::LoginState::LoggedInState logged_in_state;
1010 logged_in_state = active_user_ ? chromeos::LoginState::LOGGED_IN_ACTIVE
1011 : chromeos::LoginState::LOGGED_IN_NONE;
1013 chromeos::LoginState::LoggedInUserType login_user_type;
1014 if (logged_in_state == chromeos::LoginState::LOGGED_IN_NONE)
1015 login_user_type = chromeos::LoginState::LOGGED_IN_USER_NONE;
1016 else if (is_current_user_owner_)
1017 login_user_type = chromeos::LoginState::LOGGED_IN_USER_OWNER;
1018 else if (active_user_->GetType() == USER_TYPE_GUEST)
1019 login_user_type = chromeos::LoginState::LOGGED_IN_USER_GUEST;
1020 else if (active_user_->GetType() == USER_TYPE_RETAIL_MODE)
1021 login_user_type = chromeos::LoginState::LOGGED_IN_USER_RETAIL_MODE;
1022 else if (active_user_->GetType() == USER_TYPE_PUBLIC_ACCOUNT)
1023 login_user_type = chromeos::LoginState::LOGGED_IN_USER_PUBLIC_ACCOUNT;
1024 else if (active_user_->GetType() == USER_TYPE_SUPERVISED)
1025 login_user_type = chromeos::LoginState::LOGGED_IN_USER_SUPERVISED;
1026 else if (active_user_->GetType() == USER_TYPE_KIOSK_APP)
1027 login_user_type = chromeos::LoginState::LOGGED_IN_USER_KIOSK_APP;
1028 else
1029 login_user_type = chromeos::LoginState::LOGGED_IN_USER_REGULAR;
1031 if (primary_user_) {
1032 chromeos::LoginState::Get()->SetLoggedInStateAndPrimaryUser(
1033 logged_in_state, login_user_type, primary_user_->username_hash());
1034 } else {
1035 chromeos::LoginState::Get()->SetLoggedInState(logged_in_state,
1036 login_user_type);
1040 void UserManagerBase::SetLRUUser(User* user) {
1041 GetLocalState()->SetString(kLastActiveUser, user->email());
1042 GetLocalState()->CommitPendingWrite();
1044 UserList::iterator it =
1045 std::find(lru_logged_in_users_.begin(), lru_logged_in_users_.end(), user);
1046 if (it != lru_logged_in_users_.end())
1047 lru_logged_in_users_.erase(it);
1048 lru_logged_in_users_.insert(lru_logged_in_users_.begin(), user);
1051 void UserManagerBase::SendGaiaUserLoginMetrics(const std::string& user_id) {
1052 // If this isn't the first time Chrome was run after the system booted,
1053 // assume that Chrome was restarted because a previous session ended.
1054 if (!CommandLine::ForCurrentProcess()->HasSwitch(
1055 chromeos::switches::kFirstExecAfterBoot)) {
1056 const std::string last_email =
1057 GetLocalState()->GetString(kLastLoggedInGaiaUser);
1058 const base::TimeDelta time_to_login =
1059 base::TimeTicks::Now() - manager_creation_time_;
1060 if (!last_email.empty() && user_id != last_email &&
1061 time_to_login.InSeconds() <= kLogoutToLoginDelayMaxSec) {
1062 UMA_HISTOGRAM_CUSTOM_COUNTS("UserManager.LogoutToLoginDelay",
1063 time_to_login.InSeconds(),
1065 kLogoutToLoginDelayMaxSec,
1066 50);
1071 void UserManagerBase::UpdateUserAccountLocale(const std::string& user_id,
1072 const std::string& locale) {
1073 scoped_ptr<std::string> resolved_locale(new std::string());
1074 if (!locale.empty() && locale != GetApplicationLocale()) {
1075 // base::Pased will NULL out |resolved_locale|, so cache the underlying ptr.
1076 std::string* raw_resolved_locale = resolved_locale.get();
1077 blocking_task_runner_->PostTaskAndReply(
1078 FROM_HERE,
1079 base::Bind(ResolveLocale,
1080 locale,
1081 base::Unretained(raw_resolved_locale)),
1082 base::Bind(&UserManagerBase::DoUpdateAccountLocale,
1083 weak_factory_.GetWeakPtr(),
1084 user_id,
1085 base::Passed(&resolved_locale)));
1086 } else {
1087 resolved_locale.reset(new std::string(locale));
1088 DoUpdateAccountLocale(user_id, resolved_locale.Pass());
1092 void UserManagerBase::DoUpdateAccountLocale(
1093 const std::string& user_id,
1094 scoped_ptr<std::string> resolved_locale) {
1095 User* user = FindUserAndModify(user_id);
1096 if (user && resolved_locale)
1097 user->SetAccountLocale(*resolved_locale);
1100 void UserManagerBase::DeleteUser(User* user) {
1101 const bool is_active_user = (user == active_user_);
1102 delete user;
1103 if (is_active_user)
1104 active_user_ = NULL;
1107 } // namespace user_manager