fd50a75d3b539bc47fcbd37ad74788c97ebfb419
[platform/framework/web/crosswalk.git] / src / components / user_manager / user_manager_base.cc
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.
4
5 #include "components/user_manager/user_manager_base.h"
6
7 #include <cstddef>
8 #include <set>
9
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"
36
37 namespace user_manager {
38 namespace {
39
40 // A vector pref of the the regular users known on this device, arranged in LRU
41 // order.
42 const char kRegularUsers[] = "LoggedInUsers";
43
44 // A dictionary that maps user IDs to the displayed name.
45 const char kUserDisplayName[] = "UserDisplayName";
46
47 // A dictionary that maps user IDs to the user's given name.
48 const char kUserGivenName[] = "UserGivenName";
49
50 // A dictionary that maps user IDs to the displayed (non-canonical) emails.
51 const char kUserDisplayEmail[] = "UserDisplayEmail";
52
53 // A dictionary that maps user IDs to OAuth token presence flag.
54 const char kUserOAuthTokenStatus[] = "OAuthTokenStatus";
55
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";
59
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";
64
65 // Upper bound for a histogram metric reporting the amount of time between
66 // one regular user logging out and a different regular user logging in.
67 const int kLogoutToLoginDelayMaxSec = 1800;
68
69 // Callback that is called after user removal is complete.
70 void OnRemoveUserComplete(const std::string& user_email,
71                           bool success,
72                           cryptohome::MountError return_code) {
73   // Log the error, but there's not much we can do.
74   if (!success) {
75     LOG(ERROR) << "Removal of cryptohome for " << user_email
76                << " failed, return code: " << return_code;
77   }
78 }
79
80 }  // namespace
81
82 // static
83 void UserManagerBase::RegisterPrefs(PrefRegistrySimple* registry) {
84   registry->RegisterListPref(kRegularUsers);
85   registry->RegisterStringPref(kLastLoggedInRegularUser, std::string());
86   registry->RegisterDictionaryPref(kUserDisplayName);
87   registry->RegisterDictionaryPref(kUserGivenName);
88   registry->RegisterDictionaryPref(kUserDisplayEmail);
89   registry->RegisterDictionaryPref(kUserOAuthTokenStatus);
90   registry->RegisterDictionaryPref(kUserForceOnlineSignin);
91 }
92
93 UserManagerBase::UserManagerBase(
94     scoped_refptr<base::TaskRunner> task_runner,
95     scoped_refptr<base::TaskRunner> blocking_task_runner)
96     : active_user_(NULL),
97       primary_user_(NULL),
98       user_loading_stage_(STAGE_NOT_LOADED),
99       session_started_(false),
100       is_current_user_owner_(false),
101       is_current_user_new_(false),
102       is_current_user_ephemeral_regular_user_(false),
103       ephemeral_users_enabled_(false),
104       manager_creation_time_(base::TimeTicks::Now()),
105       task_runner_(task_runner),
106       blocking_task_runner_(blocking_task_runner),
107       weak_factory_(this) {
108   UpdateLoginState();
109 }
110
111 UserManagerBase::~UserManagerBase() {
112   // Can't use STLDeleteElements because of the private destructor of User.
113   for (UserList::iterator it = users_.begin(); it != users_.end();
114        it = users_.erase(it)) {
115     DeleteUser(*it);
116   }
117   // These are pointers to the same User instances that were in users_ list.
118   logged_in_users_.clear();
119   lru_logged_in_users_.clear();
120
121   DeleteUser(active_user_);
122 }
123
124 void UserManagerBase::Shutdown() {
125   DCHECK(task_runner_->RunsTasksOnCurrentThread());
126 }
127
128 const UserList& UserManagerBase::GetUsers() const {
129   const_cast<UserManagerBase*>(this)->EnsureUsersLoaded();
130   return users_;
131 }
132
133 const UserList& UserManagerBase::GetLoggedInUsers() const {
134   return logged_in_users_;
135 }
136
137 const UserList& UserManagerBase::GetLRULoggedInUsers() const {
138   return lru_logged_in_users_;
139 }
140
141 const std::string& UserManagerBase::GetOwnerEmail() const {
142   return owner_email_;
143 }
144
145 void UserManagerBase::UserLoggedIn(const std::string& user_id,
146                                    const std::string& username_hash,
147                                    bool browser_restart) {
148   DCHECK(task_runner_->RunsTasksOnCurrentThread());
149
150   User* user = FindUserInListAndModify(user_id);
151   if (active_user_ && user) {
152     user->set_is_logged_in(true);
153     user->set_username_hash(username_hash);
154     logged_in_users_.push_back(user);
155     lru_logged_in_users_.push_back(user);
156
157     // Reset the new user flag if the user already exists.
158     SetIsCurrentUserNew(false);
159     NotifyUserAddedToSession(user, true /* user switch pending */);
160
161     return;
162   }
163
164   if (user_id == chromeos::login::kGuestUserName) {
165     GuestUserLoggedIn();
166   } else if (user_id == chromeos::login::kRetailModeUserName) {
167     RetailModeUserLoggedIn();
168   } else if (IsKioskApp(user_id)) {
169     KioskAppLoggedIn(user_id);
170   } else if (IsDemoApp(user_id)) {
171     DemoAccountLoggedIn();
172   } else {
173     EnsureUsersLoaded();
174
175     if (user && user->GetType() == USER_TYPE_PUBLIC_ACCOUNT) {
176       PublicAccountUserLoggedIn(user);
177     } else if ((user && user->GetType() == USER_TYPE_SUPERVISED) ||
178                (!user &&
179                 gaia::ExtractDomainName(user_id) ==
180                     chromeos::login::kSupervisedUserDomain)) {
181       SupervisedUserLoggedIn(user_id);
182     } else if (browser_restart && IsPublicAccountMarkedForRemoval(user_id)) {
183       PublicAccountUserLoggedIn(User::CreatePublicAccountUser(user_id));
184     } else if (user_id != GetOwnerEmail() && !user &&
185                (AreEphemeralUsersEnabled() || browser_restart)) {
186       RegularUserLoggedInAsEphemeral(user_id);
187     } else {
188       RegularUserLoggedIn(user_id);
189     }
190   }
191
192   DCHECK(active_user_);
193   active_user_->set_is_logged_in(true);
194   active_user_->set_is_active(true);
195   active_user_->set_username_hash(username_hash);
196
197   // Place user who just signed in to the top of the logged in users.
198   logged_in_users_.insert(logged_in_users_.begin(), active_user_);
199   SetLRUUser(active_user_);
200
201   if (!primary_user_) {
202     primary_user_ = active_user_;
203     if (primary_user_->GetType() == USER_TYPE_REGULAR)
204       SendRegularUserLoginMetrics(user_id);
205   }
206
207   UMA_HISTOGRAM_ENUMERATION(
208       "UserManager.LoginUserType", active_user_->GetType(), NUM_USER_TYPES);
209
210   GetLocalState()->SetString(
211       kLastLoggedInRegularUser,
212       (active_user_->GetType() == USER_TYPE_REGULAR) ? user_id : "");
213
214   NotifyOnLogin();
215   PerformPostUserLoggedInActions(browser_restart);
216 }
217
218 void UserManagerBase::SwitchActiveUser(const std::string& user_id) {
219   User* user = FindUserAndModify(user_id);
220   if (!user) {
221     NOTREACHED() << "Switching to a non-existing user";
222     return;
223   }
224   if (user == active_user_) {
225     NOTREACHED() << "Switching to a user who is already active";
226     return;
227   }
228   if (!user->is_logged_in()) {
229     NOTREACHED() << "Switching to a user that is not logged in";
230     return;
231   }
232   if (user->GetType() != USER_TYPE_REGULAR) {
233     NOTREACHED() << "Switching to a non-regular user";
234     return;
235   }
236   if (user->username_hash().empty()) {
237     NOTREACHED() << "Switching to a user that doesn't have username_hash set";
238     return;
239   }
240
241   DCHECK(active_user_);
242   active_user_->set_is_active(false);
243   user->set_is_active(true);
244   active_user_ = user;
245
246   // Move the user to the front.
247   SetLRUUser(active_user_);
248
249   NotifyActiveUserHashChanged(active_user_->username_hash());
250   NotifyActiveUserChanged(active_user_);
251 }
252
253 void UserManagerBase::SessionStarted() {
254   DCHECK(task_runner_->RunsTasksOnCurrentThread());
255   session_started_ = true;
256
257   UpdateLoginState();
258   session_manager::SessionManager::Get()->SetSessionState(
259       session_manager::SESSION_STATE_ACTIVE);
260
261   if (IsCurrentUserNew()) {
262     // Make sure that the new user's data is persisted to Local State.
263     GetLocalState()->CommitPendingWrite();
264   }
265 }
266
267 void UserManagerBase::RemoveUser(const std::string& user_id,
268                                  RemoveUserDelegate* delegate) {
269   DCHECK(task_runner_->RunsTasksOnCurrentThread());
270
271   if (!CanUserBeRemoved(FindUser(user_id)))
272     return;
273
274   RemoveUserInternal(user_id, delegate);
275 }
276
277 void UserManagerBase::RemoveUserInternal(const std::string& user_email,
278                                          RemoveUserDelegate* delegate) {
279   RemoveNonOwnerUserInternal(user_email, delegate);
280 }
281
282 void UserManagerBase::RemoveNonOwnerUserInternal(const std::string& user_email,
283                                                  RemoveUserDelegate* delegate) {
284   if (delegate)
285     delegate->OnBeforeUserRemoved(user_email);
286   RemoveUserFromList(user_email);
287   cryptohome::AsyncMethodCaller::GetInstance()->AsyncRemove(
288       user_email, base::Bind(&OnRemoveUserComplete, user_email));
289
290   if (delegate)
291     delegate->OnUserRemoved(user_email);
292 }
293
294 void UserManagerBase::RemoveUserFromList(const std::string& user_id) {
295   DCHECK(task_runner_->RunsTasksOnCurrentThread());
296   RemoveNonCryptohomeData(user_id);
297   if (user_loading_stage_ == STAGE_LOADED) {
298     DeleteUser(RemoveRegularOrSupervisedUserFromList(user_id));
299   } else if (user_loading_stage_ == STAGE_LOADING) {
300     DCHECK(gaia::ExtractDomainName(user_id) ==
301            chromeos::login::kSupervisedUserDomain);
302     // Special case, removing partially-constructed supervised user during user
303     // list loading.
304     ListPrefUpdate users_update(GetLocalState(), kRegularUsers);
305     users_update->Remove(base::StringValue(user_id), NULL);
306   } else {
307     NOTREACHED() << "Users are not loaded yet.";
308     return;
309   }
310
311   // Make sure that new data is persisted to Local State.
312   GetLocalState()->CommitPendingWrite();
313 }
314
315 bool UserManagerBase::IsKnownUser(const std::string& user_id) const {
316   return FindUser(user_id) != NULL;
317 }
318
319 const User* UserManagerBase::FindUser(const std::string& user_id) const {
320   DCHECK(task_runner_->RunsTasksOnCurrentThread());
321   if (active_user_ && active_user_->email() == user_id)
322     return active_user_;
323   return FindUserInList(user_id);
324 }
325
326 User* UserManagerBase::FindUserAndModify(const std::string& user_id) {
327   DCHECK(task_runner_->RunsTasksOnCurrentThread());
328   if (active_user_ && active_user_->email() == user_id)
329     return active_user_;
330   return FindUserInListAndModify(user_id);
331 }
332
333 const User* UserManagerBase::GetLoggedInUser() const {
334   DCHECK(task_runner_->RunsTasksOnCurrentThread());
335   return active_user_;
336 }
337
338 User* UserManagerBase::GetLoggedInUser() {
339   DCHECK(task_runner_->RunsTasksOnCurrentThread());
340   return active_user_;
341 }
342
343 const User* UserManagerBase::GetActiveUser() const {
344   DCHECK(task_runner_->RunsTasksOnCurrentThread());
345   return active_user_;
346 }
347
348 User* UserManagerBase::GetActiveUser() {
349   DCHECK(task_runner_->RunsTasksOnCurrentThread());
350   return active_user_;
351 }
352
353 const User* UserManagerBase::GetPrimaryUser() const {
354   DCHECK(task_runner_->RunsTasksOnCurrentThread());
355   return primary_user_;
356 }
357
358 void UserManagerBase::SaveUserOAuthStatus(
359     const std::string& user_id,
360     User::OAuthTokenStatus oauth_token_status) {
361   DCHECK(task_runner_->RunsTasksOnCurrentThread());
362
363   DVLOG(1) << "Saving user OAuth token status in Local State";
364   User* user = FindUserAndModify(user_id);
365   if (user)
366     user->set_oauth_token_status(oauth_token_status);
367
368   // Do not update local state if data stored or cached outside the user's
369   // cryptohome is to be treated as ephemeral.
370   if (IsUserNonCryptohomeDataEphemeral(user_id))
371     return;
372
373   DictionaryPrefUpdate oauth_status_update(GetLocalState(),
374                                            kUserOAuthTokenStatus);
375   oauth_status_update->SetWithoutPathExpansion(
376       user_id,
377       new base::FundamentalValue(static_cast<int>(oauth_token_status)));
378 }
379
380 void UserManagerBase::SaveForceOnlineSignin(const std::string& user_id,
381                                             bool force_online_signin) {
382   DCHECK(task_runner_->RunsTasksOnCurrentThread());
383
384   // Do not update local state if data stored or cached outside the user's
385   // cryptohome is to be treated as ephemeral.
386   if (IsUserNonCryptohomeDataEphemeral(user_id))
387     return;
388
389   DictionaryPrefUpdate force_online_update(GetLocalState(),
390                                            kUserForceOnlineSignin);
391   force_online_update->SetBooleanWithoutPathExpansion(user_id,
392                                                       force_online_signin);
393 }
394
395 void UserManagerBase::SaveUserDisplayName(const std::string& user_id,
396                                           const base::string16& display_name) {
397   DCHECK(task_runner_->RunsTasksOnCurrentThread());
398
399   if (User* user = FindUserAndModify(user_id)) {
400     user->set_display_name(display_name);
401
402     // Do not update local state if data stored or cached outside the user's
403     // cryptohome is to be treated as ephemeral.
404     if (!IsUserNonCryptohomeDataEphemeral(user_id)) {
405       DictionaryPrefUpdate display_name_update(GetLocalState(),
406                                                kUserDisplayName);
407       display_name_update->SetWithoutPathExpansion(
408           user_id, new base::StringValue(display_name));
409     }
410   }
411 }
412
413 base::string16 UserManagerBase::GetUserDisplayName(
414     const std::string& user_id) const {
415   const User* user = FindUser(user_id);
416   return user ? user->display_name() : base::string16();
417 }
418
419 void UserManagerBase::SaveUserDisplayEmail(const std::string& user_id,
420                                            const std::string& display_email) {
421   DCHECK(task_runner_->RunsTasksOnCurrentThread());
422
423   User* user = FindUserAndModify(user_id);
424   if (!user) {
425     LOG(ERROR) << "User not found: " << user_id;
426     return;  // Ignore if there is no such user.
427   }
428
429   user->set_display_email(display_email);
430
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     return;
435
436   DictionaryPrefUpdate display_email_update(GetLocalState(), kUserDisplayEmail);
437   display_email_update->SetWithoutPathExpansion(
438       user_id, new base::StringValue(display_email));
439 }
440
441 std::string UserManagerBase::GetUserDisplayEmail(
442     const std::string& user_id) const {
443   const User* user = FindUser(user_id);
444   return user ? user->display_email() : user_id;
445 }
446
447 void UserManagerBase::UpdateUserAccountData(
448     const std::string& user_id,
449     const UserAccountData& account_data) {
450   DCHECK(task_runner_->RunsTasksOnCurrentThread());
451
452   SaveUserDisplayName(user_id, account_data.display_name());
453
454   if (User* user = FindUserAndModify(user_id)) {
455     base::string16 given_name = account_data.given_name();
456     user->set_given_name(given_name);
457     if (!IsUserNonCryptohomeDataEphemeral(user_id)) {
458       DictionaryPrefUpdate given_name_update(GetLocalState(), kUserGivenName);
459       given_name_update->SetWithoutPathExpansion(
460           user_id, new base::StringValue(given_name));
461     }
462   }
463
464   UpdateUserAccountLocale(user_id, account_data.locale());
465 }
466
467 // static
468 void UserManagerBase::ParseUserList(const base::ListValue& users_list,
469                                     const std::set<std::string>& existing_users,
470                                     std::vector<std::string>* users_vector,
471                                     std::set<std::string>* users_set) {
472   users_vector->clear();
473   users_set->clear();
474   for (size_t i = 0; i < users_list.GetSize(); ++i) {
475     std::string email;
476     if (!users_list.GetString(i, &email) || email.empty()) {
477       LOG(ERROR) << "Corrupt entry in user list at index " << i << ".";
478       continue;
479     }
480     if (existing_users.find(email) != existing_users.end() ||
481         !users_set->insert(email).second) {
482       LOG(ERROR) << "Duplicate user: " << email;
483       continue;
484     }
485     users_vector->push_back(email);
486   }
487 }
488
489 bool UserManagerBase::IsCurrentUserOwner() const {
490   DCHECK(task_runner_->RunsTasksOnCurrentThread());
491   base::AutoLock lk(is_current_user_owner_lock_);
492   return is_current_user_owner_;
493 }
494
495 void UserManagerBase::SetCurrentUserIsOwner(bool is_current_user_owner) {
496   DCHECK(task_runner_->RunsTasksOnCurrentThread());
497   {
498     base::AutoLock lk(is_current_user_owner_lock_);
499     is_current_user_owner_ = is_current_user_owner;
500   }
501   UpdateLoginState();
502 }
503
504 bool UserManagerBase::IsCurrentUserNew() const {
505   DCHECK(task_runner_->RunsTasksOnCurrentThread());
506   return is_current_user_new_;
507 }
508
509 bool UserManagerBase::IsCurrentUserNonCryptohomeDataEphemeral() const {
510   DCHECK(task_runner_->RunsTasksOnCurrentThread());
511   return IsUserLoggedIn() &&
512          IsUserNonCryptohomeDataEphemeral(GetLoggedInUser()->email());
513 }
514
515 bool UserManagerBase::CanCurrentUserLock() const {
516   DCHECK(task_runner_->RunsTasksOnCurrentThread());
517   return IsUserLoggedIn() && active_user_->can_lock();
518 }
519
520 bool UserManagerBase::IsUserLoggedIn() const {
521   DCHECK(task_runner_->RunsTasksOnCurrentThread());
522   return active_user_;
523 }
524
525 bool UserManagerBase::IsLoggedInAsRegularUser() const {
526   DCHECK(task_runner_->RunsTasksOnCurrentThread());
527   return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_REGULAR;
528 }
529
530 bool UserManagerBase::IsLoggedInAsDemoUser() const {
531   DCHECK(task_runner_->RunsTasksOnCurrentThread());
532   return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_RETAIL_MODE;
533 }
534
535 bool UserManagerBase::IsLoggedInAsPublicAccount() const {
536   DCHECK(task_runner_->RunsTasksOnCurrentThread());
537   return IsUserLoggedIn() &&
538          active_user_->GetType() == USER_TYPE_PUBLIC_ACCOUNT;
539 }
540
541 bool UserManagerBase::IsLoggedInAsGuest() const {
542   DCHECK(task_runner_->RunsTasksOnCurrentThread());
543   return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_GUEST;
544 }
545
546 bool UserManagerBase::IsLoggedInAsSupervisedUser() const {
547   DCHECK(task_runner_->RunsTasksOnCurrentThread());
548   return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_SUPERVISED;
549 }
550
551 bool UserManagerBase::IsLoggedInAsKioskApp() const {
552   DCHECK(task_runner_->RunsTasksOnCurrentThread());
553   return IsUserLoggedIn() && active_user_->GetType() == USER_TYPE_KIOSK_APP;
554 }
555
556 bool UserManagerBase::IsLoggedInAsStub() const {
557   DCHECK(task_runner_->RunsTasksOnCurrentThread());
558   return IsUserLoggedIn() &&
559          active_user_->email() == chromeos::login::kStubUser;
560 }
561
562 bool UserManagerBase::IsSessionStarted() const {
563   DCHECK(task_runner_->RunsTasksOnCurrentThread());
564   return session_started_;
565 }
566
567 bool UserManagerBase::IsUserNonCryptohomeDataEphemeral(
568     const std::string& user_id) const {
569   // Data belonging to the guest, retail mode and stub users is always
570   // ephemeral.
571   if (user_id == chromeos::login::kGuestUserName ||
572       user_id == chromeos::login::kRetailModeUserName ||
573       user_id == chromeos::login::kStubUser) {
574     return true;
575   }
576
577   // Data belonging to the owner, anyone found on the user list and obsolete
578   // public accounts whose data has not been removed yet is not ephemeral.
579   if (user_id == GetOwnerEmail() || UserExistsInList(user_id) ||
580       IsPublicAccountMarkedForRemoval(user_id)) {
581     return false;
582   }
583
584   // Data belonging to the currently logged-in user is ephemeral when:
585   // a) The user logged into a regular account while the ephemeral users policy
586   //    was enabled.
587   //    - or -
588   // b) The user logged into any other account type.
589   if (IsUserLoggedIn() && (user_id == GetLoggedInUser()->email()) &&
590       (is_current_user_ephemeral_regular_user_ || !IsLoggedInAsRegularUser())) {
591     return true;
592   }
593
594   // Data belonging to any other user is ephemeral when:
595   // a) Going through the regular login flow and the ephemeral users policy is
596   //    enabled.
597   //    - or -
598   // b) The browser is restarting after a crash.
599   return AreEphemeralUsersEnabled() ||
600          session_manager::SessionManager::HasBrowserRestarted();
601 }
602
603 void UserManagerBase::AddObserver(UserManager::Observer* obs) {
604   DCHECK(task_runner_->RunsTasksOnCurrentThread());
605   observer_list_.AddObserver(obs);
606 }
607
608 void UserManagerBase::RemoveObserver(UserManager::Observer* obs) {
609   DCHECK(task_runner_->RunsTasksOnCurrentThread());
610   observer_list_.RemoveObserver(obs);
611 }
612
613 void UserManagerBase::AddSessionStateObserver(
614     UserManager::UserSessionStateObserver* obs) {
615   DCHECK(task_runner_->RunsTasksOnCurrentThread());
616   session_state_observer_list_.AddObserver(obs);
617 }
618
619 void UserManagerBase::RemoveSessionStateObserver(
620     UserManager::UserSessionStateObserver* obs) {
621   DCHECK(task_runner_->RunsTasksOnCurrentThread());
622   session_state_observer_list_.RemoveObserver(obs);
623 }
624
625 void UserManagerBase::NotifyLocalStateChanged() {
626   DCHECK(task_runner_->RunsTasksOnCurrentThread());
627   FOR_EACH_OBSERVER(
628       UserManager::Observer, observer_list_, LocalStateChanged(this));
629 }
630
631 bool UserManagerBase::CanUserBeRemoved(const User* user) const {
632   // Only regular and supervised users are allowed to be manually removed.
633   if (!user || (user->GetType() != USER_TYPE_REGULAR &&
634                 user->GetType() != USER_TYPE_SUPERVISED)) {
635     return false;
636   }
637
638   // Sanity check: we must not remove single user unless it's an enterprise
639   // device. This check may seem redundant at a first sight because
640   // this single user must be an owner and we perform special check later
641   // in order not to remove an owner. However due to non-instant nature of
642   // ownership assignment this later check may sometimes fail.
643   // See http://crosbug.com/12723
644   if (users_.size() < 2 && !IsEnterpriseManaged())
645     return false;
646
647   // Sanity check: do not allow any of the the logged in users to be removed.
648   for (UserList::const_iterator it = logged_in_users_.begin();
649        it != logged_in_users_.end();
650        ++it) {
651     if ((*it)->email() == user->email())
652       return false;
653   }
654
655   return true;
656 }
657
658 bool UserManagerBase::GetEphemeralUsersEnabled() const {
659   return ephemeral_users_enabled_;
660 }
661
662 void UserManagerBase::SetEphemeralUsersEnabled(bool enabled) {
663   ephemeral_users_enabled_ = enabled;
664 }
665
666 void UserManagerBase::SetIsCurrentUserNew(bool is_new) {
667   is_current_user_new_ = is_new;
668 }
669
670 void UserManagerBase::SetOwnerEmail(std::string owner_user_id) {
671   owner_email_ = owner_user_id;
672 }
673
674 const std::string& UserManagerBase::GetPendingUserSwitchID() const {
675   return pending_user_switch_;
676 }
677
678 void UserManagerBase::SetPendingUserSwitchID(std::string user_id) {
679   pending_user_switch_ = user_id;
680 }
681
682 void UserManagerBase::EnsureUsersLoaded() {
683   DCHECK(task_runner_->RunsTasksOnCurrentThread());
684   if (!GetLocalState())
685     return;
686
687   if (user_loading_stage_ != STAGE_NOT_LOADED)
688     return;
689   user_loading_stage_ = STAGE_LOADING;
690
691   PerformPreUserListLoadingActions();
692
693   PrefService* local_state = GetLocalState();
694   const base::ListValue* prefs_regular_users =
695       local_state->GetList(kRegularUsers);
696
697   const base::DictionaryValue* prefs_display_names =
698       local_state->GetDictionary(kUserDisplayName);
699   const base::DictionaryValue* prefs_given_names =
700       local_state->GetDictionary(kUserGivenName);
701   const base::DictionaryValue* prefs_display_emails =
702       local_state->GetDictionary(kUserDisplayEmail);
703
704   // Load public sessions first.
705   std::set<std::string> public_sessions_set;
706   LoadPublicAccounts(&public_sessions_set);
707
708   // Load regular users and supervised users.
709   std::vector<std::string> regular_users;
710   std::set<std::string> regular_users_set;
711   ParseUserList(*prefs_regular_users,
712                 public_sessions_set,
713                 &regular_users,
714                 &regular_users_set);
715   for (std::vector<std::string>::const_iterator it = regular_users.begin();
716        it != regular_users.end();
717        ++it) {
718     User* user = NULL;
719     const std::string domain = gaia::ExtractDomainName(*it);
720     if (domain == chromeos::login::kSupervisedUserDomain)
721       user = User::CreateSupervisedUser(*it);
722     else
723       user = User::CreateRegularUser(*it);
724     user->set_oauth_token_status(LoadUserOAuthStatus(*it));
725     user->set_force_online_signin(LoadForceOnlineSignin(*it));
726     users_.push_back(user);
727
728     base::string16 display_name;
729     if (prefs_display_names->GetStringWithoutPathExpansion(*it,
730                                                            &display_name)) {
731       user->set_display_name(display_name);
732     }
733
734     base::string16 given_name;
735     if (prefs_given_names->GetStringWithoutPathExpansion(*it, &given_name)) {
736       user->set_given_name(given_name);
737     }
738
739     std::string display_email;
740     if (prefs_display_emails->GetStringWithoutPathExpansion(*it,
741                                                             &display_email)) {
742       user->set_display_email(display_email);
743     }
744   }
745
746   user_loading_stage_ = STAGE_LOADED;
747
748   PerformPostUserListLoadingActions();
749 }
750
751 UserList& UserManagerBase::GetUsersAndModify() {
752   EnsureUsersLoaded();
753   return users_;
754 }
755
756 const User* UserManagerBase::FindUserInList(const std::string& user_id) const {
757   const UserList& users = GetUsers();
758   for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) {
759     if ((*it)->email() == user_id)
760       return *it;
761   }
762   return NULL;
763 }
764
765 const bool UserManagerBase::UserExistsInList(const std::string& user_id) const {
766   const base::ListValue* user_list = GetLocalState()->GetList(kRegularUsers);
767   for (size_t i = 0; i < user_list->GetSize(); ++i) {
768     std::string email;
769     if (user_list->GetString(i, &email) && (user_id == email))
770       return true;
771   }
772   return false;
773 }
774
775 User* UserManagerBase::FindUserInListAndModify(const std::string& user_id) {
776   UserList& users = GetUsersAndModify();
777   for (UserList::iterator it = users.begin(); it != users.end(); ++it) {
778     if ((*it)->email() == user_id)
779       return *it;
780   }
781   return NULL;
782 }
783
784 void UserManagerBase::GuestUserLoggedIn() {
785   DCHECK(task_runner_->RunsTasksOnCurrentThread());
786   active_user_ = User::CreateGuestUser();
787 }
788
789 void UserManagerBase::AddUserRecord(User* user) {
790   // Add the user to the front of the user list.
791   ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers);
792   prefs_users_update->Insert(0, new base::StringValue(user->email()));
793   users_.insert(users_.begin(), user);
794 }
795
796 void UserManagerBase::RegularUserLoggedIn(const std::string& user_id) {
797   // Remove the user from the user list.
798   active_user_ = RemoveRegularOrSupervisedUserFromList(user_id);
799
800   // If the user was not found on the user list, create a new user.
801   SetIsCurrentUserNew(!active_user_);
802   if (IsCurrentUserNew()) {
803     active_user_ = User::CreateRegularUser(user_id);
804     active_user_->set_oauth_token_status(LoadUserOAuthStatus(user_id));
805     SaveUserDisplayName(active_user_->email(),
806                         base::UTF8ToUTF16(active_user_->GetAccountName(true)));
807   }
808
809   AddUserRecord(active_user_);
810
811   // Make sure that new data is persisted to Local State.
812   GetLocalState()->CommitPendingWrite();
813 }
814
815 void UserManagerBase::RegularUserLoggedInAsEphemeral(
816     const std::string& user_id) {
817   DCHECK(task_runner_->RunsTasksOnCurrentThread());
818   SetIsCurrentUserNew(true);
819   is_current_user_ephemeral_regular_user_ = true;
820   active_user_ = User::CreateRegularUser(user_id);
821 }
822
823 void UserManagerBase::NotifyOnLogin() {
824   DCHECK(task_runner_->RunsTasksOnCurrentThread());
825
826   NotifyActiveUserHashChanged(active_user_->username_hash());
827   NotifyActiveUserChanged(active_user_);
828   UpdateLoginState();
829 }
830
831 User::OAuthTokenStatus UserManagerBase::LoadUserOAuthStatus(
832     const std::string& user_id) const {
833   DCHECK(task_runner_->RunsTasksOnCurrentThread());
834
835   const base::DictionaryValue* prefs_oauth_status =
836       GetLocalState()->GetDictionary(kUserOAuthTokenStatus);
837   int oauth_token_status = User::OAUTH_TOKEN_STATUS_UNKNOWN;
838   if (prefs_oauth_status &&
839       prefs_oauth_status->GetIntegerWithoutPathExpansion(user_id,
840                                                          &oauth_token_status)) {
841     User::OAuthTokenStatus status =
842         static_cast<User::OAuthTokenStatus>(oauth_token_status);
843     HandleUserOAuthTokenStatusChange(user_id, status);
844
845     return status;
846   }
847   return User::OAUTH_TOKEN_STATUS_UNKNOWN;
848 }
849
850 bool UserManagerBase::LoadForceOnlineSignin(const std::string& user_id) const {
851   DCHECK(task_runner_->RunsTasksOnCurrentThread());
852
853   const base::DictionaryValue* prefs_force_online =
854       GetLocalState()->GetDictionary(kUserForceOnlineSignin);
855   bool force_online_signin = false;
856   if (prefs_force_online) {
857     prefs_force_online->GetBooleanWithoutPathExpansion(user_id,
858                                                        &force_online_signin);
859   }
860   return force_online_signin;
861 }
862
863 void UserManagerBase::RemoveNonCryptohomeData(const std::string& user_id) {
864   PrefService* prefs = GetLocalState();
865   DictionaryPrefUpdate prefs_display_name_update(prefs, kUserDisplayName);
866   prefs_display_name_update->RemoveWithoutPathExpansion(user_id, NULL);
867
868   DictionaryPrefUpdate prefs_given_name_update(prefs, kUserGivenName);
869   prefs_given_name_update->RemoveWithoutPathExpansion(user_id, NULL);
870
871   DictionaryPrefUpdate prefs_display_email_update(prefs, kUserDisplayEmail);
872   prefs_display_email_update->RemoveWithoutPathExpansion(user_id, NULL);
873
874   DictionaryPrefUpdate prefs_oauth_update(prefs, kUserOAuthTokenStatus);
875   prefs_oauth_update->RemoveWithoutPathExpansion(user_id, NULL);
876
877   DictionaryPrefUpdate prefs_force_online_update(prefs, kUserForceOnlineSignin);
878   prefs_force_online_update->RemoveWithoutPathExpansion(user_id, NULL);
879 }
880
881 User* UserManagerBase::RemoveRegularOrSupervisedUserFromList(
882     const std::string& user_id) {
883   ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers);
884   prefs_users_update->Clear();
885   User* user = NULL;
886   for (UserList::iterator it = users_.begin(); it != users_.end();) {
887     const std::string user_email = (*it)->email();
888     if (user_email == user_id) {
889       user = *it;
890       it = users_.erase(it);
891     } else {
892       if ((*it)->GetType() == USER_TYPE_REGULAR ||
893           (*it)->GetType() == USER_TYPE_SUPERVISED) {
894         prefs_users_update->Append(new base::StringValue(user_email));
895       }
896       ++it;
897     }
898   }
899   return user;
900 }
901
902 void UserManagerBase::NotifyActiveUserChanged(const User* active_user) {
903   DCHECK(task_runner_->RunsTasksOnCurrentThread());
904   FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
905                     session_state_observer_list_,
906                     ActiveUserChanged(active_user));
907 }
908
909 void UserManagerBase::NotifyUserAddedToSession(const User* added_user,
910                                                bool user_switch_pending) {
911   DCHECK(task_runner_->RunsTasksOnCurrentThread());
912   FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
913                     session_state_observer_list_,
914                     UserAddedToSession(added_user));
915 }
916
917 void UserManagerBase::NotifyActiveUserHashChanged(const std::string& hash) {
918   DCHECK(task_runner_->RunsTasksOnCurrentThread());
919   FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
920                     session_state_observer_list_,
921                     ActiveUserHashChanged(hash));
922 }
923
924 void UserManagerBase::UpdateLoginState() {
925   if (!chromeos::LoginState::IsInitialized())
926     return;  // LoginState may not be intialized in tests.
927
928   chromeos::LoginState::LoggedInState logged_in_state;
929   logged_in_state = active_user_ ? chromeos::LoginState::LOGGED_IN_ACTIVE
930                                  : chromeos::LoginState::LOGGED_IN_NONE;
931
932   chromeos::LoginState::LoggedInUserType login_user_type;
933   if (logged_in_state == chromeos::LoginState::LOGGED_IN_NONE)
934     login_user_type = chromeos::LoginState::LOGGED_IN_USER_NONE;
935   else if (is_current_user_owner_)
936     login_user_type = chromeos::LoginState::LOGGED_IN_USER_OWNER;
937   else if (active_user_->GetType() == USER_TYPE_GUEST)
938     login_user_type = chromeos::LoginState::LOGGED_IN_USER_GUEST;
939   else if (active_user_->GetType() == USER_TYPE_RETAIL_MODE)
940     login_user_type = chromeos::LoginState::LOGGED_IN_USER_RETAIL_MODE;
941   else if (active_user_->GetType() == USER_TYPE_PUBLIC_ACCOUNT)
942     login_user_type = chromeos::LoginState::LOGGED_IN_USER_PUBLIC_ACCOUNT;
943   else if (active_user_->GetType() == USER_TYPE_SUPERVISED)
944     login_user_type = chromeos::LoginState::LOGGED_IN_USER_SUPERVISED;
945   else if (active_user_->GetType() == USER_TYPE_KIOSK_APP)
946     login_user_type = chromeos::LoginState::LOGGED_IN_USER_KIOSK_APP;
947   else
948     login_user_type = chromeos::LoginState::LOGGED_IN_USER_REGULAR;
949
950   if (primary_user_) {
951     chromeos::LoginState::Get()->SetLoggedInStateAndPrimaryUser(
952         logged_in_state, login_user_type, primary_user_->username_hash());
953   } else {
954     chromeos::LoginState::Get()->SetLoggedInState(logged_in_state,
955                                                   login_user_type);
956   }
957 }
958
959 void UserManagerBase::SetLRUUser(User* user) {
960   UserList::iterator it =
961       std::find(lru_logged_in_users_.begin(), lru_logged_in_users_.end(), user);
962   if (it != lru_logged_in_users_.end())
963     lru_logged_in_users_.erase(it);
964   lru_logged_in_users_.insert(lru_logged_in_users_.begin(), user);
965 }
966
967 void UserManagerBase::SendRegularUserLoginMetrics(const std::string& user_id) {
968   // If this isn't the first time Chrome was run after the system booted,
969   // assume that Chrome was restarted because a previous session ended.
970   if (!CommandLine::ForCurrentProcess()->HasSwitch(
971           chromeos::switches::kFirstExecAfterBoot)) {
972     const std::string last_email =
973         GetLocalState()->GetString(kLastLoggedInRegularUser);
974     const base::TimeDelta time_to_login =
975         base::TimeTicks::Now() - manager_creation_time_;
976     if (!last_email.empty() && user_id != last_email &&
977         time_to_login.InSeconds() <= kLogoutToLoginDelayMaxSec) {
978       UMA_HISTOGRAM_CUSTOM_COUNTS("UserManager.LogoutToLoginDelay",
979                                   time_to_login.InSeconds(),
980                                   0,
981                                   kLogoutToLoginDelayMaxSec,
982                                   50);
983     }
984   }
985 }
986
987 void UserManagerBase::UpdateUserAccountLocale(const std::string& user_id,
988                                               const std::string& locale) {
989   if (!locale.empty() && locale != GetApplicationLocale()) {
990     base::Callback<void(const std::string&)> on_resolve_callback =
991         base::Bind(&UserManagerBase::DoUpdateAccountLocale,
992                    weak_factory_.GetWeakPtr(),
993                    user_id);
994     blocking_task_runner_->PostTask(FROM_HERE,
995                                     base::Bind(&UserManagerBase::ResolveLocale,
996                                                weak_factory_.GetWeakPtr(),
997                                                locale,
998                                                on_resolve_callback));
999   } else {
1000     DoUpdateAccountLocale(user_id, locale);
1001   }
1002 }
1003
1004 void UserManagerBase::ResolveLocale(
1005     const std::string& raw_locale,
1006     base::Callback<void(const std::string&)> on_resolve_callback) {
1007   DCHECK(task_runner_->RunsTasksOnCurrentThread());
1008   std::string resolved_locale;
1009   ignore_result(l10n_util::CheckAndResolveLocale(raw_locale, &resolved_locale));
1010   task_runner_->PostTask(FROM_HERE,
1011                          base::Bind(on_resolve_callback, resolved_locale));
1012 }
1013
1014 void UserManagerBase::DoUpdateAccountLocale(
1015     const std::string& user_id,
1016     const std::string& resolved_locale) {
1017   if (User* user = FindUserAndModify(user_id))
1018     user->SetAccountLocale(resolved_locale);
1019 }
1020
1021 void UserManagerBase::DeleteUser(User* user) {
1022   const bool is_active_user = (user == active_user_);
1023   delete user;
1024   if (is_active_user)
1025     active_user_ = NULL;
1026 }
1027
1028 }  // namespace user_manager