Roll src/third_party/skia 99c7c07:4af6580
[chromium-blink-merge.git] / components / user_manager / user_manager_base.cc
blob2cee60b6d7984a004b968ea063f727709d524539
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 // A vector pref of preferences of known users. All new preferences should be
74 // placed in this list.
75 const char kKnownUsers[] = "KnownUsers";
77 // Known user preferences keys (stored in Local State).
79 // Key of canonical e-mail value.
80 const char kCanonicalEmail[] = "email";
82 // Key of obfuscated GAIA id value.
83 const char kGAIAIdKey[] = "gaia_id";
85 // Key of whether this user ID refers to a SAML user.
86 const char kUsingSAMLKey[] = "using_saml";
88 // Key of Device Id.
89 const char kDeviceId[] = "device_id";
91 // Upper bound for a histogram metric reporting the amount of time between
92 // one regular user logging out and a different regular user logging in.
93 const int kLogoutToLoginDelayMaxSec = 1800;
95 // Callback that is called after user removal is complete.
96 void OnRemoveUserComplete(const std::string& user_email,
97 bool success,
98 cryptohome::MountError return_code) {
99 // Log the error, but there's not much we can do.
100 if (!success) {
101 LOG(ERROR) << "Removal of cryptohome for " << user_email
102 << " failed, return code: " << return_code;
106 // Runs on SequencedWorkerPool thread. Passes resolved locale to UI thread.
107 void ResolveLocale(const std::string& raw_locale,
108 std::string* resolved_locale) {
109 ignore_result(l10n_util::CheckAndResolveLocale(raw_locale, resolved_locale));
112 // Checks if values in |dict| correspond with |user_id| identity.
113 bool UserMatches(const UserID& user_id, const base::DictionaryValue& dict) {
114 std::string value;
116 bool has_email = dict.GetString(kCanonicalEmail, &value);
117 if (has_email && user_id == value)
118 return true;
120 // TODO(antrim): update code once user id is really a struct.
121 bool has_gaia_id = dict.GetString(kGAIAIdKey, &value);
122 if (has_gaia_id && user_id == value)
123 return true;
125 return false;
128 // Fills relevant |dict| values based on |user_id|.
129 void UpdateIdentity(const UserID& user_id, base::DictionaryValue& dict) {
130 dict.SetString(kCanonicalEmail, user_id);
133 } // namespace
135 // static
136 void UserManagerBase::RegisterPrefs(PrefRegistrySimple* registry) {
137 registry->RegisterListPref(kRegularUsers);
138 registry->RegisterListPref(kKnownUsers);
139 registry->RegisterStringPref(kLastLoggedInGaiaUser, std::string());
140 registry->RegisterDictionaryPref(kUserDisplayName);
141 registry->RegisterDictionaryPref(kUserGivenName);
142 registry->RegisterDictionaryPref(kUserDisplayEmail);
143 registry->RegisterDictionaryPref(kUserOAuthTokenStatus);
144 registry->RegisterDictionaryPref(kUserForceOnlineSignin);
145 registry->RegisterDictionaryPref(kUserType);
146 registry->RegisterStringPref(kLastActiveUser, std::string());
149 UserManagerBase::UserManagerBase(
150 scoped_refptr<base::TaskRunner> task_runner,
151 scoped_refptr<base::TaskRunner> blocking_task_runner)
152 : active_user_(NULL),
153 primary_user_(NULL),
154 user_loading_stage_(STAGE_NOT_LOADED),
155 session_started_(false),
156 is_current_user_owner_(false),
157 is_current_user_new_(false),
158 is_current_user_ephemeral_regular_user_(false),
159 ephemeral_users_enabled_(false),
160 manager_creation_time_(base::TimeTicks::Now()),
161 last_session_active_user_initialized_(false),
162 task_runner_(task_runner),
163 blocking_task_runner_(blocking_task_runner),
164 weak_factory_(this) {
165 UpdateLoginState();
168 UserManagerBase::~UserManagerBase() {
169 // Can't use STLDeleteElements because of the private destructor of User.
170 for (UserList::iterator it = users_.begin(); it != users_.end();
171 it = users_.erase(it)) {
172 DeleteUser(*it);
174 // These are pointers to the same User instances that were in users_ list.
175 logged_in_users_.clear();
176 lru_logged_in_users_.clear();
178 DeleteUser(active_user_);
181 void UserManagerBase::Shutdown() {
182 DCHECK(task_runner_->RunsTasksOnCurrentThread());
185 const UserList& UserManagerBase::GetUsers() const {
186 const_cast<UserManagerBase*>(this)->EnsureUsersLoaded();
187 return users_;
190 const UserList& UserManagerBase::GetLoggedInUsers() const {
191 return logged_in_users_;
194 const UserList& UserManagerBase::GetLRULoggedInUsers() const {
195 return lru_logged_in_users_;
198 const std::string& UserManagerBase::GetOwnerEmail() const {
199 return owner_email_;
202 void UserManagerBase::UserLoggedIn(const std::string& user_id,
203 const std::string& username_hash,
204 bool browser_restart) {
205 DCHECK(task_runner_->RunsTasksOnCurrentThread());
207 if (!last_session_active_user_initialized_) {
208 last_session_active_user_ = GetLocalState()->GetString(kLastActiveUser);
209 last_session_active_user_initialized_ = true;
212 User* user = FindUserInListAndModify(user_id);
213 if (active_user_ && user) {
214 user->set_is_logged_in(true);
215 user->set_username_hash(username_hash);
216 logged_in_users_.push_back(user);
217 lru_logged_in_users_.push_back(user);
219 // Reset the new user flag if the user already exists.
220 SetIsCurrentUserNew(false);
221 NotifyUserAddedToSession(user, true /* user switch pending */);
223 return;
226 if (user_id == chromeos::login::kGuestUserName) {
227 GuestUserLoggedIn();
228 } else if (IsKioskApp(user_id)) {
229 KioskAppLoggedIn(user_id);
230 } else if (IsDemoApp(user_id)) {
231 DemoAccountLoggedIn();
232 } else {
233 EnsureUsersLoaded();
235 if (user && user->GetType() == USER_TYPE_PUBLIC_ACCOUNT) {
236 PublicAccountUserLoggedIn(user);
237 } else if ((user && user->GetType() == USER_TYPE_SUPERVISED) ||
238 (!user &&
239 gaia::ExtractDomainName(user_id) ==
240 chromeos::login::kSupervisedUserDomain)) {
241 SupervisedUserLoggedIn(user_id);
242 } else if (browser_restart && IsPublicAccountMarkedForRemoval(user_id)) {
243 PublicAccountUserLoggedIn(User::CreatePublicAccountUser(user_id));
244 } else if (user_id != GetOwnerEmail() && !user &&
245 (AreEphemeralUsersEnabled() || browser_restart)) {
246 RegularUserLoggedInAsEphemeral(user_id);
247 } else {
248 RegularUserLoggedIn(user_id);
252 DCHECK(active_user_);
253 active_user_->set_is_logged_in(true);
254 active_user_->set_is_active(true);
255 active_user_->set_username_hash(username_hash);
257 // Place user who just signed in to the top of the logged in users.
258 logged_in_users_.insert(logged_in_users_.begin(), active_user_);
259 SetLRUUser(active_user_);
261 if (!primary_user_) {
262 primary_user_ = active_user_;
263 if (primary_user_->HasGaiaAccount())
264 SendGaiaUserLoginMetrics(user_id);
267 UMA_HISTOGRAM_ENUMERATION(
268 "UserManager.LoginUserType", active_user_->GetType(), NUM_USER_TYPES);
270 GetLocalState()->SetString(
271 kLastLoggedInGaiaUser, active_user_->HasGaiaAccount() ? user_id : "");
273 NotifyOnLogin();
274 PerformPostUserLoggedInActions(browser_restart);
277 void UserManagerBase::SwitchActiveUser(const std::string& user_id) {
278 User* user = FindUserAndModify(user_id);
279 if (!user) {
280 NOTREACHED() << "Switching to a non-existing user";
281 return;
283 if (user == active_user_) {
284 NOTREACHED() << "Switching to a user who is already active";
285 return;
287 if (!user->is_logged_in()) {
288 NOTREACHED() << "Switching to a user that is not logged in";
289 return;
291 if (!user->HasGaiaAccount()) {
292 NOTREACHED() <<
293 "Switching to a user without gaia account (non-regular one)";
294 return;
296 if (user->username_hash().empty()) {
297 NOTREACHED() << "Switching to a user that doesn't have username_hash set";
298 return;
301 DCHECK(active_user_);
302 active_user_->set_is_active(false);
303 user->set_is_active(true);
304 active_user_ = user;
306 // Move the user to the front.
307 SetLRUUser(active_user_);
309 NotifyActiveUserHashChanged(active_user_->username_hash());
310 NotifyActiveUserChanged(active_user_);
313 void UserManagerBase::SwitchToLastActiveUser() {
314 if (last_session_active_user_.empty())
315 return;
317 if (GetActiveUser()->email() != last_session_active_user_)
318 SwitchActiveUser(last_session_active_user_);
320 // Make sure that this function gets run only once.
321 last_session_active_user_.clear();
324 void UserManagerBase::SessionStarted() {
325 DCHECK(task_runner_->RunsTasksOnCurrentThread());
326 session_started_ = true;
328 UpdateLoginState();
329 session_manager::SessionManager::Get()->SetSessionState(
330 session_manager::SESSION_STATE_ACTIVE);
332 if (IsCurrentUserNew()) {
333 // Make sure that the new user's data is persisted to Local State.
334 GetLocalState()->CommitPendingWrite();
338 void UserManagerBase::RemoveUser(const std::string& user_id,
339 RemoveUserDelegate* delegate) {
340 DCHECK(task_runner_->RunsTasksOnCurrentThread());
342 if (!CanUserBeRemoved(FindUser(user_id)))
343 return;
345 RemoveUserInternal(user_id, delegate);
348 void UserManagerBase::RemoveUserInternal(const std::string& user_email,
349 RemoveUserDelegate* delegate) {
350 RemoveNonOwnerUserInternal(user_email, delegate);
353 void UserManagerBase::RemoveNonOwnerUserInternal(const std::string& user_email,
354 RemoveUserDelegate* delegate) {
355 if (delegate)
356 delegate->OnBeforeUserRemoved(user_email);
357 RemoveUserFromList(user_email);
358 cryptohome::AsyncMethodCaller::GetInstance()->AsyncRemove(
359 user_email, base::Bind(&OnRemoveUserComplete, user_email));
361 if (delegate)
362 delegate->OnUserRemoved(user_email);
365 void UserManagerBase::RemoveUserFromList(const std::string& user_id) {
366 DCHECK(task_runner_->RunsTasksOnCurrentThread());
367 RemoveNonCryptohomeData(user_id);
368 if (user_loading_stage_ == STAGE_LOADED) {
369 DeleteUser(RemoveRegularOrSupervisedUserFromList(user_id));
370 } else if (user_loading_stage_ == STAGE_LOADING) {
371 DCHECK(gaia::ExtractDomainName(user_id) ==
372 chromeos::login::kSupervisedUserDomain ||
373 HasPendingBootstrap(user_id));
374 // Special case, removing partially-constructed supervised user or
375 // boostrapping user during user list loading.
376 ListPrefUpdate users_update(GetLocalState(), kRegularUsers);
377 users_update->Remove(base::StringValue(user_id), NULL);
378 } else {
379 NOTREACHED() << "Users are not loaded yet.";
380 return;
383 // Make sure that new data is persisted to Local State.
384 GetLocalState()->CommitPendingWrite();
387 bool UserManagerBase::IsKnownUser(const std::string& user_id) const {
388 return FindUser(user_id) != NULL;
391 const User* UserManagerBase::FindUser(const std::string& user_id) const {
392 DCHECK(task_runner_->RunsTasksOnCurrentThread());
393 if (active_user_ && active_user_->email() == user_id)
394 return active_user_;
395 return FindUserInList(user_id);
398 User* UserManagerBase::FindUserAndModify(const std::string& user_id) {
399 DCHECK(task_runner_->RunsTasksOnCurrentThread());
400 if (active_user_ && active_user_->email() == user_id)
401 return active_user_;
402 return FindUserInListAndModify(user_id);
405 const User* UserManagerBase::GetLoggedInUser() const {
406 DCHECK(task_runner_->RunsTasksOnCurrentThread());
407 return active_user_;
410 User* UserManagerBase::GetLoggedInUser() {
411 DCHECK(task_runner_->RunsTasksOnCurrentThread());
412 return active_user_;
415 const User* UserManagerBase::GetActiveUser() const {
416 DCHECK(task_runner_->RunsTasksOnCurrentThread());
417 return active_user_;
420 User* UserManagerBase::GetActiveUser() {
421 DCHECK(task_runner_->RunsTasksOnCurrentThread());
422 return active_user_;
425 const User* UserManagerBase::GetPrimaryUser() const {
426 DCHECK(task_runner_->RunsTasksOnCurrentThread());
427 return primary_user_;
430 void UserManagerBase::SaveUserOAuthStatus(
431 const std::string& user_id,
432 User::OAuthTokenStatus oauth_token_status) {
433 DCHECK(task_runner_->RunsTasksOnCurrentThread());
435 DVLOG(1) << "Saving user OAuth token status in Local State";
436 User* user = FindUserAndModify(user_id);
437 if (user)
438 user->set_oauth_token_status(oauth_token_status);
440 // Do not update local state if data stored or cached outside the user's
441 // cryptohome is to be treated as ephemeral.
442 if (IsUserNonCryptohomeDataEphemeral(user_id))
443 return;
445 DictionaryPrefUpdate oauth_status_update(GetLocalState(),
446 kUserOAuthTokenStatus);
447 oauth_status_update->SetWithoutPathExpansion(
448 user_id,
449 new base::FundamentalValue(static_cast<int>(oauth_token_status)));
452 void UserManagerBase::SaveForceOnlineSignin(const std::string& user_id,
453 bool force_online_signin) {
454 DCHECK(task_runner_->RunsTasksOnCurrentThread());
456 // Do not update local state if data stored or cached outside the user's
457 // cryptohome is to be treated as ephemeral.
458 if (IsUserNonCryptohomeDataEphemeral(user_id))
459 return;
461 DictionaryPrefUpdate force_online_update(GetLocalState(),
462 kUserForceOnlineSignin);
463 force_online_update->SetBooleanWithoutPathExpansion(user_id,
464 force_online_signin);
467 void UserManagerBase::SaveUserDisplayName(const std::string& user_id,
468 const base::string16& display_name) {
469 DCHECK(task_runner_->RunsTasksOnCurrentThread());
471 if (User* user = FindUserAndModify(user_id)) {
472 user->set_display_name(display_name);
474 // Do not update local state if data stored or cached outside the user's
475 // cryptohome is to be treated as ephemeral.
476 if (!IsUserNonCryptohomeDataEphemeral(user_id)) {
477 DictionaryPrefUpdate display_name_update(GetLocalState(),
478 kUserDisplayName);
479 display_name_update->SetWithoutPathExpansion(
480 user_id, new base::StringValue(display_name));
485 base::string16 UserManagerBase::GetUserDisplayName(
486 const std::string& user_id) const {
487 const User* user = FindUser(user_id);
488 return user ? user->display_name() : base::string16();
491 void UserManagerBase::SaveUserDisplayEmail(const std::string& user_id,
492 const std::string& display_email) {
493 DCHECK(task_runner_->RunsTasksOnCurrentThread());
495 User* user = FindUserAndModify(user_id);
496 if (!user) {
497 LOG(ERROR) << "User not found: " << user_id;
498 return; // Ignore if there is no such user.
501 user->set_display_email(display_email);
503 // Do not update local state if data stored or cached outside the user's
504 // cryptohome is to be treated as ephemeral.
505 if (IsUserNonCryptohomeDataEphemeral(user_id))
506 return;
508 DictionaryPrefUpdate display_email_update(GetLocalState(), kUserDisplayEmail);
509 display_email_update->SetWithoutPathExpansion(
510 user_id, new base::StringValue(display_email));
513 std::string UserManagerBase::GetUserDisplayEmail(
514 const std::string& user_id) const {
515 const User* user = FindUser(user_id);
516 return user ? user->display_email() : user_id;
519 void UserManagerBase::SaveUserType(const std::string& user_id,
520 const UserType& user_type) {
521 DCHECK(task_runner_->RunsTasksOnCurrentThread());
523 User* user = FindUserAndModify(user_id);
524 if (!user) {
525 LOG(ERROR) << "User not found: " << user_id;
526 return; // Ignore if there is no such user.
529 // Do not update local state if data stored or cached outside the user's
530 // cryptohome is to be treated as ephemeral.
531 if (IsUserNonCryptohomeDataEphemeral(user_id))
532 return;
534 DictionaryPrefUpdate user_type_update(GetLocalState(), kUserType);
535 user_type_update->SetWithoutPathExpansion(
536 user_id, new base::FundamentalValue(static_cast<int>(user_type)));
537 GetLocalState()->CommitPendingWrite();
540 void UserManagerBase::UpdateUsingSAML(const std::string& user_id,
541 const bool using_saml) {
542 SetKnownUserBooleanPref(user_id, kUsingSAMLKey, using_saml);
545 bool UserManagerBase::FindUsingSAML(const std::string& user_id) {
546 bool using_saml;
547 if (GetKnownUserBooleanPref(user_id, kUsingSAMLKey, &using_saml))
548 return using_saml;
549 return false;
552 void UserManagerBase::UpdateUserAccountData(
553 const std::string& user_id,
554 const UserAccountData& account_data) {
555 DCHECK(task_runner_->RunsTasksOnCurrentThread());
557 SaveUserDisplayName(user_id, account_data.display_name());
559 if (User* user = FindUserAndModify(user_id)) {
560 base::string16 given_name = account_data.given_name();
561 user->set_given_name(given_name);
562 if (!IsUserNonCryptohomeDataEphemeral(user_id)) {
563 DictionaryPrefUpdate given_name_update(GetLocalState(), kUserGivenName);
564 given_name_update->SetWithoutPathExpansion(
565 user_id, new base::StringValue(given_name));
569 UpdateUserAccountLocale(user_id, account_data.locale());
572 // static
573 void UserManagerBase::ParseUserList(const base::ListValue& users_list,
574 const std::set<std::string>& existing_users,
575 std::vector<std::string>* users_vector,
576 std::set<std::string>* users_set) {
577 users_vector->clear();
578 users_set->clear();
579 for (size_t i = 0; i < users_list.GetSize(); ++i) {
580 std::string email;
581 if (!users_list.GetString(i, &email) || email.empty()) {
582 LOG(ERROR) << "Corrupt entry in user list at index " << i << ".";
583 continue;
585 if (existing_users.find(email) != existing_users.end() ||
586 !users_set->insert(email).second) {
587 LOG(ERROR) << "Duplicate user: " << email;
588 continue;
590 users_vector->push_back(email);
594 bool UserManagerBase::IsCurrentUserOwner() const {
595 DCHECK(task_runner_->RunsTasksOnCurrentThread());
596 base::AutoLock lk(is_current_user_owner_lock_);
597 return is_current_user_owner_;
600 void UserManagerBase::SetCurrentUserIsOwner(bool is_current_user_owner) {
601 DCHECK(task_runner_->RunsTasksOnCurrentThread());
603 base::AutoLock lk(is_current_user_owner_lock_);
604 is_current_user_owner_ = is_current_user_owner;
606 UpdateLoginState();
609 bool UserManagerBase::IsCurrentUserNew() const {
610 DCHECK(task_runner_->RunsTasksOnCurrentThread());
611 return is_current_user_new_;
614 bool UserManagerBase::IsCurrentUserNonCryptohomeDataEphemeral() const {
615 DCHECK(task_runner_->RunsTasksOnCurrentThread());
616 return IsUserLoggedIn() &&
617 IsUserNonCryptohomeDataEphemeral(GetLoggedInUser()->email());
620 bool UserManagerBase::CanCurrentUserLock() const {
621 DCHECK(task_runner_->RunsTasksOnCurrentThread());
622 return IsUserLoggedIn() && active_user_->can_lock();
625 bool UserManagerBase::IsUserLoggedIn() const {
626 DCHECK(task_runner_->RunsTasksOnCurrentThread());
627 return active_user_;
630 bool UserManagerBase::IsLoggedInAsUserWithGaiaAccount() const {
631 DCHECK(task_runner_->RunsTasksOnCurrentThread());
632 return IsUserLoggedIn() && active_user_->HasGaiaAccount();
635 bool UserManagerBase::IsLoggedInAsChildUser() const {
636 DCHECK(task_runner_->RunsTasksOnCurrentThread());
637 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_CHILD;
640 bool UserManagerBase::IsLoggedInAsPublicAccount() const {
641 DCHECK(task_runner_->RunsTasksOnCurrentThread());
642 return IsUserLoggedIn() &&
643 active_user_->GetType() == USER_TYPE_PUBLIC_ACCOUNT;
646 bool UserManagerBase::IsLoggedInAsGuest() const {
647 DCHECK(task_runner_->RunsTasksOnCurrentThread());
648 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_GUEST;
651 bool UserManagerBase::IsLoggedInAsSupervisedUser() const {
652 DCHECK(task_runner_->RunsTasksOnCurrentThread());
653 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_SUPERVISED;
656 bool UserManagerBase::IsLoggedInAsKioskApp() const {
657 DCHECK(task_runner_->RunsTasksOnCurrentThread());
658 return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_KIOSK_APP;
661 bool UserManagerBase::IsLoggedInAsStub() const {
662 DCHECK(task_runner_->RunsTasksOnCurrentThread());
663 return IsUserLoggedIn() &&
664 active_user_->email() == chromeos::login::kStubUser;
667 bool UserManagerBase::IsSessionStarted() const {
668 DCHECK(task_runner_->RunsTasksOnCurrentThread());
669 return session_started_;
672 bool UserManagerBase::IsUserNonCryptohomeDataEphemeral(
673 const std::string& user_id) const {
674 // Data belonging to the guest and stub users is always ephemeral.
675 if (user_id == chromeos::login::kGuestUserName ||
676 user_id == chromeos::login::kStubUser) {
677 return true;
680 // Data belonging to the owner, anyone found on the user list and obsolete
681 // public accounts whose data has not been removed yet is not ephemeral.
682 if (user_id == GetOwnerEmail() || UserExistsInList(user_id) ||
683 IsPublicAccountMarkedForRemoval(user_id)) {
684 return false;
687 // Data belonging to the currently logged-in user is ephemeral when:
688 // a) The user logged into a regular gaia account while the ephemeral users
689 // policy was enabled.
690 // - or -
691 // b) The user logged into any other account type.
692 if (IsUserLoggedIn() && (user_id == GetLoggedInUser()->email()) &&
693 (is_current_user_ephemeral_regular_user_ ||
694 !IsLoggedInAsUserWithGaiaAccount())) {
695 return true;
698 // Data belonging to any other user is ephemeral when:
699 // a) Going through the regular login flow and the ephemeral users policy is
700 // enabled.
701 // - or -
702 // b) The browser is restarting after a crash.
703 return AreEphemeralUsersEnabled() ||
704 session_manager::SessionManager::HasBrowserRestarted();
707 void UserManagerBase::AddObserver(UserManager::Observer* obs) {
708 DCHECK(task_runner_->RunsTasksOnCurrentThread());
709 observer_list_.AddObserver(obs);
712 void UserManagerBase::RemoveObserver(UserManager::Observer* obs) {
713 DCHECK(task_runner_->RunsTasksOnCurrentThread());
714 observer_list_.RemoveObserver(obs);
717 void UserManagerBase::AddSessionStateObserver(
718 UserManager::UserSessionStateObserver* obs) {
719 DCHECK(task_runner_->RunsTasksOnCurrentThread());
720 session_state_observer_list_.AddObserver(obs);
723 void UserManagerBase::RemoveSessionStateObserver(
724 UserManager::UserSessionStateObserver* obs) {
725 DCHECK(task_runner_->RunsTasksOnCurrentThread());
726 session_state_observer_list_.RemoveObserver(obs);
729 void UserManagerBase::NotifyLocalStateChanged() {
730 DCHECK(task_runner_->RunsTasksOnCurrentThread());
731 FOR_EACH_OBSERVER(
732 UserManager::Observer, observer_list_, LocalStateChanged(this));
735 bool UserManagerBase::CanUserBeRemoved(const User* user) const {
736 // Only regular and supervised users are allowed to be manually removed.
737 if (!user || !(user->HasGaiaAccount() || user->IsSupervised()))
738 return false;
740 // Sanity check: we must not remove single user unless it's an enterprise
741 // device. This check may seem redundant at a first sight because
742 // this single user must be an owner and we perform special check later
743 // in order not to remove an owner. However due to non-instant nature of
744 // ownership assignment this later check may sometimes fail.
745 // See http://crosbug.com/12723
746 if (users_.size() < 2 && !IsEnterpriseManaged())
747 return false;
749 // Sanity check: do not allow any of the the logged in users to be removed.
750 for (UserList::const_iterator it = logged_in_users_.begin();
751 it != logged_in_users_.end();
752 ++it) {
753 if ((*it)->email() == user->email())
754 return false;
757 return true;
760 bool UserManagerBase::GetEphemeralUsersEnabled() const {
761 return ephemeral_users_enabled_;
764 void UserManagerBase::SetEphemeralUsersEnabled(bool enabled) {
765 ephemeral_users_enabled_ = enabled;
768 void UserManagerBase::SetIsCurrentUserNew(bool is_new) {
769 is_current_user_new_ = is_new;
772 bool UserManagerBase::HasPendingBootstrap(const std::string& user_id) const {
773 return false;
776 void UserManagerBase::SetOwnerEmail(std::string owner_user_id) {
777 owner_email_ = owner_user_id;
780 const std::string& UserManagerBase::GetPendingUserSwitchID() const {
781 return pending_user_switch_;
784 void UserManagerBase::SetPendingUserSwitchID(std::string user_id) {
785 pending_user_switch_ = user_id;
788 void UserManagerBase::EnsureUsersLoaded() {
789 DCHECK(task_runner_->RunsTasksOnCurrentThread());
790 if (!GetLocalState())
791 return;
793 if (user_loading_stage_ != STAGE_NOT_LOADED)
794 return;
795 user_loading_stage_ = STAGE_LOADING;
797 PerformPreUserListLoadingActions();
799 PrefService* local_state = GetLocalState();
800 const base::ListValue* prefs_regular_users =
801 local_state->GetList(kRegularUsers);
803 const base::DictionaryValue* prefs_display_names =
804 local_state->GetDictionary(kUserDisplayName);
805 const base::DictionaryValue* prefs_given_names =
806 local_state->GetDictionary(kUserGivenName);
807 const base::DictionaryValue* prefs_display_emails =
808 local_state->GetDictionary(kUserDisplayEmail);
809 const base::DictionaryValue* prefs_user_types =
810 local_state->GetDictionary(kUserType);
812 // Load public sessions first.
813 std::set<std::string> public_sessions_set;
814 LoadPublicAccounts(&public_sessions_set);
816 // Load regular users and supervised users.
817 std::vector<std::string> regular_users;
818 std::set<std::string> regular_users_set;
819 ParseUserList(*prefs_regular_users,
820 public_sessions_set,
821 &regular_users,
822 &regular_users_set);
823 for (std::vector<std::string>::const_iterator it = regular_users.begin();
824 it != regular_users.end();
825 ++it) {
826 User* user = NULL;
827 const std::string domain = gaia::ExtractDomainName(*it);
828 if (domain == chromeos::login::kSupervisedUserDomain) {
829 user = User::CreateSupervisedUser(*it);
830 } else {
831 user = User::CreateRegularUser(*it);
832 int user_type;
833 if (prefs_user_types->GetIntegerWithoutPathExpansion(*it, &user_type) &&
834 user_type == USER_TYPE_CHILD) {
835 ChangeUserChildStatus(user, true /* is child */);
838 user->set_oauth_token_status(LoadUserOAuthStatus(*it));
839 user->set_force_online_signin(LoadForceOnlineSignin(*it));
840 users_.push_back(user);
842 base::string16 display_name;
843 if (prefs_display_names->GetStringWithoutPathExpansion(*it,
844 &display_name)) {
845 user->set_display_name(display_name);
848 base::string16 given_name;
849 if (prefs_given_names->GetStringWithoutPathExpansion(*it, &given_name)) {
850 user->set_given_name(given_name);
853 std::string display_email;
854 if (prefs_display_emails->GetStringWithoutPathExpansion(*it,
855 &display_email)) {
856 user->set_display_email(display_email);
860 user_loading_stage_ = STAGE_LOADED;
862 PerformPostUserListLoadingActions();
865 UserList& UserManagerBase::GetUsersAndModify() {
866 EnsureUsersLoaded();
867 return users_;
870 const User* UserManagerBase::FindUserInList(const std::string& user_id) const {
871 const UserList& users = GetUsers();
872 for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) {
873 if ((*it)->email() == user_id)
874 return *it;
876 return NULL;
879 bool UserManagerBase::UserExistsInList(const std::string& user_id) const {
880 const base::ListValue* user_list = GetLocalState()->GetList(kRegularUsers);
881 for (size_t i = 0; i < user_list->GetSize(); ++i) {
882 std::string email;
883 if (user_list->GetString(i, &email) && (user_id == email))
884 return true;
886 return false;
889 User* UserManagerBase::FindUserInListAndModify(const std::string& user_id) {
890 UserList& users = GetUsersAndModify();
891 for (UserList::iterator it = users.begin(); it != users.end(); ++it) {
892 if ((*it)->email() == user_id)
893 return *it;
895 return NULL;
898 void UserManagerBase::GuestUserLoggedIn() {
899 DCHECK(task_runner_->RunsTasksOnCurrentThread());
900 active_user_ = User::CreateGuestUser();
903 void UserManagerBase::AddUserRecord(User* user) {
904 // Add the user to the front of the user list.
905 ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers);
906 prefs_users_update->Insert(0, new base::StringValue(user->email()));
907 users_.insert(users_.begin(), user);
910 void UserManagerBase::RegularUserLoggedIn(const std::string& user_id) {
911 // Remove the user from the user list.
912 active_user_ = RemoveRegularOrSupervisedUserFromList(user_id);
914 // If the user was not found on the user list, create a new user.
915 SetIsCurrentUserNew(!active_user_);
916 if (IsCurrentUserNew()) {
917 active_user_ = User::CreateRegularUser(user_id);
918 active_user_->set_oauth_token_status(LoadUserOAuthStatus(user_id));
919 SaveUserDisplayName(active_user_->email(),
920 base::UTF8ToUTF16(active_user_->GetAccountName(true)));
923 AddUserRecord(active_user_);
925 // Make sure that new data is persisted to Local State.
926 GetLocalState()->CommitPendingWrite();
929 void UserManagerBase::RegularUserLoggedInAsEphemeral(
930 const std::string& user_id) {
931 DCHECK(task_runner_->RunsTasksOnCurrentThread());
932 SetIsCurrentUserNew(true);
933 is_current_user_ephemeral_regular_user_ = true;
934 active_user_ = User::CreateRegularUser(user_id);
937 void UserManagerBase::NotifyOnLogin() {
938 DCHECK(task_runner_->RunsTasksOnCurrentThread());
940 NotifyActiveUserHashChanged(active_user_->username_hash());
941 NotifyActiveUserChanged(active_user_);
942 UpdateLoginState();
945 User::OAuthTokenStatus UserManagerBase::LoadUserOAuthStatus(
946 const std::string& user_id) const {
947 DCHECK(task_runner_->RunsTasksOnCurrentThread());
949 const base::DictionaryValue* prefs_oauth_status =
950 GetLocalState()->GetDictionary(kUserOAuthTokenStatus);
951 int oauth_token_status = User::OAUTH_TOKEN_STATUS_UNKNOWN;
952 if (prefs_oauth_status &&
953 prefs_oauth_status->GetIntegerWithoutPathExpansion(user_id,
954 &oauth_token_status)) {
955 User::OAuthTokenStatus status =
956 static_cast<User::OAuthTokenStatus>(oauth_token_status);
957 HandleUserOAuthTokenStatusChange(user_id, status);
959 return status;
961 return User::OAUTH_TOKEN_STATUS_UNKNOWN;
964 bool UserManagerBase::LoadForceOnlineSignin(const std::string& user_id) const {
965 DCHECK(task_runner_->RunsTasksOnCurrentThread());
967 const base::DictionaryValue* prefs_force_online =
968 GetLocalState()->GetDictionary(kUserForceOnlineSignin);
969 bool force_online_signin = false;
970 if (prefs_force_online) {
971 prefs_force_online->GetBooleanWithoutPathExpansion(user_id,
972 &force_online_signin);
974 return force_online_signin;
977 void UserManagerBase::RemoveNonCryptohomeData(const std::string& user_id) {
978 PrefService* prefs = GetLocalState();
979 DictionaryPrefUpdate prefs_display_name_update(prefs, kUserDisplayName);
980 prefs_display_name_update->RemoveWithoutPathExpansion(user_id, NULL);
982 DictionaryPrefUpdate prefs_given_name_update(prefs, kUserGivenName);
983 prefs_given_name_update->RemoveWithoutPathExpansion(user_id, NULL);
985 DictionaryPrefUpdate prefs_display_email_update(prefs, kUserDisplayEmail);
986 prefs_display_email_update->RemoveWithoutPathExpansion(user_id, NULL);
988 DictionaryPrefUpdate prefs_oauth_update(prefs, kUserOAuthTokenStatus);
989 prefs_oauth_update->RemoveWithoutPathExpansion(user_id, NULL);
991 DictionaryPrefUpdate prefs_force_online_update(prefs, kUserForceOnlineSignin);
992 prefs_force_online_update->RemoveWithoutPathExpansion(user_id, NULL);
994 RemoveKnownUserPrefs(user_id);
996 std::string last_active_user = GetLocalState()->GetString(kLastActiveUser);
997 if (user_id == last_active_user)
998 GetLocalState()->SetString(kLastActiveUser, std::string());
1001 bool UserManagerBase::FindKnownUserPrefs(
1002 const UserID& user_id,
1003 const base::DictionaryValue** out_value) {
1004 PrefService* local_state = GetLocalState();
1005 const base::ListValue* known_users = local_state->GetList(kKnownUsers);
1006 for (size_t i = 0; i < known_users->GetSize(); ++i) {
1007 const base::DictionaryValue* element = nullptr;
1008 if (known_users->GetDictionary(i, &element)) {
1009 if (UserMatches(user_id, *element)) {
1010 known_users->GetDictionary(i, out_value);
1011 return true;
1015 return false;
1018 void UserManagerBase::UpdateKnownUserPrefs(const UserID& user_id,
1019 const base::DictionaryValue& values,
1020 bool clear) {
1021 ListPrefUpdate update(GetLocalState(), kKnownUsers);
1022 for (size_t i = 0; i < update->GetSize(); ++i) {
1023 base::DictionaryValue* element = nullptr;
1024 if (update->GetDictionary(i, &element)) {
1025 if (UserMatches(user_id, *element)) {
1026 if (clear)
1027 element->Clear();
1028 element->MergeDictionary(&values);
1029 UpdateIdentity(user_id, *element);
1030 return;
1034 scoped_ptr<base::DictionaryValue> new_value(new base::DictionaryValue());
1035 new_value->MergeDictionary(&values);
1036 UpdateIdentity(user_id, *new_value);
1037 update->Append(new_value.release());
1040 bool UserManagerBase::GetKnownUserStringPref(const UserID& user_id,
1041 const std::string& path,
1042 std::string* out_value) {
1043 const base::DictionaryValue* user_pref_dict = nullptr;
1044 if (!FindKnownUserPrefs(user_id, &user_pref_dict))
1045 return false;
1047 return user_pref_dict->GetString(path, out_value);
1050 void UserManagerBase::SetKnownUserStringPref(const UserID& user_id,
1051 const std::string& path,
1052 const std::string& in_value) {
1053 ListPrefUpdate update(GetLocalState(), kKnownUsers);
1054 base::DictionaryValue dict;
1055 dict.SetString(path, in_value);
1056 UpdateKnownUserPrefs(user_id, dict, false);
1059 bool UserManagerBase::GetKnownUserBooleanPref(const UserID& user_id,
1060 const std::string& path,
1061 bool* out_value) {
1062 const base::DictionaryValue* user_pref_dict = nullptr;
1063 if (!FindKnownUserPrefs(user_id, &user_pref_dict))
1064 return false;
1066 return user_pref_dict->GetBoolean(path, out_value);
1069 void UserManagerBase::SetKnownUserBooleanPref(const UserID& user_id,
1070 const std::string& path,
1071 const bool in_value) {
1072 ListPrefUpdate update(GetLocalState(), kKnownUsers);
1073 base::DictionaryValue dict;
1074 dict.SetBoolean(path, in_value);
1075 UpdateKnownUserPrefs(user_id, dict, false);
1078 void UserManagerBase::UpdateGaiaID(const UserID& user_id,
1079 const std::string& gaia_id) {
1080 SetKnownUserStringPref(user_id, kGAIAIdKey, gaia_id);
1083 bool UserManagerBase::FindGaiaID(const UserID& user_id,
1084 std::string* out_value) {
1085 return GetKnownUserStringPref(user_id, kGAIAIdKey, out_value);
1088 void UserManagerBase::SetKnownUserDeviceId(const UserID& user_id,
1089 const std::string& device_id) {
1090 SetKnownUserStringPref(user_id, kDeviceId, device_id);
1093 std::string UserManagerBase::GetKnownUserDeviceId(const UserID& user_id) {
1094 std::string device_id;
1095 if (GetKnownUserStringPref(user_id, kDeviceId, &device_id)) {
1096 return device_id;
1098 return std::string();
1101 User* UserManagerBase::RemoveRegularOrSupervisedUserFromList(
1102 const std::string& user_id) {
1103 ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers);
1104 prefs_users_update->Clear();
1105 User* user = NULL;
1106 for (UserList::iterator it = users_.begin(); it != users_.end();) {
1107 const std::string user_email = (*it)->email();
1108 if (user_email == user_id) {
1109 user = *it;
1110 it = users_.erase(it);
1111 } else {
1112 if ((*it)->HasGaiaAccount() || (*it)->IsSupervised())
1113 prefs_users_update->Append(new base::StringValue(user_email));
1114 ++it;
1117 return user;
1120 void UserManagerBase::RemoveKnownUserPrefs(const UserID& user_id) {
1121 ListPrefUpdate update(GetLocalState(), kKnownUsers);
1122 for (size_t i = 0; i < update->GetSize(); ++i) {
1123 base::DictionaryValue* element = nullptr;
1124 if (update->GetDictionary(i, &element)) {
1125 if (UserMatches(user_id, *element)) {
1126 update->Remove(i, nullptr);
1127 break;
1133 void UserManagerBase::NotifyActiveUserChanged(const User* active_user) {
1134 DCHECK(task_runner_->RunsTasksOnCurrentThread());
1135 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
1136 session_state_observer_list_,
1137 ActiveUserChanged(active_user));
1140 void UserManagerBase::NotifyUserAddedToSession(const User* added_user,
1141 bool user_switch_pending) {
1142 DCHECK(task_runner_->RunsTasksOnCurrentThread());
1143 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
1144 session_state_observer_list_,
1145 UserAddedToSession(added_user));
1148 void UserManagerBase::NotifyActiveUserHashChanged(const std::string& hash) {
1149 DCHECK(task_runner_->RunsTasksOnCurrentThread());
1150 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
1151 session_state_observer_list_,
1152 ActiveUserHashChanged(hash));
1155 void UserManagerBase::ChangeUserChildStatus(User* user, bool is_child) {
1156 DCHECK(task_runner_->RunsTasksOnCurrentThread());
1157 if (user->IsSupervised() == is_child)
1158 return;
1159 user->SetIsChild(is_child);
1160 SaveUserType(user->email(), is_child ? user_manager::USER_TYPE_CHILD
1161 : user_manager::USER_TYPE_REGULAR);
1162 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
1163 session_state_observer_list_,
1164 UserChangedChildStatus(user));
1167 void UserManagerBase::UpdateLoginState() {
1168 if (!chromeos::LoginState::IsInitialized())
1169 return; // LoginState may not be initialized in tests.
1171 chromeos::LoginState::LoggedInState logged_in_state;
1172 logged_in_state = active_user_ ? chromeos::LoginState::LOGGED_IN_ACTIVE
1173 : chromeos::LoginState::LOGGED_IN_NONE;
1175 chromeos::LoginState::LoggedInUserType login_user_type;
1176 if (logged_in_state == chromeos::LoginState::LOGGED_IN_NONE)
1177 login_user_type = chromeos::LoginState::LOGGED_IN_USER_NONE;
1178 else if (is_current_user_owner_)
1179 login_user_type = chromeos::LoginState::LOGGED_IN_USER_OWNER;
1180 else if (active_user_->GetType() == USER_TYPE_GUEST)
1181 login_user_type = chromeos::LoginState::LOGGED_IN_USER_GUEST;
1182 else if (active_user_->GetType() == USER_TYPE_PUBLIC_ACCOUNT)
1183 login_user_type = chromeos::LoginState::LOGGED_IN_USER_PUBLIC_ACCOUNT;
1184 else if (active_user_->GetType() == USER_TYPE_SUPERVISED)
1185 login_user_type = chromeos::LoginState::LOGGED_IN_USER_SUPERVISED;
1186 else if (active_user_->GetType() == USER_TYPE_KIOSK_APP)
1187 login_user_type = chromeos::LoginState::LOGGED_IN_USER_KIOSK_APP;
1188 else
1189 login_user_type = chromeos::LoginState::LOGGED_IN_USER_REGULAR;
1191 if (primary_user_) {
1192 chromeos::LoginState::Get()->SetLoggedInStateAndPrimaryUser(
1193 logged_in_state, login_user_type, primary_user_->username_hash());
1194 } else {
1195 chromeos::LoginState::Get()->SetLoggedInState(logged_in_state,
1196 login_user_type);
1200 void UserManagerBase::SetLRUUser(User* user) {
1201 GetLocalState()->SetString(kLastActiveUser, user->email());
1202 GetLocalState()->CommitPendingWrite();
1204 UserList::iterator it =
1205 std::find(lru_logged_in_users_.begin(), lru_logged_in_users_.end(), user);
1206 if (it != lru_logged_in_users_.end())
1207 lru_logged_in_users_.erase(it);
1208 lru_logged_in_users_.insert(lru_logged_in_users_.begin(), user);
1211 void UserManagerBase::SendGaiaUserLoginMetrics(const std::string& user_id) {
1212 // If this isn't the first time Chrome was run after the system booted,
1213 // assume that Chrome was restarted because a previous session ended.
1214 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1215 chromeos::switches::kFirstExecAfterBoot)) {
1216 const std::string last_email =
1217 GetLocalState()->GetString(kLastLoggedInGaiaUser);
1218 const base::TimeDelta time_to_login =
1219 base::TimeTicks::Now() - manager_creation_time_;
1220 if (!last_email.empty() && user_id != last_email &&
1221 time_to_login.InSeconds() <= kLogoutToLoginDelayMaxSec) {
1222 UMA_HISTOGRAM_CUSTOM_COUNTS("UserManager.LogoutToLoginDelay",
1223 time_to_login.InSeconds(),
1225 kLogoutToLoginDelayMaxSec,
1226 50);
1231 void UserManagerBase::UpdateUserAccountLocale(const std::string& user_id,
1232 const std::string& locale) {
1233 scoped_ptr<std::string> resolved_locale(new std::string());
1234 if (!locale.empty() && locale != GetApplicationLocale()) {
1235 // base::Pased will NULL out |resolved_locale|, so cache the underlying ptr.
1236 std::string* raw_resolved_locale = resolved_locale.get();
1237 blocking_task_runner_->PostTaskAndReply(
1238 FROM_HERE,
1239 base::Bind(ResolveLocale,
1240 locale,
1241 base::Unretained(raw_resolved_locale)),
1242 base::Bind(&UserManagerBase::DoUpdateAccountLocale,
1243 weak_factory_.GetWeakPtr(),
1244 user_id,
1245 base::Passed(&resolved_locale)));
1246 } else {
1247 resolved_locale.reset(new std::string(locale));
1248 DoUpdateAccountLocale(user_id, resolved_locale.Pass());
1252 void UserManagerBase::DoUpdateAccountLocale(
1253 const std::string& user_id,
1254 scoped_ptr<std::string> resolved_locale) {
1255 User* user = FindUserAndModify(user_id);
1256 if (user && resolved_locale)
1257 user->SetAccountLocale(*resolved_locale);
1260 void UserManagerBase::DeleteUser(User* user) {
1261 const bool is_active_user = (user == active_user_);
1262 delete user;
1263 if (is_active_user)
1264 active_user_ = NULL;
1267 } // namespace user_manager