Revert of Fix doodle verification URL. (patchset #3 id:40001 of https://codereview...
[chromium-blink-merge.git] / components / user_manager / user_manager_base.cc
blob4bf1731d2953617029b9559e65f9956f495b5f6b
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 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,
71 bool success,
72 cryptohome::MountError return_code) {
73 // Log the error, but there's not much we can do.
74 if (!success) {
75 LOG(ERROR) << "Removal of cryptohome for " << user_email
76 << " failed, return code: " << return_code;
80 // Runs on SequencedWorkerPool thread. Passes resolved locale to UI thread.
81 void ResolveLocale(const std::string& raw_locale,
82 std::string* resolved_locale) {
83 ignore_result(l10n_util::CheckAndResolveLocale(raw_locale, resolved_locale));
86 } // namespace
88 // static
89 void UserManagerBase::RegisterPrefs(PrefRegistrySimple* registry) {
90 registry->RegisterListPref(kRegularUsers);
91 registry->RegisterStringPref(kLastLoggedInRegularUser, std::string());
92 registry->RegisterDictionaryPref(kUserDisplayName);
93 registry->RegisterDictionaryPref(kUserGivenName);
94 registry->RegisterDictionaryPref(kUserDisplayEmail);
95 registry->RegisterDictionaryPref(kUserOAuthTokenStatus);
96 registry->RegisterDictionaryPref(kUserForceOnlineSignin);
99 UserManagerBase::UserManagerBase(
100 scoped_refptr<base::TaskRunner> task_runner,
101 scoped_refptr<base::TaskRunner> blocking_task_runner)
102 : active_user_(NULL),
103 primary_user_(NULL),
104 user_loading_stage_(STAGE_NOT_LOADED),
105 session_started_(false),
106 is_current_user_owner_(false),
107 is_current_user_new_(false),
108 is_current_user_ephemeral_regular_user_(false),
109 ephemeral_users_enabled_(false),
110 manager_creation_time_(base::TimeTicks::Now()),
111 task_runner_(task_runner),
112 blocking_task_runner_(blocking_task_runner),
113 weak_factory_(this) {
114 UpdateLoginState();
117 UserManagerBase::~UserManagerBase() {
118 // Can't use STLDeleteElements because of the private destructor of User.
119 for (UserList::iterator it = users_.begin(); it != users_.end();
120 it = users_.erase(it)) {
121 DeleteUser(*it);
123 // These are pointers to the same User instances that were in users_ list.
124 logged_in_users_.clear();
125 lru_logged_in_users_.clear();
127 DeleteUser(active_user_);
130 void UserManagerBase::Shutdown() {
131 DCHECK(task_runner_->RunsTasksOnCurrentThread());
134 const UserList& UserManagerBase::GetUsers() const {
135 const_cast<UserManagerBase*>(this)->EnsureUsersLoaded();
136 return users_;
139 const UserList& UserManagerBase::GetLoggedInUsers() const {
140 return logged_in_users_;
143 const UserList& UserManagerBase::GetLRULoggedInUsers() const {
144 return lru_logged_in_users_;
147 const std::string& UserManagerBase::GetOwnerEmail() const {
148 return owner_email_;
151 void UserManagerBase::UserLoggedIn(const std::string& user_id,
152 const std::string& username_hash,
153 bool browser_restart) {
154 DCHECK(task_runner_->RunsTasksOnCurrentThread());
156 User* user = FindUserInListAndModify(user_id);
157 if (active_user_ && user) {
158 user->set_is_logged_in(true);
159 user->set_username_hash(username_hash);
160 logged_in_users_.push_back(user);
161 lru_logged_in_users_.push_back(user);
163 // Reset the new user flag if the user already exists.
164 SetIsCurrentUserNew(false);
165 NotifyUserAddedToSession(user, true /* user switch pending */);
167 return;
170 if (user_id == chromeos::login::kGuestUserName) {
171 GuestUserLoggedIn();
172 } else if (user_id == chromeos::login::kRetailModeUserName) {
173 RetailModeUserLoggedIn();
174 } else if (IsKioskApp(user_id)) {
175 KioskAppLoggedIn(user_id);
176 } else if (IsDemoApp(user_id)) {
177 DemoAccountLoggedIn();
178 } else {
179 EnsureUsersLoaded();
181 if (user && user->GetType() == USER_TYPE_PUBLIC_ACCOUNT) {
182 PublicAccountUserLoggedIn(user);
183 } else if ((user && user->GetType() == USER_TYPE_SUPERVISED) ||
184 (!user &&
185 gaia::ExtractDomainName(user_id) ==
186 chromeos::login::kSupervisedUserDomain)) {
187 SupervisedUserLoggedIn(user_id);
188 } else if (browser_restart && IsPublicAccountMarkedForRemoval(user_id)) {
189 PublicAccountUserLoggedIn(User::CreatePublicAccountUser(user_id));
190 } else if (user_id != GetOwnerEmail() && !user &&
191 (AreEphemeralUsersEnabled() || browser_restart)) {
192 RegularUserLoggedInAsEphemeral(user_id);
193 } else {
194 RegularUserLoggedIn(user_id);
198 DCHECK(active_user_);
199 active_user_->set_is_logged_in(true);
200 active_user_->set_is_active(true);
201 active_user_->set_username_hash(username_hash);
203 // Place user who just signed in to the top of the logged in users.
204 logged_in_users_.insert(logged_in_users_.begin(), active_user_);
205 SetLRUUser(active_user_);
207 if (!primary_user_) {
208 primary_user_ = active_user_;
209 if (primary_user_->GetType() == USER_TYPE_REGULAR)
210 SendRegularUserLoginMetrics(user_id);
213 UMA_HISTOGRAM_ENUMERATION(
214 "UserManager.LoginUserType", active_user_->GetType(), NUM_USER_TYPES);
216 GetLocalState()->SetString(
217 kLastLoggedInRegularUser,
218 (active_user_->GetType() == USER_TYPE_REGULAR) ? user_id : "");
220 NotifyOnLogin();
221 PerformPostUserLoggedInActions(browser_restart);
224 void UserManagerBase::SwitchActiveUser(const std::string& user_id) {
225 User* user = FindUserAndModify(user_id);
226 if (!user) {
227 NOTREACHED() << "Switching to a non-existing user";
228 return;
230 if (user == active_user_) {
231 NOTREACHED() << "Switching to a user who is already active";
232 return;
234 if (!user->is_logged_in()) {
235 NOTREACHED() << "Switching to a user that is not logged in";
236 return;
238 if (user->GetType() != USER_TYPE_REGULAR) {
239 NOTREACHED() << "Switching to a non-regular user";
240 return;
242 if (user->username_hash().empty()) {
243 NOTREACHED() << "Switching to a user that doesn't have username_hash set";
244 return;
247 DCHECK(active_user_);
248 active_user_->set_is_active(false);
249 user->set_is_active(true);
250 active_user_ = user;
252 // Move the user to the front.
253 SetLRUUser(active_user_);
255 NotifyActiveUserHashChanged(active_user_->username_hash());
256 NotifyActiveUserChanged(active_user_);
259 void UserManagerBase::SessionStarted() {
260 DCHECK(task_runner_->RunsTasksOnCurrentThread());
261 session_started_ = true;
263 UpdateLoginState();
264 session_manager::SessionManager::Get()->SetSessionState(
265 session_manager::SESSION_STATE_ACTIVE);
267 if (IsCurrentUserNew()) {
268 // Make sure that the new user's data is persisted to Local State.
269 GetLocalState()->CommitPendingWrite();
273 void UserManagerBase::RemoveUser(const std::string& user_id,
274 RemoveUserDelegate* delegate) {
275 DCHECK(task_runner_->RunsTasksOnCurrentThread());
277 if (!CanUserBeRemoved(FindUser(user_id)))
278 return;
280 RemoveUserInternal(user_id, delegate);
283 void UserManagerBase::RemoveUserInternal(const std::string& user_email,
284 RemoveUserDelegate* delegate) {
285 RemoveNonOwnerUserInternal(user_email, delegate);
288 void UserManagerBase::RemoveNonOwnerUserInternal(const std::string& user_email,
289 RemoveUserDelegate* delegate) {
290 if (delegate)
291 delegate->OnBeforeUserRemoved(user_email);
292 RemoveUserFromList(user_email);
293 cryptohome::AsyncMethodCaller::GetInstance()->AsyncRemove(
294 user_email, base::Bind(&OnRemoveUserComplete, user_email));
296 if (delegate)
297 delegate->OnUserRemoved(user_email);
300 void UserManagerBase::RemoveUserFromList(const std::string& user_id) {
301 DCHECK(task_runner_->RunsTasksOnCurrentThread());
302 RemoveNonCryptohomeData(user_id);
303 if (user_loading_stage_ == STAGE_LOADED) {
304 DeleteUser(RemoveRegularOrSupervisedUserFromList(user_id));
305 } else if (user_loading_stage_ == STAGE_LOADING) {
306 DCHECK(gaia::ExtractDomainName(user_id) ==
307 chromeos::login::kSupervisedUserDomain);
308 // Special case, removing partially-constructed supervised user during user
309 // list loading.
310 ListPrefUpdate users_update(GetLocalState(), kRegularUsers);
311 users_update->Remove(base::StringValue(user_id), NULL);
312 } else {
313 NOTREACHED() << "Users are not loaded yet.";
314 return;
317 // Make sure that new data is persisted to Local State.
318 GetLocalState()->CommitPendingWrite();
321 bool UserManagerBase::IsKnownUser(const std::string& user_id) const {
322 return FindUser(user_id) != NULL;
325 const User* UserManagerBase::FindUser(const std::string& user_id) const {
326 DCHECK(task_runner_->RunsTasksOnCurrentThread());
327 if (active_user_ && active_user_->email() == user_id)
328 return active_user_;
329 return FindUserInList(user_id);
332 User* UserManagerBase::FindUserAndModify(const std::string& user_id) {
333 DCHECK(task_runner_->RunsTasksOnCurrentThread());
334 if (active_user_ && active_user_->email() == user_id)
335 return active_user_;
336 return FindUserInListAndModify(user_id);
339 const User* UserManagerBase::GetLoggedInUser() const {
340 DCHECK(task_runner_->RunsTasksOnCurrentThread());
341 return active_user_;
344 User* UserManagerBase::GetLoggedInUser() {
345 DCHECK(task_runner_->RunsTasksOnCurrentThread());
346 return active_user_;
349 const User* UserManagerBase::GetActiveUser() const {
350 DCHECK(task_runner_->RunsTasksOnCurrentThread());
351 return active_user_;
354 User* UserManagerBase::GetActiveUser() {
355 DCHECK(task_runner_->RunsTasksOnCurrentThread());
356 return active_user_;
359 const User* UserManagerBase::GetPrimaryUser() const {
360 DCHECK(task_runner_->RunsTasksOnCurrentThread());
361 return primary_user_;
364 void UserManagerBase::SaveUserOAuthStatus(
365 const std::string& user_id,
366 User::OAuthTokenStatus oauth_token_status) {
367 DCHECK(task_runner_->RunsTasksOnCurrentThread());
369 DVLOG(1) << "Saving user OAuth token status in Local State";
370 User* user = FindUserAndModify(user_id);
371 if (user)
372 user->set_oauth_token_status(oauth_token_status);
374 // Do not update local state if data stored or cached outside the user's
375 // cryptohome is to be treated as ephemeral.
376 if (IsUserNonCryptohomeDataEphemeral(user_id))
377 return;
379 DictionaryPrefUpdate oauth_status_update(GetLocalState(),
380 kUserOAuthTokenStatus);
381 oauth_status_update->SetWithoutPathExpansion(
382 user_id,
383 new base::FundamentalValue(static_cast<int>(oauth_token_status)));
386 void UserManagerBase::SaveForceOnlineSignin(const std::string& user_id,
387 bool force_online_signin) {
388 DCHECK(task_runner_->RunsTasksOnCurrentThread());
390 // Do not update local state if data stored or cached outside the user's
391 // cryptohome is to be treated as ephemeral.
392 if (IsUserNonCryptohomeDataEphemeral(user_id))
393 return;
395 DictionaryPrefUpdate force_online_update(GetLocalState(),
396 kUserForceOnlineSignin);
397 force_online_update->SetBooleanWithoutPathExpansion(user_id,
398 force_online_signin);
401 void UserManagerBase::SaveUserDisplayName(const std::string& user_id,
402 const base::string16& display_name) {
403 DCHECK(task_runner_->RunsTasksOnCurrentThread());
405 if (User* user = FindUserAndModify(user_id)) {
406 user->set_display_name(display_name);
408 // Do not update local state if data stored or cached outside the user's
409 // cryptohome is to be treated as ephemeral.
410 if (!IsUserNonCryptohomeDataEphemeral(user_id)) {
411 DictionaryPrefUpdate display_name_update(GetLocalState(),
412 kUserDisplayName);
413 display_name_update->SetWithoutPathExpansion(
414 user_id, new base::StringValue(display_name));
419 base::string16 UserManagerBase::GetUserDisplayName(
420 const std::string& user_id) const {
421 const User* user = FindUser(user_id);
422 return user ? user->display_name() : base::string16();
425 void UserManagerBase::SaveUserDisplayEmail(const std::string& user_id,
426 const std::string& display_email) {
427 DCHECK(task_runner_->RunsTasksOnCurrentThread());
429 User* user = FindUserAndModify(user_id);
430 if (!user) {
431 LOG(ERROR) << "User not found: " << user_id;
432 return; // Ignore if there is no such user.
435 user->set_display_email(display_email);
437 // Do not update local state if data stored or cached outside the user's
438 // cryptohome is to be treated as ephemeral.
439 if (IsUserNonCryptohomeDataEphemeral(user_id))
440 return;
442 DictionaryPrefUpdate display_email_update(GetLocalState(), kUserDisplayEmail);
443 display_email_update->SetWithoutPathExpansion(
444 user_id, new base::StringValue(display_email));
447 std::string UserManagerBase::GetUserDisplayEmail(
448 const std::string& user_id) const {
449 const User* user = FindUser(user_id);
450 return user ? user->display_email() : user_id;
453 void UserManagerBase::UpdateUserAccountData(
454 const std::string& user_id,
455 const UserAccountData& account_data) {
456 DCHECK(task_runner_->RunsTasksOnCurrentThread());
458 SaveUserDisplayName(user_id, account_data.display_name());
460 if (User* user = FindUserAndModify(user_id)) {
461 base::string16 given_name = account_data.given_name();
462 user->set_given_name(given_name);
463 if (!IsUserNonCryptohomeDataEphemeral(user_id)) {
464 DictionaryPrefUpdate given_name_update(GetLocalState(), kUserGivenName);
465 given_name_update->SetWithoutPathExpansion(
466 user_id, new base::StringValue(given_name));
470 UpdateUserAccountLocale(user_id, account_data.locale());
473 // static
474 void UserManagerBase::ParseUserList(const base::ListValue& users_list,
475 const std::set<std::string>& existing_users,
476 std::vector<std::string>* users_vector,
477 std::set<std::string>* users_set) {
478 users_vector->clear();
479 users_set->clear();
480 for (size_t i = 0; i < users_list.GetSize(); ++i) {
481 std::string email;
482 if (!users_list.GetString(i, &email) || email.empty()) {
483 LOG(ERROR) << "Corrupt entry in user list at index " << i << ".";
484 continue;
486 if (existing_users.find(email) != existing_users.end() ||
487 !users_set->insert(email).second) {
488 LOG(ERROR) << "Duplicate user: " << email;
489 continue;
491 users_vector->push_back(email);
495 bool UserManagerBase::IsCurrentUserOwner() const {
496 DCHECK(task_runner_->RunsTasksOnCurrentThread());
497 base::AutoLock lk(is_current_user_owner_lock_);
498 return is_current_user_owner_;
501 void UserManagerBase::SetCurrentUserIsOwner(bool is_current_user_owner) {
502 DCHECK(task_runner_->RunsTasksOnCurrentThread());
504 base::AutoLock lk(is_current_user_owner_lock_);
505 is_current_user_owner_ = is_current_user_owner;
507 UpdateLoginState();
510 bool UserManagerBase::IsCurrentUserNew() const {
511 DCHECK(task_runner_->RunsTasksOnCurrentThread());
512 return is_current_user_new_;
515 bool UserManagerBase::IsCurrentUserNonCryptohomeDataEphemeral() const {
516 DCHECK(task_runner_->RunsTasksOnCurrentThread());
517 return IsUserLoggedIn() &&
518 IsUserNonCryptohomeDataEphemeral(GetLoggedInUser()->email());
521 bool UserManagerBase::CanCurrentUserLock() const {
522 DCHECK(task_runner_->RunsTasksOnCurrentThread());
523 return IsUserLoggedIn() && active_user_->can_lock();
526 bool UserManagerBase::IsUserLoggedIn() const {
527 DCHECK(task_runner_->RunsTasksOnCurrentThread());
528 return active_user_;
531 bool UserManagerBase::IsLoggedInAsRegularUser() const {
532 DCHECK(task_runner_->RunsTasksOnCurrentThread());
533 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_REGULAR;
536 bool UserManagerBase::IsLoggedInAsDemoUser() const {
537 DCHECK(task_runner_->RunsTasksOnCurrentThread());
538 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_RETAIL_MODE;
541 bool UserManagerBase::IsLoggedInAsPublicAccount() const {
542 DCHECK(task_runner_->RunsTasksOnCurrentThread());
543 return IsUserLoggedIn() &&
544 active_user_->GetType() == USER_TYPE_PUBLIC_ACCOUNT;
547 bool UserManagerBase::IsLoggedInAsGuest() const {
548 DCHECK(task_runner_->RunsTasksOnCurrentThread());
549 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_GUEST;
552 bool UserManagerBase::IsLoggedInAsSupervisedUser() const {
553 DCHECK(task_runner_->RunsTasksOnCurrentThread());
554 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_SUPERVISED;
557 bool UserManagerBase::IsLoggedInAsKioskApp() const {
558 DCHECK(task_runner_->RunsTasksOnCurrentThread());
559 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_KIOSK_APP;
562 bool UserManagerBase::IsLoggedInAsStub() const {
563 DCHECK(task_runner_->RunsTasksOnCurrentThread());
564 return IsUserLoggedIn() &&
565 active_user_->email() == chromeos::login::kStubUser;
568 bool UserManagerBase::IsSessionStarted() const {
569 DCHECK(task_runner_->RunsTasksOnCurrentThread());
570 return session_started_;
573 bool UserManagerBase::IsUserNonCryptohomeDataEphemeral(
574 const std::string& user_id) const {
575 // Data belonging to the guest, retail mode and stub users is always
576 // ephemeral.
577 if (user_id == chromeos::login::kGuestUserName ||
578 user_id == chromeos::login::kRetailModeUserName ||
579 user_id == chromeos::login::kStubUser) {
580 return true;
583 // Data belonging to the owner, anyone found on the user list and obsolete
584 // public accounts whose data has not been removed yet is not ephemeral.
585 if (user_id == GetOwnerEmail() || UserExistsInList(user_id) ||
586 IsPublicAccountMarkedForRemoval(user_id)) {
587 return false;
590 // Data belonging to the currently logged-in user is ephemeral when:
591 // a) The user logged into a regular account while the ephemeral users policy
592 // was enabled.
593 // - or -
594 // b) The user logged into any other account type.
595 if (IsUserLoggedIn() && (user_id == GetLoggedInUser()->email()) &&
596 (is_current_user_ephemeral_regular_user_ || !IsLoggedInAsRegularUser())) {
597 return true;
600 // Data belonging to any other user is ephemeral when:
601 // a) Going through the regular login flow and the ephemeral users policy is
602 // enabled.
603 // - or -
604 // b) The browser is restarting after a crash.
605 return AreEphemeralUsersEnabled() ||
606 session_manager::SessionManager::HasBrowserRestarted();
609 void UserManagerBase::AddObserver(UserManager::Observer* obs) {
610 DCHECK(task_runner_->RunsTasksOnCurrentThread());
611 observer_list_.AddObserver(obs);
614 void UserManagerBase::RemoveObserver(UserManager::Observer* obs) {
615 DCHECK(task_runner_->RunsTasksOnCurrentThread());
616 observer_list_.RemoveObserver(obs);
619 void UserManagerBase::AddSessionStateObserver(
620 UserManager::UserSessionStateObserver* obs) {
621 DCHECK(task_runner_->RunsTasksOnCurrentThread());
622 session_state_observer_list_.AddObserver(obs);
625 void UserManagerBase::RemoveSessionStateObserver(
626 UserManager::UserSessionStateObserver* obs) {
627 DCHECK(task_runner_->RunsTasksOnCurrentThread());
628 session_state_observer_list_.RemoveObserver(obs);
631 void UserManagerBase::NotifyLocalStateChanged() {
632 DCHECK(task_runner_->RunsTasksOnCurrentThread());
633 FOR_EACH_OBSERVER(
634 UserManager::Observer, observer_list_, LocalStateChanged(this));
637 void UserManagerBase::ForceUpdateState() {
638 UpdateLoginState();
641 bool UserManagerBase::CanUserBeRemoved(const User* user) const {
642 // Only regular and supervised users are allowed to be manually removed.
643 if (!user || (user->GetType() != USER_TYPE_REGULAR &&
644 user->GetType() != USER_TYPE_SUPERVISED)) {
645 return false;
648 // Sanity check: we must not remove single user unless it's an enterprise
649 // device. This check may seem redundant at a first sight because
650 // this single user must be an owner and we perform special check later
651 // in order not to remove an owner. However due to non-instant nature of
652 // ownership assignment this later check may sometimes fail.
653 // See http://crosbug.com/12723
654 if (users_.size() < 2 && !IsEnterpriseManaged())
655 return false;
657 // Sanity check: do not allow any of the the logged in users to be removed.
658 for (UserList::const_iterator it = logged_in_users_.begin();
659 it != logged_in_users_.end();
660 ++it) {
661 if ((*it)->email() == user->email())
662 return false;
665 return true;
668 bool UserManagerBase::GetEphemeralUsersEnabled() const {
669 return ephemeral_users_enabled_;
672 void UserManagerBase::SetEphemeralUsersEnabled(bool enabled) {
673 ephemeral_users_enabled_ = enabled;
676 void UserManagerBase::SetIsCurrentUserNew(bool is_new) {
677 is_current_user_new_ = is_new;
680 void UserManagerBase::SetOwnerEmail(std::string owner_user_id) {
681 owner_email_ = owner_user_id;
684 const std::string& UserManagerBase::GetPendingUserSwitchID() const {
685 return pending_user_switch_;
688 void UserManagerBase::SetPendingUserSwitchID(std::string user_id) {
689 pending_user_switch_ = user_id;
692 void UserManagerBase::EnsureUsersLoaded() {
693 DCHECK(task_runner_->RunsTasksOnCurrentThread());
694 if (!GetLocalState())
695 return;
697 if (user_loading_stage_ != STAGE_NOT_LOADED)
698 return;
699 user_loading_stage_ = STAGE_LOADING;
701 PerformPreUserListLoadingActions();
703 PrefService* local_state = GetLocalState();
704 const base::ListValue* prefs_regular_users =
705 local_state->GetList(kRegularUsers);
707 const base::DictionaryValue* prefs_display_names =
708 local_state->GetDictionary(kUserDisplayName);
709 const base::DictionaryValue* prefs_given_names =
710 local_state->GetDictionary(kUserGivenName);
711 const base::DictionaryValue* prefs_display_emails =
712 local_state->GetDictionary(kUserDisplayEmail);
714 // Load public sessions first.
715 std::set<std::string> public_sessions_set;
716 LoadPublicAccounts(&public_sessions_set);
718 // Load regular users and supervised users.
719 std::vector<std::string> regular_users;
720 std::set<std::string> regular_users_set;
721 ParseUserList(*prefs_regular_users,
722 public_sessions_set,
723 &regular_users,
724 &regular_users_set);
725 for (std::vector<std::string>::const_iterator it = regular_users.begin();
726 it != regular_users.end();
727 ++it) {
728 User* user = NULL;
729 const std::string domain = gaia::ExtractDomainName(*it);
730 if (domain == chromeos::login::kSupervisedUserDomain)
731 user = User::CreateSupervisedUser(*it);
732 else
733 user = User::CreateRegularUser(*it);
734 user->set_oauth_token_status(LoadUserOAuthStatus(*it));
735 user->set_force_online_signin(LoadForceOnlineSignin(*it));
736 users_.push_back(user);
738 base::string16 display_name;
739 if (prefs_display_names->GetStringWithoutPathExpansion(*it,
740 &display_name)) {
741 user->set_display_name(display_name);
744 base::string16 given_name;
745 if (prefs_given_names->GetStringWithoutPathExpansion(*it, &given_name)) {
746 user->set_given_name(given_name);
749 std::string display_email;
750 if (prefs_display_emails->GetStringWithoutPathExpansion(*it,
751 &display_email)) {
752 user->set_display_email(display_email);
756 user_loading_stage_ = STAGE_LOADED;
758 PerformPostUserListLoadingActions();
761 UserList& UserManagerBase::GetUsersAndModify() {
762 EnsureUsersLoaded();
763 return users_;
766 const User* UserManagerBase::FindUserInList(const std::string& user_id) const {
767 const UserList& users = GetUsers();
768 for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) {
769 if ((*it)->email() == user_id)
770 return *it;
772 return NULL;
775 const bool UserManagerBase::UserExistsInList(const std::string& user_id) const {
776 const base::ListValue* user_list = GetLocalState()->GetList(kRegularUsers);
777 for (size_t i = 0; i < user_list->GetSize(); ++i) {
778 std::string email;
779 if (user_list->GetString(i, &email) && (user_id == email))
780 return true;
782 return false;
785 User* UserManagerBase::FindUserInListAndModify(const std::string& user_id) {
786 UserList& users = GetUsersAndModify();
787 for (UserList::iterator it = users.begin(); it != users.end(); ++it) {
788 if ((*it)->email() == user_id)
789 return *it;
791 return NULL;
794 void UserManagerBase::GuestUserLoggedIn() {
795 DCHECK(task_runner_->RunsTasksOnCurrentThread());
796 active_user_ = User::CreateGuestUser();
799 void UserManagerBase::AddUserRecord(User* user) {
800 // Add the user to the front of the user list.
801 ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers);
802 prefs_users_update->Insert(0, new base::StringValue(user->email()));
803 users_.insert(users_.begin(), user);
806 void UserManagerBase::RegularUserLoggedIn(const std::string& user_id) {
807 // Remove the user from the user list.
808 active_user_ = RemoveRegularOrSupervisedUserFromList(user_id);
810 // If the user was not found on the user list, create a new user.
811 SetIsCurrentUserNew(!active_user_);
812 if (IsCurrentUserNew()) {
813 active_user_ = User::CreateRegularUser(user_id);
814 active_user_->set_oauth_token_status(LoadUserOAuthStatus(user_id));
815 SaveUserDisplayName(active_user_->email(),
816 base::UTF8ToUTF16(active_user_->GetAccountName(true)));
819 AddUserRecord(active_user_);
821 // Make sure that new data is persisted to Local State.
822 GetLocalState()->CommitPendingWrite();
825 void UserManagerBase::RegularUserLoggedInAsEphemeral(
826 const std::string& user_id) {
827 DCHECK(task_runner_->RunsTasksOnCurrentThread());
828 SetIsCurrentUserNew(true);
829 is_current_user_ephemeral_regular_user_ = true;
830 active_user_ = User::CreateRegularUser(user_id);
833 void UserManagerBase::NotifyOnLogin() {
834 DCHECK(task_runner_->RunsTasksOnCurrentThread());
836 NotifyActiveUserHashChanged(active_user_->username_hash());
837 NotifyActiveUserChanged(active_user_);
838 UpdateLoginState();
841 User::OAuthTokenStatus UserManagerBase::LoadUserOAuthStatus(
842 const std::string& user_id) const {
843 DCHECK(task_runner_->RunsTasksOnCurrentThread());
845 const base::DictionaryValue* prefs_oauth_status =
846 GetLocalState()->GetDictionary(kUserOAuthTokenStatus);
847 int oauth_token_status = User::OAUTH_TOKEN_STATUS_UNKNOWN;
848 if (prefs_oauth_status &&
849 prefs_oauth_status->GetIntegerWithoutPathExpansion(user_id,
850 &oauth_token_status)) {
851 User::OAuthTokenStatus status =
852 static_cast<User::OAuthTokenStatus>(oauth_token_status);
853 HandleUserOAuthTokenStatusChange(user_id, status);
855 return status;
857 return User::OAUTH_TOKEN_STATUS_UNKNOWN;
860 bool UserManagerBase::LoadForceOnlineSignin(const std::string& user_id) const {
861 DCHECK(task_runner_->RunsTasksOnCurrentThread());
863 const base::DictionaryValue* prefs_force_online =
864 GetLocalState()->GetDictionary(kUserForceOnlineSignin);
865 bool force_online_signin = false;
866 if (prefs_force_online) {
867 prefs_force_online->GetBooleanWithoutPathExpansion(user_id,
868 &force_online_signin);
870 return force_online_signin;
873 void UserManagerBase::RemoveNonCryptohomeData(const std::string& user_id) {
874 PrefService* prefs = GetLocalState();
875 DictionaryPrefUpdate prefs_display_name_update(prefs, kUserDisplayName);
876 prefs_display_name_update->RemoveWithoutPathExpansion(user_id, NULL);
878 DictionaryPrefUpdate prefs_given_name_update(prefs, kUserGivenName);
879 prefs_given_name_update->RemoveWithoutPathExpansion(user_id, NULL);
881 DictionaryPrefUpdate prefs_display_email_update(prefs, kUserDisplayEmail);
882 prefs_display_email_update->RemoveWithoutPathExpansion(user_id, NULL);
884 DictionaryPrefUpdate prefs_oauth_update(prefs, kUserOAuthTokenStatus);
885 prefs_oauth_update->RemoveWithoutPathExpansion(user_id, NULL);
887 DictionaryPrefUpdate prefs_force_online_update(prefs, kUserForceOnlineSignin);
888 prefs_force_online_update->RemoveWithoutPathExpansion(user_id, NULL);
891 User* UserManagerBase::RemoveRegularOrSupervisedUserFromList(
892 const std::string& user_id) {
893 ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers);
894 prefs_users_update->Clear();
895 User* user = NULL;
896 for (UserList::iterator it = users_.begin(); it != users_.end();) {
897 const std::string user_email = (*it)->email();
898 if (user_email == user_id) {
899 user = *it;
900 it = users_.erase(it);
901 } else {
902 if ((*it)->GetType() == USER_TYPE_REGULAR ||
903 (*it)->GetType() == USER_TYPE_SUPERVISED) {
904 prefs_users_update->Append(new base::StringValue(user_email));
906 ++it;
909 return user;
912 void UserManagerBase::NotifyActiveUserChanged(const User* active_user) {
913 DCHECK(task_runner_->RunsTasksOnCurrentThread());
914 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
915 session_state_observer_list_,
916 ActiveUserChanged(active_user));
919 void UserManagerBase::NotifyUserAddedToSession(const User* added_user,
920 bool user_switch_pending) {
921 DCHECK(task_runner_->RunsTasksOnCurrentThread());
922 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
923 session_state_observer_list_,
924 UserAddedToSession(added_user));
927 void UserManagerBase::NotifyActiveUserHashChanged(const std::string& hash) {
928 DCHECK(task_runner_->RunsTasksOnCurrentThread());
929 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
930 session_state_observer_list_,
931 ActiveUserHashChanged(hash));
934 void UserManagerBase::UpdateLoginState() {
935 if (!chromeos::LoginState::IsInitialized())
936 return; // LoginState may not be intialized in tests.
938 chromeos::LoginState::LoggedInState logged_in_state;
939 logged_in_state = active_user_ ? chromeos::LoginState::LOGGED_IN_ACTIVE
940 : chromeos::LoginState::LOGGED_IN_NONE;
942 chromeos::LoginState::LoggedInUserType login_user_type;
943 if (logged_in_state == chromeos::LoginState::LOGGED_IN_NONE)
944 login_user_type = chromeos::LoginState::LOGGED_IN_USER_NONE;
945 else if (is_current_user_owner_)
946 login_user_type = chromeos::LoginState::LOGGED_IN_USER_OWNER;
947 else if (active_user_->GetType() == USER_TYPE_GUEST)
948 login_user_type = chromeos::LoginState::LOGGED_IN_USER_GUEST;
949 else if (active_user_->GetType() == USER_TYPE_RETAIL_MODE)
950 login_user_type = chromeos::LoginState::LOGGED_IN_USER_RETAIL_MODE;
951 else if (active_user_->GetType() == USER_TYPE_PUBLIC_ACCOUNT)
952 login_user_type = chromeos::LoginState::LOGGED_IN_USER_PUBLIC_ACCOUNT;
953 else if (active_user_->GetType() == USER_TYPE_SUPERVISED)
954 login_user_type = chromeos::LoginState::LOGGED_IN_USER_SUPERVISED;
955 else if (active_user_->GetType() == USER_TYPE_KIOSK_APP)
956 login_user_type = chromeos::LoginState::LOGGED_IN_USER_KIOSK_APP;
957 else
958 login_user_type = chromeos::LoginState::LOGGED_IN_USER_REGULAR;
960 if (primary_user_) {
961 chromeos::LoginState::Get()->SetLoggedInStateAndPrimaryUser(
962 logged_in_state, login_user_type, primary_user_->username_hash());
963 } else {
964 chromeos::LoginState::Get()->SetLoggedInState(logged_in_state,
965 login_user_type);
969 void UserManagerBase::SetLRUUser(User* user) {
970 UserList::iterator it =
971 std::find(lru_logged_in_users_.begin(), lru_logged_in_users_.end(), user);
972 if (it != lru_logged_in_users_.end())
973 lru_logged_in_users_.erase(it);
974 lru_logged_in_users_.insert(lru_logged_in_users_.begin(), user);
977 void UserManagerBase::SendRegularUserLoginMetrics(const std::string& user_id) {
978 // If this isn't the first time Chrome was run after the system booted,
979 // assume that Chrome was restarted because a previous session ended.
980 if (!CommandLine::ForCurrentProcess()->HasSwitch(
981 chromeos::switches::kFirstExecAfterBoot)) {
982 const std::string last_email =
983 GetLocalState()->GetString(kLastLoggedInRegularUser);
984 const base::TimeDelta time_to_login =
985 base::TimeTicks::Now() - manager_creation_time_;
986 if (!last_email.empty() && user_id != last_email &&
987 time_to_login.InSeconds() <= kLogoutToLoginDelayMaxSec) {
988 UMA_HISTOGRAM_CUSTOM_COUNTS("UserManager.LogoutToLoginDelay",
989 time_to_login.InSeconds(),
991 kLogoutToLoginDelayMaxSec,
992 50);
997 void UserManagerBase::UpdateUserAccountLocale(const std::string& user_id,
998 const std::string& locale) {
999 scoped_ptr<std::string> resolved_locale(new std::string());
1000 if (!locale.empty() && locale != GetApplicationLocale()) {
1001 // base::Pased will NULL out |resolved_locale|, so cache the underlying ptr.
1002 std::string* raw_resolved_locale = resolved_locale.get();
1003 blocking_task_runner_->PostTaskAndReply(
1004 FROM_HERE,
1005 base::Bind(ResolveLocale,
1006 locale,
1007 base::Unretained(raw_resolved_locale)),
1008 base::Bind(&UserManagerBase::DoUpdateAccountLocale,
1009 weak_factory_.GetWeakPtr(),
1010 user_id,
1011 base::Passed(&resolved_locale)));
1012 } else {
1013 resolved_locale.reset(new std::string(locale));
1014 DoUpdateAccountLocale(user_id, resolved_locale.Pass());
1018 void UserManagerBase::DoUpdateAccountLocale(
1019 const std::string& user_id,
1020 scoped_ptr<std::string> resolved_locale) {
1021 User* user = FindUserAndModify(user_id);
1022 if (user && resolved_locale)
1023 user->SetAccountLocale(*resolved_locale);
1026 void UserManagerBase::DeleteUser(User* user) {
1027 const bool is_active_user = (user == active_user_);
1028 delete user;
1029 if (is_active_user)
1030 active_user_ = NULL;
1033 } // namespace user_manager