kMaxBlockSize -> kMaxHeaderBlockSize to avoid shadowing warning on VS2015
[chromium-blink-merge.git] / components / user_manager / user_manager_base.cc
blobd10f95622851350487a49be3bfba97f3710551f2
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 (IsKioskApp(user_id)) {
189 KioskAppLoggedIn(user_id);
190 } else if (IsDemoApp(user_id)) {
191 DemoAccountLoggedIn();
192 } else {
193 EnsureUsersLoaded();
195 if (user && user->GetType() == USER_TYPE_PUBLIC_ACCOUNT) {
196 PublicAccountUserLoggedIn(user);
197 } else if ((user && user->GetType() == USER_TYPE_SUPERVISED) ||
198 (!user &&
199 gaia::ExtractDomainName(user_id) ==
200 chromeos::login::kSupervisedUserDomain)) {
201 SupervisedUserLoggedIn(user_id);
202 } else if (browser_restart && IsPublicAccountMarkedForRemoval(user_id)) {
203 PublicAccountUserLoggedIn(User::CreatePublicAccountUser(user_id));
204 } else if (user_id != GetOwnerEmail() && !user &&
205 (AreEphemeralUsersEnabled() || browser_restart)) {
206 RegularUserLoggedInAsEphemeral(user_id);
207 } else {
208 RegularUserLoggedIn(user_id);
212 DCHECK(active_user_);
213 active_user_->set_is_logged_in(true);
214 active_user_->set_is_active(true);
215 active_user_->set_username_hash(username_hash);
217 // Place user who just signed in to the top of the logged in users.
218 logged_in_users_.insert(logged_in_users_.begin(), active_user_);
219 SetLRUUser(active_user_);
221 if (!primary_user_) {
222 primary_user_ = active_user_;
223 if (primary_user_->HasGaiaAccount())
224 SendGaiaUserLoginMetrics(user_id);
227 UMA_HISTOGRAM_ENUMERATION(
228 "UserManager.LoginUserType", active_user_->GetType(), NUM_USER_TYPES);
230 GetLocalState()->SetString(
231 kLastLoggedInGaiaUser, active_user_->HasGaiaAccount() ? user_id : "");
233 NotifyOnLogin();
234 PerformPostUserLoggedInActions(browser_restart);
237 void UserManagerBase::SwitchActiveUser(const std::string& user_id) {
238 User* user = FindUserAndModify(user_id);
239 if (!user) {
240 NOTREACHED() << "Switching to a non-existing user";
241 return;
243 if (user == active_user_) {
244 NOTREACHED() << "Switching to a user who is already active";
245 return;
247 if (!user->is_logged_in()) {
248 NOTREACHED() << "Switching to a user that is not logged in";
249 return;
251 if (!user->HasGaiaAccount()) {
252 NOTREACHED() <<
253 "Switching to a user without gaia account (non-regular one)";
254 return;
256 if (user->username_hash().empty()) {
257 NOTREACHED() << "Switching to a user that doesn't have username_hash set";
258 return;
261 DCHECK(active_user_);
262 active_user_->set_is_active(false);
263 user->set_is_active(true);
264 active_user_ = user;
266 // Move the user to the front.
267 SetLRUUser(active_user_);
269 NotifyActiveUserHashChanged(active_user_->username_hash());
270 NotifyActiveUserChanged(active_user_);
273 void UserManagerBase::SwitchToLastActiveUser() {
274 if (last_session_active_user_.empty())
275 return;
277 if (GetActiveUser()->email() != last_session_active_user_)
278 SwitchActiveUser(last_session_active_user_);
280 // Make sure that this function gets run only once.
281 last_session_active_user_.clear();
284 void UserManagerBase::SessionStarted() {
285 DCHECK(task_runner_->RunsTasksOnCurrentThread());
286 session_started_ = true;
288 UpdateLoginState();
289 session_manager::SessionManager::Get()->SetSessionState(
290 session_manager::SESSION_STATE_ACTIVE);
292 if (IsCurrentUserNew()) {
293 // Make sure that the new user's data is persisted to Local State.
294 GetLocalState()->CommitPendingWrite();
298 void UserManagerBase::RemoveUser(const std::string& user_id,
299 RemoveUserDelegate* delegate) {
300 DCHECK(task_runner_->RunsTasksOnCurrentThread());
302 if (!CanUserBeRemoved(FindUser(user_id)))
303 return;
305 RemoveUserInternal(user_id, delegate);
308 void UserManagerBase::RemoveUserInternal(const std::string& user_email,
309 RemoveUserDelegate* delegate) {
310 RemoveNonOwnerUserInternal(user_email, delegate);
313 void UserManagerBase::RemoveNonOwnerUserInternal(const std::string& user_email,
314 RemoveUserDelegate* delegate) {
315 if (delegate)
316 delegate->OnBeforeUserRemoved(user_email);
317 RemoveUserFromList(user_email);
318 cryptohome::AsyncMethodCaller::GetInstance()->AsyncRemove(
319 user_email, base::Bind(&OnRemoveUserComplete, user_email));
321 if (delegate)
322 delegate->OnUserRemoved(user_email);
325 void UserManagerBase::RemoveUserFromList(const std::string& user_id) {
326 DCHECK(task_runner_->RunsTasksOnCurrentThread());
327 RemoveNonCryptohomeData(user_id);
328 if (user_loading_stage_ == STAGE_LOADED) {
329 DeleteUser(RemoveRegularOrSupervisedUserFromList(user_id));
330 } else if (user_loading_stage_ == STAGE_LOADING) {
331 DCHECK(gaia::ExtractDomainName(user_id) ==
332 chromeos::login::kSupervisedUserDomain);
333 // Special case, removing partially-constructed supervised user during user
334 // list loading.
335 ListPrefUpdate users_update(GetLocalState(), kRegularUsers);
336 users_update->Remove(base::StringValue(user_id), NULL);
337 } else {
338 NOTREACHED() << "Users are not loaded yet.";
339 return;
342 // Make sure that new data is persisted to Local State.
343 GetLocalState()->CommitPendingWrite();
346 bool UserManagerBase::IsKnownUser(const std::string& user_id) const {
347 return FindUser(user_id) != NULL;
350 const User* UserManagerBase::FindUser(const std::string& user_id) const {
351 DCHECK(task_runner_->RunsTasksOnCurrentThread());
352 if (active_user_ && active_user_->email() == user_id)
353 return active_user_;
354 return FindUserInList(user_id);
357 User* UserManagerBase::FindUserAndModify(const std::string& user_id) {
358 DCHECK(task_runner_->RunsTasksOnCurrentThread());
359 if (active_user_ && active_user_->email() == user_id)
360 return active_user_;
361 return FindUserInListAndModify(user_id);
364 const User* UserManagerBase::GetLoggedInUser() const {
365 DCHECK(task_runner_->RunsTasksOnCurrentThread());
366 return active_user_;
369 User* UserManagerBase::GetLoggedInUser() {
370 DCHECK(task_runner_->RunsTasksOnCurrentThread());
371 return active_user_;
374 const User* UserManagerBase::GetActiveUser() const {
375 DCHECK(task_runner_->RunsTasksOnCurrentThread());
376 return active_user_;
379 User* UserManagerBase::GetActiveUser() {
380 DCHECK(task_runner_->RunsTasksOnCurrentThread());
381 return active_user_;
384 const User* UserManagerBase::GetPrimaryUser() const {
385 DCHECK(task_runner_->RunsTasksOnCurrentThread());
386 return primary_user_;
389 void UserManagerBase::SaveUserOAuthStatus(
390 const std::string& user_id,
391 User::OAuthTokenStatus oauth_token_status) {
392 DCHECK(task_runner_->RunsTasksOnCurrentThread());
394 DVLOG(1) << "Saving user OAuth token status in Local State";
395 User* user = FindUserAndModify(user_id);
396 if (user)
397 user->set_oauth_token_status(oauth_token_status);
399 // Do not update local state if data stored or cached outside the user's
400 // cryptohome is to be treated as ephemeral.
401 if (IsUserNonCryptohomeDataEphemeral(user_id))
402 return;
404 DictionaryPrefUpdate oauth_status_update(GetLocalState(),
405 kUserOAuthTokenStatus);
406 oauth_status_update->SetWithoutPathExpansion(
407 user_id,
408 new base::FundamentalValue(static_cast<int>(oauth_token_status)));
411 void UserManagerBase::SaveForceOnlineSignin(const std::string& user_id,
412 bool force_online_signin) {
413 DCHECK(task_runner_->RunsTasksOnCurrentThread());
415 // Do not update local state if data stored or cached outside the user's
416 // cryptohome is to be treated as ephemeral.
417 if (IsUserNonCryptohomeDataEphemeral(user_id))
418 return;
420 DictionaryPrefUpdate force_online_update(GetLocalState(),
421 kUserForceOnlineSignin);
422 force_online_update->SetBooleanWithoutPathExpansion(user_id,
423 force_online_signin);
426 void UserManagerBase::SaveUserDisplayName(const std::string& user_id,
427 const base::string16& display_name) {
428 DCHECK(task_runner_->RunsTasksOnCurrentThread());
430 if (User* user = FindUserAndModify(user_id)) {
431 user->set_display_name(display_name);
433 // Do not update local state if data stored or cached outside the user's
434 // cryptohome is to be treated as ephemeral.
435 if (!IsUserNonCryptohomeDataEphemeral(user_id)) {
436 DictionaryPrefUpdate display_name_update(GetLocalState(),
437 kUserDisplayName);
438 display_name_update->SetWithoutPathExpansion(
439 user_id, new base::StringValue(display_name));
444 base::string16 UserManagerBase::GetUserDisplayName(
445 const std::string& user_id) const {
446 const User* user = FindUser(user_id);
447 return user ? user->display_name() : base::string16();
450 void UserManagerBase::SaveUserDisplayEmail(const std::string& user_id,
451 const std::string& display_email) {
452 DCHECK(task_runner_->RunsTasksOnCurrentThread());
454 User* user = FindUserAndModify(user_id);
455 if (!user) {
456 LOG(ERROR) << "User not found: " << user_id;
457 return; // Ignore if there is no such user.
460 user->set_display_email(display_email);
462 // Do not update local state if data stored or cached outside the user's
463 // cryptohome is to be treated as ephemeral.
464 if (IsUserNonCryptohomeDataEphemeral(user_id))
465 return;
467 DictionaryPrefUpdate display_email_update(GetLocalState(), kUserDisplayEmail);
468 display_email_update->SetWithoutPathExpansion(
469 user_id, new base::StringValue(display_email));
472 std::string UserManagerBase::GetUserDisplayEmail(
473 const std::string& user_id) const {
474 const User* user = FindUser(user_id);
475 return user ? user->display_email() : user_id;
478 void UserManagerBase::SaveUserType(const std::string& user_id,
479 const UserType& user_type) {
480 DCHECK(task_runner_->RunsTasksOnCurrentThread());
482 User* user = FindUserAndModify(user_id);
483 if (!user) {
484 LOG(ERROR) << "User not found: " << user_id;
485 return; // Ignore if there is no such user.
488 // Do not update local state if data stored or cached outside the user's
489 // cryptohome is to be treated as ephemeral.
490 if (IsUserNonCryptohomeDataEphemeral(user_id))
491 return;
493 DictionaryPrefUpdate user_type_update(GetLocalState(), kUserType);
494 user_type_update->SetWithoutPathExpansion(
495 user_id, new base::FundamentalValue(static_cast<int>(user_type)));
496 GetLocalState()->CommitPendingWrite();
499 void UserManagerBase::UpdateUserAccountData(
500 const std::string& user_id,
501 const UserAccountData& account_data) {
502 DCHECK(task_runner_->RunsTasksOnCurrentThread());
504 SaveUserDisplayName(user_id, account_data.display_name());
506 if (User* user = FindUserAndModify(user_id)) {
507 base::string16 given_name = account_data.given_name();
508 user->set_given_name(given_name);
509 if (!IsUserNonCryptohomeDataEphemeral(user_id)) {
510 DictionaryPrefUpdate given_name_update(GetLocalState(), kUserGivenName);
511 given_name_update->SetWithoutPathExpansion(
512 user_id, new base::StringValue(given_name));
516 UpdateUserAccountLocale(user_id, account_data.locale());
519 // static
520 void UserManagerBase::ParseUserList(const base::ListValue& users_list,
521 const std::set<std::string>& existing_users,
522 std::vector<std::string>* users_vector,
523 std::set<std::string>* users_set) {
524 users_vector->clear();
525 users_set->clear();
526 for (size_t i = 0; i < users_list.GetSize(); ++i) {
527 std::string email;
528 if (!users_list.GetString(i, &email) || email.empty()) {
529 LOG(ERROR) << "Corrupt entry in user list at index " << i << ".";
530 continue;
532 if (existing_users.find(email) != existing_users.end() ||
533 !users_set->insert(email).second) {
534 LOG(ERROR) << "Duplicate user: " << email;
535 continue;
537 users_vector->push_back(email);
541 bool UserManagerBase::IsCurrentUserOwner() const {
542 DCHECK(task_runner_->RunsTasksOnCurrentThread());
543 base::AutoLock lk(is_current_user_owner_lock_);
544 return is_current_user_owner_;
547 void UserManagerBase::SetCurrentUserIsOwner(bool is_current_user_owner) {
548 DCHECK(task_runner_->RunsTasksOnCurrentThread());
550 base::AutoLock lk(is_current_user_owner_lock_);
551 is_current_user_owner_ = is_current_user_owner;
553 UpdateLoginState();
556 bool UserManagerBase::IsCurrentUserNew() const {
557 DCHECK(task_runner_->RunsTasksOnCurrentThread());
558 return is_current_user_new_;
561 bool UserManagerBase::IsCurrentUserNonCryptohomeDataEphemeral() const {
562 DCHECK(task_runner_->RunsTasksOnCurrentThread());
563 return IsUserLoggedIn() &&
564 IsUserNonCryptohomeDataEphemeral(GetLoggedInUser()->email());
567 bool UserManagerBase::CanCurrentUserLock() const {
568 DCHECK(task_runner_->RunsTasksOnCurrentThread());
569 return IsUserLoggedIn() && active_user_->can_lock();
572 bool UserManagerBase::IsUserLoggedIn() const {
573 DCHECK(task_runner_->RunsTasksOnCurrentThread());
574 return active_user_;
577 bool UserManagerBase::IsLoggedInAsUserWithGaiaAccount() const {
578 DCHECK(task_runner_->RunsTasksOnCurrentThread());
579 return IsUserLoggedIn() && active_user_->HasGaiaAccount();
582 bool UserManagerBase::IsLoggedInAsChildUser() const {
583 DCHECK(task_runner_->RunsTasksOnCurrentThread());
584 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_CHILD;
587 bool UserManagerBase::IsLoggedInAsPublicAccount() const {
588 DCHECK(task_runner_->RunsTasksOnCurrentThread());
589 return IsUserLoggedIn() &&
590 active_user_->GetType() == USER_TYPE_PUBLIC_ACCOUNT;
593 bool UserManagerBase::IsLoggedInAsGuest() const {
594 DCHECK(task_runner_->RunsTasksOnCurrentThread());
595 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_GUEST;
598 bool UserManagerBase::IsLoggedInAsSupervisedUser() const {
599 DCHECK(task_runner_->RunsTasksOnCurrentThread());
600 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_SUPERVISED;
603 bool UserManagerBase::IsLoggedInAsKioskApp() const {
604 DCHECK(task_runner_->RunsTasksOnCurrentThread());
605 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_KIOSK_APP;
608 bool UserManagerBase::IsLoggedInAsStub() const {
609 DCHECK(task_runner_->RunsTasksOnCurrentThread());
610 return IsUserLoggedIn() &&
611 active_user_->email() == chromeos::login::kStubUser;
614 bool UserManagerBase::IsSessionStarted() const {
615 DCHECK(task_runner_->RunsTasksOnCurrentThread());
616 return session_started_;
619 bool UserManagerBase::IsUserNonCryptohomeDataEphemeral(
620 const std::string& user_id) const {
621 // Data belonging to the guest and stub users is always ephemeral.
622 if (user_id == chromeos::login::kGuestUserName ||
623 user_id == chromeos::login::kStubUser) {
624 return true;
627 // Data belonging to the owner, anyone found on the user list and obsolete
628 // public accounts whose data has not been removed yet is not ephemeral.
629 if (user_id == GetOwnerEmail() || UserExistsInList(user_id) ||
630 IsPublicAccountMarkedForRemoval(user_id)) {
631 return false;
634 // Data belonging to the currently logged-in user is ephemeral when:
635 // a) The user logged into a regular gaia account while the ephemeral users
636 // policy was enabled.
637 // - or -
638 // b) The user logged into any other account type.
639 if (IsUserLoggedIn() && (user_id == GetLoggedInUser()->email()) &&
640 (is_current_user_ephemeral_regular_user_ ||
641 !IsLoggedInAsUserWithGaiaAccount())) {
642 return true;
645 // Data belonging to any other user is ephemeral when:
646 // a) Going through the regular login flow and the ephemeral users policy is
647 // enabled.
648 // - or -
649 // b) The browser is restarting after a crash.
650 return AreEphemeralUsersEnabled() ||
651 session_manager::SessionManager::HasBrowserRestarted();
654 void UserManagerBase::AddObserver(UserManager::Observer* obs) {
655 DCHECK(task_runner_->RunsTasksOnCurrentThread());
656 observer_list_.AddObserver(obs);
659 void UserManagerBase::RemoveObserver(UserManager::Observer* obs) {
660 DCHECK(task_runner_->RunsTasksOnCurrentThread());
661 observer_list_.RemoveObserver(obs);
664 void UserManagerBase::AddSessionStateObserver(
665 UserManager::UserSessionStateObserver* obs) {
666 DCHECK(task_runner_->RunsTasksOnCurrentThread());
667 session_state_observer_list_.AddObserver(obs);
670 void UserManagerBase::RemoveSessionStateObserver(
671 UserManager::UserSessionStateObserver* obs) {
672 DCHECK(task_runner_->RunsTasksOnCurrentThread());
673 session_state_observer_list_.RemoveObserver(obs);
676 void UserManagerBase::NotifyLocalStateChanged() {
677 DCHECK(task_runner_->RunsTasksOnCurrentThread());
678 FOR_EACH_OBSERVER(
679 UserManager::Observer, observer_list_, LocalStateChanged(this));
682 bool UserManagerBase::CanUserBeRemoved(const User* user) const {
683 // Only regular and supervised users are allowed to be manually removed.
684 if (!user || !(user->HasGaiaAccount() || user->IsSupervised()))
685 return false;
687 // Sanity check: we must not remove single user unless it's an enterprise
688 // device. This check may seem redundant at a first sight because
689 // this single user must be an owner and we perform special check later
690 // in order not to remove an owner. However due to non-instant nature of
691 // ownership assignment this later check may sometimes fail.
692 // See http://crosbug.com/12723
693 if (users_.size() < 2 && !IsEnterpriseManaged())
694 return false;
696 // Sanity check: do not allow any of the the logged in users to be removed.
697 for (UserList::const_iterator it = logged_in_users_.begin();
698 it != logged_in_users_.end();
699 ++it) {
700 if ((*it)->email() == user->email())
701 return false;
704 return true;
707 bool UserManagerBase::GetEphemeralUsersEnabled() const {
708 return ephemeral_users_enabled_;
711 void UserManagerBase::SetEphemeralUsersEnabled(bool enabled) {
712 ephemeral_users_enabled_ = enabled;
715 void UserManagerBase::SetIsCurrentUserNew(bool is_new) {
716 is_current_user_new_ = is_new;
719 void UserManagerBase::SetOwnerEmail(std::string owner_user_id) {
720 owner_email_ = owner_user_id;
723 const std::string& UserManagerBase::GetPendingUserSwitchID() const {
724 return pending_user_switch_;
727 void UserManagerBase::SetPendingUserSwitchID(std::string user_id) {
728 pending_user_switch_ = user_id;
731 void UserManagerBase::EnsureUsersLoaded() {
732 DCHECK(task_runner_->RunsTasksOnCurrentThread());
733 if (!GetLocalState())
734 return;
736 if (user_loading_stage_ != STAGE_NOT_LOADED)
737 return;
738 user_loading_stage_ = STAGE_LOADING;
740 PerformPreUserListLoadingActions();
742 PrefService* local_state = GetLocalState();
743 const base::ListValue* prefs_regular_users =
744 local_state->GetList(kRegularUsers);
746 const base::DictionaryValue* prefs_display_names =
747 local_state->GetDictionary(kUserDisplayName);
748 const base::DictionaryValue* prefs_given_names =
749 local_state->GetDictionary(kUserGivenName);
750 const base::DictionaryValue* prefs_display_emails =
751 local_state->GetDictionary(kUserDisplayEmail);
752 const base::DictionaryValue* prefs_user_types =
753 local_state->GetDictionary(kUserType);
755 // Load public sessions first.
756 std::set<std::string> public_sessions_set;
757 LoadPublicAccounts(&public_sessions_set);
759 // Load regular users and supervised users.
760 std::vector<std::string> regular_users;
761 std::set<std::string> regular_users_set;
762 ParseUserList(*prefs_regular_users,
763 public_sessions_set,
764 &regular_users,
765 &regular_users_set);
766 for (std::vector<std::string>::const_iterator it = regular_users.begin();
767 it != regular_users.end();
768 ++it) {
769 User* user = NULL;
770 const std::string domain = gaia::ExtractDomainName(*it);
771 if (domain == chromeos::login::kSupervisedUserDomain) {
772 user = User::CreateSupervisedUser(*it);
773 } else {
774 user = User::CreateRegularUser(*it);
775 int user_type;
776 if (prefs_user_types->GetIntegerWithoutPathExpansion(*it, &user_type) &&
777 user_type == USER_TYPE_CHILD) {
778 ChangeUserChildStatus(user, true /* is child */);
781 user->set_oauth_token_status(LoadUserOAuthStatus(*it));
782 user->set_force_online_signin(LoadForceOnlineSignin(*it));
783 users_.push_back(user);
785 base::string16 display_name;
786 if (prefs_display_names->GetStringWithoutPathExpansion(*it,
787 &display_name)) {
788 user->set_display_name(display_name);
791 base::string16 given_name;
792 if (prefs_given_names->GetStringWithoutPathExpansion(*it, &given_name)) {
793 user->set_given_name(given_name);
796 std::string display_email;
797 if (prefs_display_emails->GetStringWithoutPathExpansion(*it,
798 &display_email)) {
799 user->set_display_email(display_email);
803 user_loading_stage_ = STAGE_LOADED;
805 PerformPostUserListLoadingActions();
808 UserList& UserManagerBase::GetUsersAndModify() {
809 EnsureUsersLoaded();
810 return users_;
813 const User* UserManagerBase::FindUserInList(const std::string& user_id) const {
814 const UserList& users = GetUsers();
815 for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) {
816 if ((*it)->email() == user_id)
817 return *it;
819 return NULL;
822 bool UserManagerBase::UserExistsInList(const std::string& user_id) const {
823 const base::ListValue* user_list = GetLocalState()->GetList(kRegularUsers);
824 for (size_t i = 0; i < user_list->GetSize(); ++i) {
825 std::string email;
826 if (user_list->GetString(i, &email) && (user_id == email))
827 return true;
829 return false;
832 User* UserManagerBase::FindUserInListAndModify(const std::string& user_id) {
833 UserList& users = GetUsersAndModify();
834 for (UserList::iterator it = users.begin(); it != users.end(); ++it) {
835 if ((*it)->email() == user_id)
836 return *it;
838 return NULL;
841 void UserManagerBase::GuestUserLoggedIn() {
842 DCHECK(task_runner_->RunsTasksOnCurrentThread());
843 active_user_ = User::CreateGuestUser();
846 void UserManagerBase::AddUserRecord(User* user) {
847 // Add the user to the front of the user list.
848 ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers);
849 prefs_users_update->Insert(0, new base::StringValue(user->email()));
850 users_.insert(users_.begin(), user);
853 void UserManagerBase::RegularUserLoggedIn(const std::string& user_id) {
854 // Remove the user from the user list.
855 active_user_ = RemoveRegularOrSupervisedUserFromList(user_id);
857 // If the user was not found on the user list, create a new user.
858 SetIsCurrentUserNew(!active_user_);
859 if (IsCurrentUserNew()) {
860 active_user_ = User::CreateRegularUser(user_id);
861 active_user_->set_oauth_token_status(LoadUserOAuthStatus(user_id));
862 SaveUserDisplayName(active_user_->email(),
863 base::UTF8ToUTF16(active_user_->GetAccountName(true)));
866 AddUserRecord(active_user_);
868 // Make sure that new data is persisted to Local State.
869 GetLocalState()->CommitPendingWrite();
872 void UserManagerBase::RegularUserLoggedInAsEphemeral(
873 const std::string& user_id) {
874 DCHECK(task_runner_->RunsTasksOnCurrentThread());
875 SetIsCurrentUserNew(true);
876 is_current_user_ephemeral_regular_user_ = true;
877 active_user_ = User::CreateRegularUser(user_id);
880 void UserManagerBase::NotifyOnLogin() {
881 DCHECK(task_runner_->RunsTasksOnCurrentThread());
883 NotifyActiveUserHashChanged(active_user_->username_hash());
884 NotifyActiveUserChanged(active_user_);
885 UpdateLoginState();
888 User::OAuthTokenStatus UserManagerBase::LoadUserOAuthStatus(
889 const std::string& user_id) const {
890 DCHECK(task_runner_->RunsTasksOnCurrentThread());
892 const base::DictionaryValue* prefs_oauth_status =
893 GetLocalState()->GetDictionary(kUserOAuthTokenStatus);
894 int oauth_token_status = User::OAUTH_TOKEN_STATUS_UNKNOWN;
895 if (prefs_oauth_status &&
896 prefs_oauth_status->GetIntegerWithoutPathExpansion(user_id,
897 &oauth_token_status)) {
898 User::OAuthTokenStatus status =
899 static_cast<User::OAuthTokenStatus>(oauth_token_status);
900 HandleUserOAuthTokenStatusChange(user_id, status);
902 return status;
904 return User::OAUTH_TOKEN_STATUS_UNKNOWN;
907 bool UserManagerBase::LoadForceOnlineSignin(const std::string& user_id) const {
908 DCHECK(task_runner_->RunsTasksOnCurrentThread());
910 const base::DictionaryValue* prefs_force_online =
911 GetLocalState()->GetDictionary(kUserForceOnlineSignin);
912 bool force_online_signin = false;
913 if (prefs_force_online) {
914 prefs_force_online->GetBooleanWithoutPathExpansion(user_id,
915 &force_online_signin);
917 return force_online_signin;
920 void UserManagerBase::RemoveNonCryptohomeData(const std::string& user_id) {
921 PrefService* prefs = GetLocalState();
922 DictionaryPrefUpdate prefs_display_name_update(prefs, kUserDisplayName);
923 prefs_display_name_update->RemoveWithoutPathExpansion(user_id, NULL);
925 DictionaryPrefUpdate prefs_given_name_update(prefs, kUserGivenName);
926 prefs_given_name_update->RemoveWithoutPathExpansion(user_id, NULL);
928 DictionaryPrefUpdate prefs_display_email_update(prefs, kUserDisplayEmail);
929 prefs_display_email_update->RemoveWithoutPathExpansion(user_id, NULL);
931 DictionaryPrefUpdate prefs_oauth_update(prefs, kUserOAuthTokenStatus);
932 prefs_oauth_update->RemoveWithoutPathExpansion(user_id, NULL);
934 DictionaryPrefUpdate prefs_force_online_update(prefs, kUserForceOnlineSignin);
935 prefs_force_online_update->RemoveWithoutPathExpansion(user_id, NULL);
937 std::string last_active_user = GetLocalState()->GetString(kLastActiveUser);
938 if (user_id == last_active_user)
939 GetLocalState()->SetString(kLastActiveUser, std::string());
942 User* UserManagerBase::RemoveRegularOrSupervisedUserFromList(
943 const std::string& user_id) {
944 ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers);
945 prefs_users_update->Clear();
946 User* user = NULL;
947 for (UserList::iterator it = users_.begin(); it != users_.end();) {
948 const std::string user_email = (*it)->email();
949 if (user_email == user_id) {
950 user = *it;
951 it = users_.erase(it);
952 } else {
953 if ((*it)->HasGaiaAccount() || (*it)->IsSupervised())
954 prefs_users_update->Append(new base::StringValue(user_email));
955 ++it;
958 return user;
961 void UserManagerBase::NotifyActiveUserChanged(const User* active_user) {
962 DCHECK(task_runner_->RunsTasksOnCurrentThread());
963 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
964 session_state_observer_list_,
965 ActiveUserChanged(active_user));
968 void UserManagerBase::NotifyUserAddedToSession(const User* added_user,
969 bool user_switch_pending) {
970 DCHECK(task_runner_->RunsTasksOnCurrentThread());
971 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
972 session_state_observer_list_,
973 UserAddedToSession(added_user));
976 void UserManagerBase::NotifyActiveUserHashChanged(const std::string& hash) {
977 DCHECK(task_runner_->RunsTasksOnCurrentThread());
978 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
979 session_state_observer_list_,
980 ActiveUserHashChanged(hash));
983 void UserManagerBase::ChangeUserChildStatus(User* user, bool is_child) {
984 DCHECK(task_runner_->RunsTasksOnCurrentThread());
985 if (user->IsSupervised() == is_child)
986 return;
987 user->SetIsChild(is_child);
988 SaveUserType(user->email(), is_child ? user_manager::USER_TYPE_CHILD
989 : user_manager::USER_TYPE_REGULAR);
990 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
991 session_state_observer_list_,
992 UserChangedChildStatus(user));
995 void UserManagerBase::UpdateLoginState() {
996 if (!chromeos::LoginState::IsInitialized())
997 return; // LoginState may not be initialized in tests.
999 chromeos::LoginState::LoggedInState logged_in_state;
1000 logged_in_state = active_user_ ? chromeos::LoginState::LOGGED_IN_ACTIVE
1001 : chromeos::LoginState::LOGGED_IN_NONE;
1003 chromeos::LoginState::LoggedInUserType login_user_type;
1004 if (logged_in_state == chromeos::LoginState::LOGGED_IN_NONE)
1005 login_user_type = chromeos::LoginState::LOGGED_IN_USER_NONE;
1006 else if (is_current_user_owner_)
1007 login_user_type = chromeos::LoginState::LOGGED_IN_USER_OWNER;
1008 else if (active_user_->GetType() == USER_TYPE_GUEST)
1009 login_user_type = chromeos::LoginState::LOGGED_IN_USER_GUEST;
1010 else if (active_user_->GetType() == USER_TYPE_PUBLIC_ACCOUNT)
1011 login_user_type = chromeos::LoginState::LOGGED_IN_USER_PUBLIC_ACCOUNT;
1012 else if (active_user_->GetType() == USER_TYPE_SUPERVISED)
1013 login_user_type = chromeos::LoginState::LOGGED_IN_USER_SUPERVISED;
1014 else if (active_user_->GetType() == USER_TYPE_KIOSK_APP)
1015 login_user_type = chromeos::LoginState::LOGGED_IN_USER_KIOSK_APP;
1016 else
1017 login_user_type = chromeos::LoginState::LOGGED_IN_USER_REGULAR;
1019 if (primary_user_) {
1020 chromeos::LoginState::Get()->SetLoggedInStateAndPrimaryUser(
1021 logged_in_state, login_user_type, primary_user_->username_hash());
1022 } else {
1023 chromeos::LoginState::Get()->SetLoggedInState(logged_in_state,
1024 login_user_type);
1028 void UserManagerBase::SetLRUUser(User* user) {
1029 GetLocalState()->SetString(kLastActiveUser, user->email());
1030 GetLocalState()->CommitPendingWrite();
1032 UserList::iterator it =
1033 std::find(lru_logged_in_users_.begin(), lru_logged_in_users_.end(), user);
1034 if (it != lru_logged_in_users_.end())
1035 lru_logged_in_users_.erase(it);
1036 lru_logged_in_users_.insert(lru_logged_in_users_.begin(), user);
1039 void UserManagerBase::SendGaiaUserLoginMetrics(const std::string& user_id) {
1040 // If this isn't the first time Chrome was run after the system booted,
1041 // assume that Chrome was restarted because a previous session ended.
1042 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1043 chromeos::switches::kFirstExecAfterBoot)) {
1044 const std::string last_email =
1045 GetLocalState()->GetString(kLastLoggedInGaiaUser);
1046 const base::TimeDelta time_to_login =
1047 base::TimeTicks::Now() - manager_creation_time_;
1048 if (!last_email.empty() && user_id != last_email &&
1049 time_to_login.InSeconds() <= kLogoutToLoginDelayMaxSec) {
1050 UMA_HISTOGRAM_CUSTOM_COUNTS("UserManager.LogoutToLoginDelay",
1051 time_to_login.InSeconds(),
1053 kLogoutToLoginDelayMaxSec,
1054 50);
1059 void UserManagerBase::UpdateUserAccountLocale(const std::string& user_id,
1060 const std::string& locale) {
1061 scoped_ptr<std::string> resolved_locale(new std::string());
1062 if (!locale.empty() && locale != GetApplicationLocale()) {
1063 // base::Pased will NULL out |resolved_locale|, so cache the underlying ptr.
1064 std::string* raw_resolved_locale = resolved_locale.get();
1065 blocking_task_runner_->PostTaskAndReply(
1066 FROM_HERE,
1067 base::Bind(ResolveLocale,
1068 locale,
1069 base::Unretained(raw_resolved_locale)),
1070 base::Bind(&UserManagerBase::DoUpdateAccountLocale,
1071 weak_factory_.GetWeakPtr(),
1072 user_id,
1073 base::Passed(&resolved_locale)));
1074 } else {
1075 resolved_locale.reset(new std::string(locale));
1076 DoUpdateAccountLocale(user_id, resolved_locale.Pass());
1080 void UserManagerBase::DoUpdateAccountLocale(
1081 const std::string& user_id,
1082 scoped_ptr<std::string> resolved_locale) {
1083 User* user = FindUserAndModify(user_id);
1084 if (user && resolved_locale)
1085 user->SetAccountLocale(*resolved_locale);
1088 void UserManagerBase::DeleteUser(User* user) {
1089 const bool is_active_user = (user == active_user_);
1090 delete user;
1091 if (is_active_user)
1092 active_user_ = NULL;
1095 } // namespace user_manager