Add testing/scripts/OWNERS
[chromium-blink-merge.git] / components / user_manager / user_manager_base.cc
blob5fa2dd4dd51e46cb3b0d08d170d5313465556f9a
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 // A string pref containing the ID of the last active user.
66 // In case of browser crash, this pref will be used to set active user after
67 // session restore.
68 const char kLastActiveUser[] = "LastActiveUser";
70 // Upper bound for a histogram metric reporting the amount of time between
71 // one regular user logging out and a different regular user logging in.
72 const int kLogoutToLoginDelayMaxSec = 1800;
74 // Callback that is called after user removal is complete.
75 void OnRemoveUserComplete(const std::string& user_email,
76 bool success,
77 cryptohome::MountError return_code) {
78 // Log the error, but there's not much we can do.
79 if (!success) {
80 LOG(ERROR) << "Removal of cryptohome for " << user_email
81 << " failed, return code: " << return_code;
85 // Runs on SequencedWorkerPool thread. Passes resolved locale to UI thread.
86 void ResolveLocale(const std::string& raw_locale,
87 std::string* resolved_locale) {
88 ignore_result(l10n_util::CheckAndResolveLocale(raw_locale, resolved_locale));
91 } // namespace
93 // static
94 void UserManagerBase::RegisterPrefs(PrefRegistrySimple* registry) {
95 registry->RegisterListPref(kRegularUsers);
96 registry->RegisterStringPref(kLastLoggedInRegularUser, std::string());
97 registry->RegisterDictionaryPref(kUserDisplayName);
98 registry->RegisterDictionaryPref(kUserGivenName);
99 registry->RegisterDictionaryPref(kUserDisplayEmail);
100 registry->RegisterDictionaryPref(kUserOAuthTokenStatus);
101 registry->RegisterDictionaryPref(kUserForceOnlineSignin);
102 registry->RegisterStringPref(kLastActiveUser, std::string());
105 UserManagerBase::UserManagerBase(
106 scoped_refptr<base::TaskRunner> task_runner,
107 scoped_refptr<base::TaskRunner> blocking_task_runner)
108 : active_user_(NULL),
109 primary_user_(NULL),
110 user_loading_stage_(STAGE_NOT_LOADED),
111 session_started_(false),
112 is_current_user_owner_(false),
113 is_current_user_new_(false),
114 is_current_user_ephemeral_regular_user_(false),
115 ephemeral_users_enabled_(false),
116 manager_creation_time_(base::TimeTicks::Now()),
117 last_session_active_user_initialized_(false),
118 task_runner_(task_runner),
119 blocking_task_runner_(blocking_task_runner),
120 weak_factory_(this) {
121 UpdateLoginState();
124 UserManagerBase::~UserManagerBase() {
125 // Can't use STLDeleteElements because of the private destructor of User.
126 for (UserList::iterator it = users_.begin(); it != users_.end();
127 it = users_.erase(it)) {
128 DeleteUser(*it);
130 // These are pointers to the same User instances that were in users_ list.
131 logged_in_users_.clear();
132 lru_logged_in_users_.clear();
134 DeleteUser(active_user_);
137 void UserManagerBase::Shutdown() {
138 DCHECK(task_runner_->RunsTasksOnCurrentThread());
141 const UserList& UserManagerBase::GetUsers() const {
142 const_cast<UserManagerBase*>(this)->EnsureUsersLoaded();
143 return users_;
146 const UserList& UserManagerBase::GetLoggedInUsers() const {
147 return logged_in_users_;
150 const UserList& UserManagerBase::GetLRULoggedInUsers() const {
151 return lru_logged_in_users_;
154 const std::string& UserManagerBase::GetOwnerEmail() const {
155 return owner_email_;
158 void UserManagerBase::UserLoggedIn(const std::string& user_id,
159 const std::string& username_hash,
160 bool browser_restart) {
161 DCHECK(task_runner_->RunsTasksOnCurrentThread());
163 if (!last_session_active_user_initialized_) {
164 last_session_active_user_ = GetLocalState()->GetString(kLastActiveUser);
165 last_session_active_user_initialized_ = true;
168 User* user = FindUserInListAndModify(user_id);
169 if (active_user_ && user) {
170 user->set_is_logged_in(true);
171 user->set_username_hash(username_hash);
172 logged_in_users_.push_back(user);
173 lru_logged_in_users_.push_back(user);
175 // Reset the new user flag if the user already exists.
176 SetIsCurrentUserNew(false);
177 NotifyUserAddedToSession(user, true /* user switch pending */);
179 return;
182 if (user_id == chromeos::login::kGuestUserName) {
183 GuestUserLoggedIn();
184 } else if (user_id == chromeos::login::kRetailModeUserName) {
185 RetailModeUserLoggedIn();
186 } else if (IsKioskApp(user_id)) {
187 KioskAppLoggedIn(user_id);
188 } else if (IsDemoApp(user_id)) {
189 DemoAccountLoggedIn();
190 } else {
191 EnsureUsersLoaded();
193 if (user && user->GetType() == USER_TYPE_PUBLIC_ACCOUNT) {
194 PublicAccountUserLoggedIn(user);
195 } else if ((user && user->GetType() == USER_TYPE_SUPERVISED) ||
196 (!user &&
197 gaia::ExtractDomainName(user_id) ==
198 chromeos::login::kSupervisedUserDomain)) {
199 SupervisedUserLoggedIn(user_id);
200 } else if (browser_restart && IsPublicAccountMarkedForRemoval(user_id)) {
201 PublicAccountUserLoggedIn(User::CreatePublicAccountUser(user_id));
202 } else if (user_id != GetOwnerEmail() && !user &&
203 (AreEphemeralUsersEnabled() || browser_restart)) {
204 RegularUserLoggedInAsEphemeral(user_id);
205 } else {
206 RegularUserLoggedIn(user_id);
210 DCHECK(active_user_);
211 active_user_->set_is_logged_in(true);
212 active_user_->set_is_active(true);
213 active_user_->set_username_hash(username_hash);
215 // Place user who just signed in to the top of the logged in users.
216 logged_in_users_.insert(logged_in_users_.begin(), active_user_);
217 SetLRUUser(active_user_);
219 if (!primary_user_) {
220 primary_user_ = active_user_;
221 if (primary_user_->GetType() == USER_TYPE_REGULAR)
222 SendRegularUserLoginMetrics(user_id);
225 UMA_HISTOGRAM_ENUMERATION(
226 "UserManager.LoginUserType", active_user_->GetType(), NUM_USER_TYPES);
228 GetLocalState()->SetString(
229 kLastLoggedInRegularUser,
230 (active_user_->GetType() == USER_TYPE_REGULAR) ? user_id : "");
232 NotifyOnLogin();
233 PerformPostUserLoggedInActions(browser_restart);
236 void UserManagerBase::SwitchActiveUser(const std::string& user_id) {
237 User* user = FindUserAndModify(user_id);
238 if (!user) {
239 NOTREACHED() << "Switching to a non-existing user";
240 return;
242 if (user == active_user_) {
243 NOTREACHED() << "Switching to a user who is already active";
244 return;
246 if (!user->is_logged_in()) {
247 NOTREACHED() << "Switching to a user that is not logged in";
248 return;
250 if (user->GetType() != USER_TYPE_REGULAR) {
251 NOTREACHED() << "Switching to a non-regular user";
252 return;
254 if (user->username_hash().empty()) {
255 NOTREACHED() << "Switching to a user that doesn't have username_hash set";
256 return;
259 DCHECK(active_user_);
260 active_user_->set_is_active(false);
261 user->set_is_active(true);
262 active_user_ = user;
264 // Move the user to the front.
265 SetLRUUser(active_user_);
267 NotifyActiveUserHashChanged(active_user_->username_hash());
268 NotifyActiveUserChanged(active_user_);
271 void UserManagerBase::SwitchToLastActiveUser() {
272 if (last_session_active_user_.empty())
273 return;
275 if (GetActiveUser()->email() != last_session_active_user_)
276 SwitchActiveUser(last_session_active_user_);
278 // Make sure that this function gets run only once.
279 last_session_active_user_.clear();
282 void UserManagerBase::SessionStarted() {
283 DCHECK(task_runner_->RunsTasksOnCurrentThread());
284 session_started_ = true;
286 UpdateLoginState();
287 session_manager::SessionManager::Get()->SetSessionState(
288 session_manager::SESSION_STATE_ACTIVE);
290 if (IsCurrentUserNew()) {
291 // Make sure that the new user's data is persisted to Local State.
292 GetLocalState()->CommitPendingWrite();
296 void UserManagerBase::RemoveUser(const std::string& user_id,
297 RemoveUserDelegate* delegate) {
298 DCHECK(task_runner_->RunsTasksOnCurrentThread());
300 if (!CanUserBeRemoved(FindUser(user_id)))
301 return;
303 RemoveUserInternal(user_id, delegate);
306 void UserManagerBase::RemoveUserInternal(const std::string& user_email,
307 RemoveUserDelegate* delegate) {
308 RemoveNonOwnerUserInternal(user_email, delegate);
311 void UserManagerBase::RemoveNonOwnerUserInternal(const std::string& user_email,
312 RemoveUserDelegate* delegate) {
313 if (delegate)
314 delegate->OnBeforeUserRemoved(user_email);
315 RemoveUserFromList(user_email);
316 cryptohome::AsyncMethodCaller::GetInstance()->AsyncRemove(
317 user_email, base::Bind(&OnRemoveUserComplete, user_email));
319 if (delegate)
320 delegate->OnUserRemoved(user_email);
323 void UserManagerBase::RemoveUserFromList(const std::string& user_id) {
324 DCHECK(task_runner_->RunsTasksOnCurrentThread());
325 RemoveNonCryptohomeData(user_id);
326 if (user_loading_stage_ == STAGE_LOADED) {
327 DeleteUser(RemoveRegularOrSupervisedUserFromList(user_id));
328 } else if (user_loading_stage_ == STAGE_LOADING) {
329 DCHECK(gaia::ExtractDomainName(user_id) ==
330 chromeos::login::kSupervisedUserDomain);
331 // Special case, removing partially-constructed supervised user during user
332 // list loading.
333 ListPrefUpdate users_update(GetLocalState(), kRegularUsers);
334 users_update->Remove(base::StringValue(user_id), NULL);
335 } else {
336 NOTREACHED() << "Users are not loaded yet.";
337 return;
340 // Make sure that new data is persisted to Local State.
341 GetLocalState()->CommitPendingWrite();
344 bool UserManagerBase::IsKnownUser(const std::string& user_id) const {
345 return FindUser(user_id) != NULL;
348 const User* UserManagerBase::FindUser(const std::string& user_id) const {
349 DCHECK(task_runner_->RunsTasksOnCurrentThread());
350 if (active_user_ && active_user_->email() == user_id)
351 return active_user_;
352 return FindUserInList(user_id);
355 User* UserManagerBase::FindUserAndModify(const std::string& user_id) {
356 DCHECK(task_runner_->RunsTasksOnCurrentThread());
357 if (active_user_ && active_user_->email() == user_id)
358 return active_user_;
359 return FindUserInListAndModify(user_id);
362 const User* UserManagerBase::GetLoggedInUser() const {
363 DCHECK(task_runner_->RunsTasksOnCurrentThread());
364 return active_user_;
367 User* UserManagerBase::GetLoggedInUser() {
368 DCHECK(task_runner_->RunsTasksOnCurrentThread());
369 return active_user_;
372 const User* UserManagerBase::GetActiveUser() const {
373 DCHECK(task_runner_->RunsTasksOnCurrentThread());
374 return active_user_;
377 User* UserManagerBase::GetActiveUser() {
378 DCHECK(task_runner_->RunsTasksOnCurrentThread());
379 return active_user_;
382 const User* UserManagerBase::GetPrimaryUser() const {
383 DCHECK(task_runner_->RunsTasksOnCurrentThread());
384 return primary_user_;
387 void UserManagerBase::SaveUserOAuthStatus(
388 const std::string& user_id,
389 User::OAuthTokenStatus oauth_token_status) {
390 DCHECK(task_runner_->RunsTasksOnCurrentThread());
392 DVLOG(1) << "Saving user OAuth token status in Local State";
393 User* user = FindUserAndModify(user_id);
394 if (user)
395 user->set_oauth_token_status(oauth_token_status);
397 // Do not update local state if data stored or cached outside the user's
398 // cryptohome is to be treated as ephemeral.
399 if (IsUserNonCryptohomeDataEphemeral(user_id))
400 return;
402 DictionaryPrefUpdate oauth_status_update(GetLocalState(),
403 kUserOAuthTokenStatus);
404 oauth_status_update->SetWithoutPathExpansion(
405 user_id,
406 new base::FundamentalValue(static_cast<int>(oauth_token_status)));
409 void UserManagerBase::SaveForceOnlineSignin(const std::string& user_id,
410 bool force_online_signin) {
411 DCHECK(task_runner_->RunsTasksOnCurrentThread());
413 // Do not update local state if data stored or cached outside the user's
414 // cryptohome is to be treated as ephemeral.
415 if (IsUserNonCryptohomeDataEphemeral(user_id))
416 return;
418 DictionaryPrefUpdate force_online_update(GetLocalState(),
419 kUserForceOnlineSignin);
420 force_online_update->SetBooleanWithoutPathExpansion(user_id,
421 force_online_signin);
424 void UserManagerBase::SaveUserDisplayName(const std::string& user_id,
425 const base::string16& display_name) {
426 DCHECK(task_runner_->RunsTasksOnCurrentThread());
428 if (User* user = FindUserAndModify(user_id)) {
429 user->set_display_name(display_name);
431 // Do not update local state if data stored or cached outside the user's
432 // cryptohome is to be treated as ephemeral.
433 if (!IsUserNonCryptohomeDataEphemeral(user_id)) {
434 DictionaryPrefUpdate display_name_update(GetLocalState(),
435 kUserDisplayName);
436 display_name_update->SetWithoutPathExpansion(
437 user_id, new base::StringValue(display_name));
442 base::string16 UserManagerBase::GetUserDisplayName(
443 const std::string& user_id) const {
444 const User* user = FindUser(user_id);
445 return user ? user->display_name() : base::string16();
448 void UserManagerBase::SaveUserDisplayEmail(const std::string& user_id,
449 const std::string& display_email) {
450 DCHECK(task_runner_->RunsTasksOnCurrentThread());
452 User* user = FindUserAndModify(user_id);
453 if (!user) {
454 LOG(ERROR) << "User not found: " << user_id;
455 return; // Ignore if there is no such user.
458 user->set_display_email(display_email);
460 // Do not update local state if data stored or cached outside the user's
461 // cryptohome is to be treated as ephemeral.
462 if (IsUserNonCryptohomeDataEphemeral(user_id))
463 return;
465 DictionaryPrefUpdate display_email_update(GetLocalState(), kUserDisplayEmail);
466 display_email_update->SetWithoutPathExpansion(
467 user_id, new base::StringValue(display_email));
470 std::string UserManagerBase::GetUserDisplayEmail(
471 const std::string& user_id) const {
472 const User* user = FindUser(user_id);
473 return user ? user->display_email() : user_id;
476 void UserManagerBase::UpdateUserAccountData(
477 const std::string& user_id,
478 const UserAccountData& account_data) {
479 DCHECK(task_runner_->RunsTasksOnCurrentThread());
481 SaveUserDisplayName(user_id, account_data.display_name());
483 if (User* user = FindUserAndModify(user_id)) {
484 base::string16 given_name = account_data.given_name();
485 user->set_given_name(given_name);
486 if (!IsUserNonCryptohomeDataEphemeral(user_id)) {
487 DictionaryPrefUpdate given_name_update(GetLocalState(), kUserGivenName);
488 given_name_update->SetWithoutPathExpansion(
489 user_id, new base::StringValue(given_name));
493 UpdateUserAccountLocale(user_id, account_data.locale());
496 // static
497 void UserManagerBase::ParseUserList(const base::ListValue& users_list,
498 const std::set<std::string>& existing_users,
499 std::vector<std::string>* users_vector,
500 std::set<std::string>* users_set) {
501 users_vector->clear();
502 users_set->clear();
503 for (size_t i = 0; i < users_list.GetSize(); ++i) {
504 std::string email;
505 if (!users_list.GetString(i, &email) || email.empty()) {
506 LOG(ERROR) << "Corrupt entry in user list at index " << i << ".";
507 continue;
509 if (existing_users.find(email) != existing_users.end() ||
510 !users_set->insert(email).second) {
511 LOG(ERROR) << "Duplicate user: " << email;
512 continue;
514 users_vector->push_back(email);
518 bool UserManagerBase::IsCurrentUserOwner() const {
519 DCHECK(task_runner_->RunsTasksOnCurrentThread());
520 base::AutoLock lk(is_current_user_owner_lock_);
521 return is_current_user_owner_;
524 void UserManagerBase::SetCurrentUserIsOwner(bool is_current_user_owner) {
525 DCHECK(task_runner_->RunsTasksOnCurrentThread());
527 base::AutoLock lk(is_current_user_owner_lock_);
528 is_current_user_owner_ = is_current_user_owner;
530 UpdateLoginState();
533 bool UserManagerBase::IsCurrentUserNew() const {
534 DCHECK(task_runner_->RunsTasksOnCurrentThread());
535 return is_current_user_new_;
538 bool UserManagerBase::IsCurrentUserNonCryptohomeDataEphemeral() const {
539 DCHECK(task_runner_->RunsTasksOnCurrentThread());
540 return IsUserLoggedIn() &&
541 IsUserNonCryptohomeDataEphemeral(GetLoggedInUser()->email());
544 bool UserManagerBase::CanCurrentUserLock() const {
545 DCHECK(task_runner_->RunsTasksOnCurrentThread());
546 return IsUserLoggedIn() && active_user_->can_lock();
549 bool UserManagerBase::IsUserLoggedIn() const {
550 DCHECK(task_runner_->RunsTasksOnCurrentThread());
551 return active_user_;
554 bool UserManagerBase::IsLoggedInAsRegularUser() const {
555 DCHECK(task_runner_->RunsTasksOnCurrentThread());
556 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_REGULAR;
559 bool UserManagerBase::IsLoggedInAsDemoUser() const {
560 DCHECK(task_runner_->RunsTasksOnCurrentThread());
561 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_RETAIL_MODE;
564 bool UserManagerBase::IsLoggedInAsPublicAccount() const {
565 DCHECK(task_runner_->RunsTasksOnCurrentThread());
566 return IsUserLoggedIn() &&
567 active_user_->GetType() == USER_TYPE_PUBLIC_ACCOUNT;
570 bool UserManagerBase::IsLoggedInAsGuest() const {
571 DCHECK(task_runner_->RunsTasksOnCurrentThread());
572 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_GUEST;
575 bool UserManagerBase::IsLoggedInAsSupervisedUser() const {
576 DCHECK(task_runner_->RunsTasksOnCurrentThread());
577 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_SUPERVISED;
580 bool UserManagerBase::IsLoggedInAsKioskApp() const {
581 DCHECK(task_runner_->RunsTasksOnCurrentThread());
582 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_KIOSK_APP;
585 bool UserManagerBase::IsLoggedInAsStub() const {
586 DCHECK(task_runner_->RunsTasksOnCurrentThread());
587 return IsUserLoggedIn() &&
588 active_user_->email() == chromeos::login::kStubUser;
591 bool UserManagerBase::IsSessionStarted() const {
592 DCHECK(task_runner_->RunsTasksOnCurrentThread());
593 return session_started_;
596 bool UserManagerBase::IsUserNonCryptohomeDataEphemeral(
597 const std::string& user_id) const {
598 // Data belonging to the guest, retail mode and stub users is always
599 // ephemeral.
600 if (user_id == chromeos::login::kGuestUserName ||
601 user_id == chromeos::login::kRetailModeUserName ||
602 user_id == chromeos::login::kStubUser) {
603 return true;
606 // Data belonging to the owner, anyone found on the user list and obsolete
607 // public accounts whose data has not been removed yet is not ephemeral.
608 if (user_id == GetOwnerEmail() || UserExistsInList(user_id) ||
609 IsPublicAccountMarkedForRemoval(user_id)) {
610 return false;
613 // Data belonging to the currently logged-in user is ephemeral when:
614 // a) The user logged into a regular account while the ephemeral users policy
615 // was enabled.
616 // - or -
617 // b) The user logged into any other account type.
618 if (IsUserLoggedIn() && (user_id == GetLoggedInUser()->email()) &&
619 (is_current_user_ephemeral_regular_user_ || !IsLoggedInAsRegularUser())) {
620 return true;
623 // Data belonging to any other user is ephemeral when:
624 // a) Going through the regular login flow and the ephemeral users policy is
625 // enabled.
626 // - or -
627 // b) The browser is restarting after a crash.
628 return AreEphemeralUsersEnabled() ||
629 session_manager::SessionManager::HasBrowserRestarted();
632 void UserManagerBase::AddObserver(UserManager::Observer* obs) {
633 DCHECK(task_runner_->RunsTasksOnCurrentThread());
634 observer_list_.AddObserver(obs);
637 void UserManagerBase::RemoveObserver(UserManager::Observer* obs) {
638 DCHECK(task_runner_->RunsTasksOnCurrentThread());
639 observer_list_.RemoveObserver(obs);
642 void UserManagerBase::AddSessionStateObserver(
643 UserManager::UserSessionStateObserver* obs) {
644 DCHECK(task_runner_->RunsTasksOnCurrentThread());
645 session_state_observer_list_.AddObserver(obs);
648 void UserManagerBase::RemoveSessionStateObserver(
649 UserManager::UserSessionStateObserver* obs) {
650 DCHECK(task_runner_->RunsTasksOnCurrentThread());
651 session_state_observer_list_.RemoveObserver(obs);
654 void UserManagerBase::NotifyLocalStateChanged() {
655 DCHECK(task_runner_->RunsTasksOnCurrentThread());
656 FOR_EACH_OBSERVER(
657 UserManager::Observer, observer_list_, LocalStateChanged(this));
660 bool UserManagerBase::CanUserBeRemoved(const User* user) const {
661 // Only regular and supervised users are allowed to be manually removed.
662 if (!user || (user->GetType() != USER_TYPE_REGULAR &&
663 user->GetType() != USER_TYPE_SUPERVISED)) {
664 return false;
667 // Sanity check: we must not remove single user unless it's an enterprise
668 // device. This check may seem redundant at a first sight because
669 // this single user must be an owner and we perform special check later
670 // in order not to remove an owner. However due to non-instant nature of
671 // ownership assignment this later check may sometimes fail.
672 // See http://crosbug.com/12723
673 if (users_.size() < 2 && !IsEnterpriseManaged())
674 return false;
676 // Sanity check: do not allow any of the the logged in users to be removed.
677 for (UserList::const_iterator it = logged_in_users_.begin();
678 it != logged_in_users_.end();
679 ++it) {
680 if ((*it)->email() == user->email())
681 return false;
684 return true;
687 bool UserManagerBase::GetEphemeralUsersEnabled() const {
688 return ephemeral_users_enabled_;
691 void UserManagerBase::SetEphemeralUsersEnabled(bool enabled) {
692 ephemeral_users_enabled_ = enabled;
695 void UserManagerBase::SetIsCurrentUserNew(bool is_new) {
696 is_current_user_new_ = is_new;
699 void UserManagerBase::SetOwnerEmail(std::string owner_user_id) {
700 owner_email_ = owner_user_id;
703 const std::string& UserManagerBase::GetPendingUserSwitchID() const {
704 return pending_user_switch_;
707 void UserManagerBase::SetPendingUserSwitchID(std::string user_id) {
708 pending_user_switch_ = user_id;
711 void UserManagerBase::EnsureUsersLoaded() {
712 DCHECK(task_runner_->RunsTasksOnCurrentThread());
713 if (!GetLocalState())
714 return;
716 if (user_loading_stage_ != STAGE_NOT_LOADED)
717 return;
718 user_loading_stage_ = STAGE_LOADING;
720 PerformPreUserListLoadingActions();
722 PrefService* local_state = GetLocalState();
723 const base::ListValue* prefs_regular_users =
724 local_state->GetList(kRegularUsers);
726 const base::DictionaryValue* prefs_display_names =
727 local_state->GetDictionary(kUserDisplayName);
728 const base::DictionaryValue* prefs_given_names =
729 local_state->GetDictionary(kUserGivenName);
730 const base::DictionaryValue* prefs_display_emails =
731 local_state->GetDictionary(kUserDisplayEmail);
733 // Load public sessions first.
734 std::set<std::string> public_sessions_set;
735 LoadPublicAccounts(&public_sessions_set);
737 // Load regular users and supervised users.
738 std::vector<std::string> regular_users;
739 std::set<std::string> regular_users_set;
740 ParseUserList(*prefs_regular_users,
741 public_sessions_set,
742 &regular_users,
743 &regular_users_set);
744 for (std::vector<std::string>::const_iterator it = regular_users.begin();
745 it != regular_users.end();
746 ++it) {
747 User* user = NULL;
748 const std::string domain = gaia::ExtractDomainName(*it);
749 if (domain == chromeos::login::kSupervisedUserDomain)
750 user = User::CreateSupervisedUser(*it);
751 else
752 user = User::CreateRegularUser(*it);
753 user->set_oauth_token_status(LoadUserOAuthStatus(*it));
754 user->set_force_online_signin(LoadForceOnlineSignin(*it));
755 users_.push_back(user);
757 base::string16 display_name;
758 if (prefs_display_names->GetStringWithoutPathExpansion(*it,
759 &display_name)) {
760 user->set_display_name(display_name);
763 base::string16 given_name;
764 if (prefs_given_names->GetStringWithoutPathExpansion(*it, &given_name)) {
765 user->set_given_name(given_name);
768 std::string display_email;
769 if (prefs_display_emails->GetStringWithoutPathExpansion(*it,
770 &display_email)) {
771 user->set_display_email(display_email);
775 user_loading_stage_ = STAGE_LOADED;
777 PerformPostUserListLoadingActions();
780 UserList& UserManagerBase::GetUsersAndModify() {
781 EnsureUsersLoaded();
782 return users_;
785 const User* UserManagerBase::FindUserInList(const std::string& user_id) const {
786 const UserList& users = GetUsers();
787 for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) {
788 if ((*it)->email() == user_id)
789 return *it;
791 return NULL;
794 bool UserManagerBase::UserExistsInList(const std::string& user_id) const {
795 const base::ListValue* user_list = GetLocalState()->GetList(kRegularUsers);
796 for (size_t i = 0; i < user_list->GetSize(); ++i) {
797 std::string email;
798 if (user_list->GetString(i, &email) && (user_id == email))
799 return true;
801 return false;
804 User* UserManagerBase::FindUserInListAndModify(const std::string& user_id) {
805 UserList& users = GetUsersAndModify();
806 for (UserList::iterator it = users.begin(); it != users.end(); ++it) {
807 if ((*it)->email() == user_id)
808 return *it;
810 return NULL;
813 void UserManagerBase::GuestUserLoggedIn() {
814 DCHECK(task_runner_->RunsTasksOnCurrentThread());
815 active_user_ = User::CreateGuestUser();
818 void UserManagerBase::AddUserRecord(User* user) {
819 // Add the user to the front of the user list.
820 ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers);
821 prefs_users_update->Insert(0, new base::StringValue(user->email()));
822 users_.insert(users_.begin(), user);
825 void UserManagerBase::RegularUserLoggedIn(const std::string& user_id) {
826 // Remove the user from the user list.
827 active_user_ = RemoveRegularOrSupervisedUserFromList(user_id);
829 // If the user was not found on the user list, create a new user.
830 SetIsCurrentUserNew(!active_user_);
831 if (IsCurrentUserNew()) {
832 active_user_ = User::CreateRegularUser(user_id);
833 active_user_->set_oauth_token_status(LoadUserOAuthStatus(user_id));
834 SaveUserDisplayName(active_user_->email(),
835 base::UTF8ToUTF16(active_user_->GetAccountName(true)));
838 AddUserRecord(active_user_);
840 // Make sure that new data is persisted to Local State.
841 GetLocalState()->CommitPendingWrite();
844 void UserManagerBase::RegularUserLoggedInAsEphemeral(
845 const std::string& user_id) {
846 DCHECK(task_runner_->RunsTasksOnCurrentThread());
847 SetIsCurrentUserNew(true);
848 is_current_user_ephemeral_regular_user_ = true;
849 active_user_ = User::CreateRegularUser(user_id);
852 void UserManagerBase::NotifyOnLogin() {
853 DCHECK(task_runner_->RunsTasksOnCurrentThread());
855 NotifyActiveUserHashChanged(active_user_->username_hash());
856 NotifyActiveUserChanged(active_user_);
857 UpdateLoginState();
860 User::OAuthTokenStatus UserManagerBase::LoadUserOAuthStatus(
861 const std::string& user_id) const {
862 DCHECK(task_runner_->RunsTasksOnCurrentThread());
864 const base::DictionaryValue* prefs_oauth_status =
865 GetLocalState()->GetDictionary(kUserOAuthTokenStatus);
866 int oauth_token_status = User::OAUTH_TOKEN_STATUS_UNKNOWN;
867 if (prefs_oauth_status &&
868 prefs_oauth_status->GetIntegerWithoutPathExpansion(user_id,
869 &oauth_token_status)) {
870 User::OAuthTokenStatus status =
871 static_cast<User::OAuthTokenStatus>(oauth_token_status);
872 HandleUserOAuthTokenStatusChange(user_id, status);
874 return status;
876 return User::OAUTH_TOKEN_STATUS_UNKNOWN;
879 bool UserManagerBase::LoadForceOnlineSignin(const std::string& user_id) const {
880 DCHECK(task_runner_->RunsTasksOnCurrentThread());
882 const base::DictionaryValue* prefs_force_online =
883 GetLocalState()->GetDictionary(kUserForceOnlineSignin);
884 bool force_online_signin = false;
885 if (prefs_force_online) {
886 prefs_force_online->GetBooleanWithoutPathExpansion(user_id,
887 &force_online_signin);
889 return force_online_signin;
892 void UserManagerBase::RemoveNonCryptohomeData(const std::string& user_id) {
893 PrefService* prefs = GetLocalState();
894 DictionaryPrefUpdate prefs_display_name_update(prefs, kUserDisplayName);
895 prefs_display_name_update->RemoveWithoutPathExpansion(user_id, NULL);
897 DictionaryPrefUpdate prefs_given_name_update(prefs, kUserGivenName);
898 prefs_given_name_update->RemoveWithoutPathExpansion(user_id, NULL);
900 DictionaryPrefUpdate prefs_display_email_update(prefs, kUserDisplayEmail);
901 prefs_display_email_update->RemoveWithoutPathExpansion(user_id, NULL);
903 DictionaryPrefUpdate prefs_oauth_update(prefs, kUserOAuthTokenStatus);
904 prefs_oauth_update->RemoveWithoutPathExpansion(user_id, NULL);
906 DictionaryPrefUpdate prefs_force_online_update(prefs, kUserForceOnlineSignin);
907 prefs_force_online_update->RemoveWithoutPathExpansion(user_id, NULL);
909 std::string last_active_user = GetLocalState()->GetString(kLastActiveUser);
910 if (user_id == last_active_user)
911 GetLocalState()->SetString(kLastActiveUser, std::string());
914 User* UserManagerBase::RemoveRegularOrSupervisedUserFromList(
915 const std::string& user_id) {
916 ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers);
917 prefs_users_update->Clear();
918 User* user = NULL;
919 for (UserList::iterator it = users_.begin(); it != users_.end();) {
920 const std::string user_email = (*it)->email();
921 if (user_email == user_id) {
922 user = *it;
923 it = users_.erase(it);
924 } else {
925 if ((*it)->GetType() == USER_TYPE_REGULAR ||
926 (*it)->GetType() == USER_TYPE_SUPERVISED) {
927 prefs_users_update->Append(new base::StringValue(user_email));
929 ++it;
932 return user;
935 void UserManagerBase::NotifyActiveUserChanged(const User* active_user) {
936 DCHECK(task_runner_->RunsTasksOnCurrentThread());
937 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
938 session_state_observer_list_,
939 ActiveUserChanged(active_user));
942 void UserManagerBase::NotifyUserAddedToSession(const User* added_user,
943 bool user_switch_pending) {
944 DCHECK(task_runner_->RunsTasksOnCurrentThread());
945 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
946 session_state_observer_list_,
947 UserAddedToSession(added_user));
950 void UserManagerBase::NotifyActiveUserHashChanged(const std::string& hash) {
951 DCHECK(task_runner_->RunsTasksOnCurrentThread());
952 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
953 session_state_observer_list_,
954 ActiveUserHashChanged(hash));
957 void UserManagerBase::ChangeUserSupervisedStatus(User* user,
958 bool is_supervised) {
959 DCHECK(task_runner_->RunsTasksOnCurrentThread());
960 user->SetIsSupervised(is_supervised);
961 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
962 session_state_observer_list_,
963 UserChangedSupervisedStatus(user));
966 void UserManagerBase::UpdateLoginState() {
967 if (!chromeos::LoginState::IsInitialized())
968 return; // LoginState may not be intialized in tests.
970 chromeos::LoginState::LoggedInState logged_in_state;
971 logged_in_state = active_user_ ? chromeos::LoginState::LOGGED_IN_ACTIVE
972 : chromeos::LoginState::LOGGED_IN_NONE;
974 chromeos::LoginState::LoggedInUserType login_user_type;
975 if (logged_in_state == chromeos::LoginState::LOGGED_IN_NONE)
976 login_user_type = chromeos::LoginState::LOGGED_IN_USER_NONE;
977 else if (is_current_user_owner_)
978 login_user_type = chromeos::LoginState::LOGGED_IN_USER_OWNER;
979 else if (active_user_->GetType() == USER_TYPE_GUEST)
980 login_user_type = chromeos::LoginState::LOGGED_IN_USER_GUEST;
981 else if (active_user_->GetType() == USER_TYPE_RETAIL_MODE)
982 login_user_type = chromeos::LoginState::LOGGED_IN_USER_RETAIL_MODE;
983 else if (active_user_->GetType() == USER_TYPE_PUBLIC_ACCOUNT)
984 login_user_type = chromeos::LoginState::LOGGED_IN_USER_PUBLIC_ACCOUNT;
985 else if (active_user_->GetType() == USER_TYPE_SUPERVISED)
986 login_user_type = chromeos::LoginState::LOGGED_IN_USER_SUPERVISED;
987 else if (active_user_->GetType() == USER_TYPE_KIOSK_APP)
988 login_user_type = chromeos::LoginState::LOGGED_IN_USER_KIOSK_APP;
989 else
990 login_user_type = chromeos::LoginState::LOGGED_IN_USER_REGULAR;
992 if (primary_user_) {
993 chromeos::LoginState::Get()->SetLoggedInStateAndPrimaryUser(
994 logged_in_state, login_user_type, primary_user_->username_hash());
995 } else {
996 chromeos::LoginState::Get()->SetLoggedInState(logged_in_state,
997 login_user_type);
1001 void UserManagerBase::SetLRUUser(User* user) {
1002 GetLocalState()->SetString(kLastActiveUser, user->email());
1003 GetLocalState()->CommitPendingWrite();
1005 UserList::iterator it =
1006 std::find(lru_logged_in_users_.begin(), lru_logged_in_users_.end(), user);
1007 if (it != lru_logged_in_users_.end())
1008 lru_logged_in_users_.erase(it);
1009 lru_logged_in_users_.insert(lru_logged_in_users_.begin(), user);
1012 void UserManagerBase::SendRegularUserLoginMetrics(const std::string& user_id) {
1013 // If this isn't the first time Chrome was run after the system booted,
1014 // assume that Chrome was restarted because a previous session ended.
1015 if (!CommandLine::ForCurrentProcess()->HasSwitch(
1016 chromeos::switches::kFirstExecAfterBoot)) {
1017 const std::string last_email =
1018 GetLocalState()->GetString(kLastLoggedInRegularUser);
1019 const base::TimeDelta time_to_login =
1020 base::TimeTicks::Now() - manager_creation_time_;
1021 if (!last_email.empty() && user_id != last_email &&
1022 time_to_login.InSeconds() <= kLogoutToLoginDelayMaxSec) {
1023 UMA_HISTOGRAM_CUSTOM_COUNTS("UserManager.LogoutToLoginDelay",
1024 time_to_login.InSeconds(),
1026 kLogoutToLoginDelayMaxSec,
1027 50);
1032 void UserManagerBase::UpdateUserAccountLocale(const std::string& user_id,
1033 const std::string& locale) {
1034 scoped_ptr<std::string> resolved_locale(new std::string());
1035 if (!locale.empty() && locale != GetApplicationLocale()) {
1036 // base::Pased will NULL out |resolved_locale|, so cache the underlying ptr.
1037 std::string* raw_resolved_locale = resolved_locale.get();
1038 blocking_task_runner_->PostTaskAndReply(
1039 FROM_HERE,
1040 base::Bind(ResolveLocale,
1041 locale,
1042 base::Unretained(raw_resolved_locale)),
1043 base::Bind(&UserManagerBase::DoUpdateAccountLocale,
1044 weak_factory_.GetWeakPtr(),
1045 user_id,
1046 base::Passed(&resolved_locale)));
1047 } else {
1048 resolved_locale.reset(new std::string(locale));
1049 DoUpdateAccountLocale(user_id, resolved_locale.Pass());
1053 void UserManagerBase::DoUpdateAccountLocale(
1054 const std::string& user_id,
1055 scoped_ptr<std::string> resolved_locale) {
1056 User* user = FindUserAndModify(user_id);
1057 if (user && resolved_locale)
1058 user->SetAccountLocale(*resolved_locale);
1061 void UserManagerBase::DeleteUser(User* user) {
1062 const bool is_active_user = (user == active_user_);
1063 delete user;
1064 if (is_active_user)
1065 active_user_ = NULL;
1068 } // namespace user_manager