Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(613)

Side by Side Diff: chrome/browser/chromeos/login/user_manager_impl.cc

Issue 286933002: [cros login] Split login related classes into subfolders. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: fix includes in new tests Created 6 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2013 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 "chrome/browser/chromeos/login/user_manager_impl.h"
6
7 #include <cstddef>
8 #include <set>
9
10 #include "ash/multi_profile_uma.h"
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/command_line.h"
14 #include "base/compiler_specific.h"
15 #include "base/files/file_path.h"
16 #include "base/format_macros.h"
17 #include "base/logging.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/rand_util.h"
23 #include "base/strings/string_util.h"
24 #include "base/strings/stringprintf.h"
25 #include "base/strings/utf_string_conversions.h"
26 #include "base/sys_info.h"
27 #include "base/threading/worker_pool.h"
28 #include "base/values.h"
29 #include "chrome/browser/app_mode/app_mode_utils.h"
30 #include "chrome/browser/browser_process.h"
31 #include "chrome/browser/chrome_notification_types.h"
32 #include "chrome/browser/chromeos/base/locale_util.h"
33 #include "chrome/browser/chromeos/login/auth_sync_observer.h"
34 #include "chrome/browser/chromeos/login/auth_sync_observer_factory.h"
35 #include "chrome/browser/chromeos/login/demo_mode/demo_app_launcher.h"
36 #include "chrome/browser/chromeos/login/login_display.h"
37 #include "chrome/browser/chromeos/login/login_utils.h"
38 #include "chrome/browser/chromeos/login/multi_profile_user_controller.h"
39 #include "chrome/browser/chromeos/login/remove_user_delegate.h"
40 #include "chrome/browser/chromeos/login/supervised_user_manager_impl.h"
41 #include "chrome/browser/chromeos/login/user_image_manager_impl.h"
42 #include "chrome/browser/chromeos/login/wizard_controller.h"
43 #include "chrome/browser/chromeos/net/network_portal_detector.h"
44 #include "chrome/browser/chromeos/net/network_portal_detector_strategy.h"
45 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
46 #include "chrome/browser/chromeos/policy/device_local_account.h"
47 #include "chrome/browser/chromeos/profiles/multiprofiles_session_aborted_dialog. h"
48 #include "chrome/browser/chromeos/profiles/profile_helper.h"
49 #include "chrome/browser/chromeos/session_length_limiter.h"
50 #include "chrome/browser/managed_mode/chromeos/managed_user_password_service_fac tory.h"
51 #include "chrome/browser/managed_mode/chromeos/manager_password_service_factory. h"
52 #include "chrome/browser/net/nss_context.h"
53 #include "chrome/browser/profiles/profile.h"
54 #include "chrome/browser/profiles/profile_manager.h"
55 #include "chrome/browser/profiles/profiles_state.h"
56 #include "chrome/browser/sync/profile_sync_service.h"
57 #include "chrome/browser/sync/profile_sync_service_factory.h"
58 #include "chrome/common/chrome_constants.h"
59 #include "chrome/common/chrome_switches.h"
60 #include "chrome/common/crash_keys.h"
61 #include "chrome/common/pref_names.h"
62 #include "chromeos/cert_loader.h"
63 #include "chromeos/chromeos_switches.h"
64 #include "chromeos/cryptohome/async_method_caller.h"
65 #include "chromeos/dbus/dbus_thread_manager.h"
66 #include "chromeos/login/login_state.h"
67 #include "chromeos/settings/cros_settings_names.h"
68 #include "content/public/browser/browser_thread.h"
69 #include "content/public/browser/notification_service.h"
70 #include "google_apis/gaia/gaia_auth_util.h"
71 #include "google_apis/gaia/google_service_auth_error.h"
72 #include "policy/policy_constants.h"
73 #include "ui/base/l10n/l10n_util.h"
74 #include "ui/wm/core/wm_core_switches.h"
75
76 using content::BrowserThread;
77
78 namespace chromeos {
79 namespace {
80
81 // A vector pref of the the regular users known on this device, arranged in LRU
82 // order.
83 const char kRegularUsers[] = "LoggedInUsers";
84
85 // A vector pref of the public accounts defined on this device.
86 const char kPublicAccounts[] = "PublicAccounts";
87
88 // A string pref that gets set when a public account is removed but a user is
89 // currently logged into that account, requiring the account's data to be
90 // removed after logout.
91 const char kPublicAccountPendingDataRemoval[] =
92 "PublicAccountPendingDataRemoval";
93
94 // A dictionary that maps user IDs to the displayed name.
95 const char kUserDisplayName[] = "UserDisplayName";
96
97 // A dictionary that maps user IDs to the user's given name.
98 const char kUserGivenName[] = "UserGivenName";
99
100 // A dictionary that maps user IDs to the displayed (non-canonical) emails.
101 const char kUserDisplayEmail[] = "UserDisplayEmail";
102
103 // A dictionary that maps user IDs to OAuth token presence flag.
104 const char kUserOAuthTokenStatus[] = "OAuthTokenStatus";
105
106 // A dictionary that maps user IDs to a flag indicating whether online
107 // authentication against GAIA should be enforced during the next sign-in.
108 const char kUserForceOnlineSignin[] = "UserForceOnlineSignin";
109
110 // A string pref containing the ID of the last user who logged in if it was
111 // a regular user or an empty string if it was another type of user (guest,
112 // kiosk, public account, etc.).
113 const char kLastLoggedInRegularUser[] = "LastLoggedInRegularUser";
114
115 // Upper bound for a histogram metric reporting the amount of time between
116 // one regular user logging out and a different regular user logging in.
117 const int kLogoutToLoginDelayMaxSec = 1800;
118
119 // Callback that is called after user removal is complete.
120 void OnRemoveUserComplete(const std::string& user_email,
121 bool success,
122 cryptohome::MountError return_code) {
123 // Log the error, but there's not much we can do.
124 if (!success) {
125 LOG(ERROR) << "Removal of cryptohome for " << user_email
126 << " failed, return code: " << return_code;
127 }
128 }
129
130 // Helper function that copies users from |users_list| to |users_vector| and
131 // |users_set|. Duplicates and users already present in |existing_users| are
132 // skipped.
133 void ParseUserList(const base::ListValue& users_list,
134 const std::set<std::string>& existing_users,
135 std::vector<std::string>* users_vector,
136 std::set<std::string>* users_set) {
137 users_vector->clear();
138 users_set->clear();
139 for (size_t i = 0; i < users_list.GetSize(); ++i) {
140 std::string email;
141 if (!users_list.GetString(i, &email) || email.empty()) {
142 LOG(ERROR) << "Corrupt entry in user list at index " << i << ".";
143 continue;
144 }
145 if (existing_users.find(email) != existing_users.end() ||
146 !users_set->insert(email).second) {
147 LOG(ERROR) << "Duplicate user: " << email;
148 continue;
149 }
150 users_vector->push_back(email);
151 }
152 }
153
154 class UserHashMatcher {
155 public:
156 explicit UserHashMatcher(const std::string& h) : username_hash(h) {}
157 bool operator()(const User* user) const {
158 return user->username_hash() == username_hash;
159 }
160
161 private:
162 const std::string& username_hash;
163 };
164
165 // Runs on SequencedWorkerPool thread. Passes resolved locale to
166 // |on_resolve_callback| on UI thread.
167 void ResolveLocale(
168 const std::string& raw_locale,
169 base::Callback<void(const std::string&)> on_resolve_callback) {
170 DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI));
171 std::string resolved_locale;
172 // Ignore result
173 l10n_util::CheckAndResolveLocale(raw_locale, &resolved_locale);
174 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
175 base::Bind(on_resolve_callback, resolved_locale));
176 }
177
178 // Callback to GetNSSCertDatabaseForProfile. It starts CertLoader using the
179 // provided NSS database. It must be called for primary user only.
180 void OnGetNSSCertDatabaseForUser(net::NSSCertDatabase* database) {
181 if (!CertLoader::IsInitialized())
182 return;
183
184 CertLoader::Get()->StartWithNSSDB(database);
185 }
186
187 } // namespace
188
189 // static
190 void UserManager::RegisterPrefs(PrefRegistrySimple* registry) {
191 registry->RegisterListPref(kRegularUsers);
192 registry->RegisterListPref(kPublicAccounts);
193 registry->RegisterStringPref(kPublicAccountPendingDataRemoval, "");
194 registry->RegisterStringPref(kLastLoggedInRegularUser, "");
195 registry->RegisterDictionaryPref(kUserDisplayName);
196 registry->RegisterDictionaryPref(kUserGivenName);
197 registry->RegisterDictionaryPref(kUserDisplayEmail);
198 registry->RegisterDictionaryPref(kUserOAuthTokenStatus);
199 registry->RegisterDictionaryPref(kUserForceOnlineSignin);
200 SupervisedUserManager::RegisterPrefs(registry);
201 SessionLengthLimiter::RegisterPrefs(registry);
202 }
203
204 UserManagerImpl::UserManagerImpl()
205 : cros_settings_(CrosSettings::Get()),
206 device_local_account_policy_service_(NULL),
207 user_loading_stage_(STAGE_NOT_LOADED),
208 active_user_(NULL),
209 primary_user_(NULL),
210 session_started_(false),
211 user_sessions_restored_(false),
212 is_current_user_owner_(false),
213 is_current_user_new_(false),
214 is_current_user_ephemeral_regular_user_(false),
215 ephemeral_users_enabled_(false),
216 supervised_user_manager_(new SupervisedUserManagerImpl(this)),
217 manager_creation_time_(base::TimeTicks::Now()) {
218 UpdateNumberOfUsers();
219 // UserManager instance should be used only on UI thread.
220 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
221 registrar_.Add(this, chrome::NOTIFICATION_OWNERSHIP_STATUS_CHANGED,
222 content::NotificationService::AllSources());
223 registrar_.Add(this, chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED,
224 content::NotificationService::AllSources());
225 registrar_.Add(this,
226 chrome::NOTIFICATION_PROFILE_CREATED,
227 content::NotificationService::AllSources());
228 RetrieveTrustedDevicePolicies();
229 local_accounts_subscription_ = cros_settings_->AddSettingsObserver(
230 kAccountsPrefDeviceLocalAccounts,
231 base::Bind(&UserManagerImpl::RetrieveTrustedDevicePolicies,
232 base::Unretained(this)));
233 supervised_users_subscription_ = cros_settings_->AddSettingsObserver(
234 kAccountsPrefSupervisedUsersEnabled,
235 base::Bind(&UserManagerImpl::RetrieveTrustedDevicePolicies,
236 base::Unretained(this)));
237 multi_profile_user_controller_.reset(new MultiProfileUserController(
238 this, g_browser_process->local_state()));
239
240 policy::BrowserPolicyConnectorChromeOS* connector =
241 g_browser_process->platform_part()->browser_policy_connector_chromeos();
242 avatar_policy_observer_.reset(new policy::CloudExternalDataPolicyObserver(
243 cros_settings_,
244 this,
245 connector->GetDeviceLocalAccountPolicyService(),
246 policy::key::kUserAvatarImage,
247 this));
248 avatar_policy_observer_->Init();
249
250 wallpaper_policy_observer_.reset(new policy::CloudExternalDataPolicyObserver(
251 cros_settings_,
252 this,
253 connector->GetDeviceLocalAccountPolicyService(),
254 policy::key::kWallpaperImage,
255 this));
256 wallpaper_policy_observer_->Init();
257
258 UpdateLoginState();
259 }
260
261 UserManagerImpl::~UserManagerImpl() {
262 // Can't use STLDeleteElements because of the private destructor of User.
263 for (UserList::iterator it = users_.begin(); it != users_.end();
264 it = users_.erase(it)) {
265 DeleteUser(*it);
266 }
267 // These are pointers to the same User instances that were in users_ list.
268 logged_in_users_.clear();
269 lru_logged_in_users_.clear();
270
271 DeleteUser(active_user_);
272 }
273
274 void UserManagerImpl::Shutdown() {
275 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
276 local_accounts_subscription_.reset();
277 supervised_users_subscription_.reset();
278 // Stop the session length limiter.
279 session_length_limiter_.reset();
280
281 if (device_local_account_policy_service_)
282 device_local_account_policy_service_->RemoveObserver(this);
283
284 for (UserImageManagerMap::iterator it = user_image_managers_.begin(),
285 ie = user_image_managers_.end();
286 it != ie; ++it) {
287 it->second->Shutdown();
288 }
289 multi_profile_user_controller_.reset();
290 avatar_policy_observer_.reset();
291 wallpaper_policy_observer_.reset();
292 registrar_.RemoveAll();
293 }
294
295 MultiProfileUserController* UserManagerImpl::GetMultiProfileUserController() {
296 return multi_profile_user_controller_.get();
297 }
298
299 UserImageManager* UserManagerImpl::GetUserImageManager(
300 const std::string& user_id) {
301 UserImageManagerMap::iterator ui = user_image_managers_.find(user_id);
302 if (ui != user_image_managers_.end())
303 return ui->second.get();
304 linked_ptr<UserImageManagerImpl> mgr(new UserImageManagerImpl(user_id, this));
305 user_image_managers_[user_id] = mgr;
306 return mgr.get();
307 }
308
309 SupervisedUserManager* UserManagerImpl::GetSupervisedUserManager() {
310 return supervised_user_manager_.get();
311 }
312
313 const UserList& UserManagerImpl::GetUsers() const {
314 const_cast<UserManagerImpl*>(this)->EnsureUsersLoaded();
315 return users_;
316 }
317
318 UserList UserManagerImpl::GetUsersAdmittedForMultiProfile() const {
319 // Supervised users are not allowed to use multi profile.
320 if (logged_in_users_.size() == 1 &&
321 GetPrimaryUser()->GetType() != User::USER_TYPE_REGULAR)
322 return UserList();
323
324 UserList result;
325 int num_users_allowed = 0;
326 const UserList& users = GetUsers();
327 for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) {
328 if ((*it)->GetType() == User::USER_TYPE_REGULAR && !(*it)->is_logged_in()) {
329 MultiProfileUserController::UserAllowedInSessionResult check =
330 multi_profile_user_controller_->
331 IsUserAllowedInSession((*it)->email());
332 if (check == MultiProfileUserController::
333 NOT_ALLOWED_PRIMARY_USER_POLICY_FORBIDS) {
334 return UserList();
335 }
336
337 // Users with a policy that prevents them being added to a session will be
338 // shown in login UI but will be grayed out.
339 if (check == MultiProfileUserController::ALLOWED ||
340 check == MultiProfileUserController::NOT_ALLOWED_POLICY_FORBIDS) {
341 result.push_back(*it);
342 if (check == MultiProfileUserController::ALLOWED)
343 num_users_allowed++;
344 }
345 }
346 }
347
348 // We only show multi-profiles sign in UI if there's at least one user that
349 // is allowed to be added to the session.
350 if (!num_users_allowed)
351 result.clear();
352
353 return result;
354 }
355
356 const UserList& UserManagerImpl::GetLoggedInUsers() const {
357 return logged_in_users_;
358 }
359
360 const UserList& UserManagerImpl::GetLRULoggedInUsers() {
361 // If there is no user logged in, we return the active user as the only one.
362 if (lru_logged_in_users_.empty() && active_user_) {
363 temp_single_logged_in_users_.clear();
364 temp_single_logged_in_users_.insert(temp_single_logged_in_users_.begin(),
365 active_user_);
366 return temp_single_logged_in_users_;
367 }
368 return lru_logged_in_users_;
369 }
370
371 UserList UserManagerImpl::GetUnlockUsers() const {
372 const UserList& logged_in_users = GetLoggedInUsers();
373 if (logged_in_users.empty())
374 return UserList();
375
376 UserList unlock_users;
377 Profile* profile = GetProfileByUser(primary_user_);
378 std::string primary_behavior =
379 profile->GetPrefs()->GetString(prefs::kMultiProfileUserBehavior);
380
381 // Specific case: only one logged in user or
382 // primary user has primary-only multi-profile policy.
383 if (logged_in_users.size() == 1 ||
384 primary_behavior == MultiProfileUserController::kBehaviorPrimaryOnly) {
385 if (primary_user_->can_lock())
386 unlock_users.push_back(primary_user_);
387 } else {
388 // Fill list of potential unlock users based on multi-profile policy state.
389 for (UserList::const_iterator it = logged_in_users.begin();
390 it != logged_in_users.end(); ++it) {
391 User* user = (*it);
392 Profile* profile = GetProfileByUser(user);
393 const std::string behavior =
394 profile->GetPrefs()->GetString(prefs::kMultiProfileUserBehavior);
395 if (behavior == MultiProfileUserController::kBehaviorUnrestricted &&
396 user->can_lock()) {
397 unlock_users.push_back(user);
398 } else if (behavior == MultiProfileUserController::kBehaviorPrimaryOnly) {
399 NOTREACHED()
400 << "Spotted primary-only multi-profile policy for non-primary user";
401 }
402 }
403 }
404
405 return unlock_users;
406 }
407
408 const std::string& UserManagerImpl::GetOwnerEmail() {
409 return owner_email_;
410 }
411
412 void UserManagerImpl::UserLoggedIn(const std::string& user_id,
413 const std::string& username_hash,
414 bool browser_restart) {
415 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
416
417 User* user = FindUserInListAndModify(user_id);
418 if (active_user_ && user) {
419 user->set_is_logged_in(true);
420 user->set_username_hash(username_hash);
421 logged_in_users_.push_back(user);
422 lru_logged_in_users_.push_back(user);
423 // Reset the new user flag if the user already exists.
424 is_current_user_new_ = false;
425 NotifyUserAddedToSession(user);
426 // Remember that we need to switch to this user as soon as profile ready.
427 pending_user_switch_ = user_id;
428 return;
429 }
430
431 policy::DeviceLocalAccount::Type device_local_account_type;
432 if (user_id == UserManager::kGuestUserName) {
433 GuestUserLoggedIn();
434 } else if (user_id == UserManager::kRetailModeUserName) {
435 RetailModeUserLoggedIn();
436 } else if (policy::IsDeviceLocalAccountUser(user_id,
437 &device_local_account_type) &&
438 device_local_account_type ==
439 policy::DeviceLocalAccount::TYPE_KIOSK_APP) {
440 KioskAppLoggedIn(user_id);
441 } else if (DemoAppLauncher::IsDemoAppSession(user_id)) {
442 DemoAccountLoggedIn();
443 } else {
444 EnsureUsersLoaded();
445
446 if (user && user->GetType() == User::USER_TYPE_PUBLIC_ACCOUNT) {
447 PublicAccountUserLoggedIn(user);
448 } else if ((user && user->GetType() == User::USER_TYPE_LOCALLY_MANAGED) ||
449 (!user && gaia::ExtractDomainName(user_id) ==
450 UserManager::kLocallyManagedUserDomain)) {
451 LocallyManagedUserLoggedIn(user_id);
452 } else if (browser_restart && user_id == g_browser_process->local_state()->
453 GetString(kPublicAccountPendingDataRemoval)) {
454 PublicAccountUserLoggedIn(User::CreatePublicAccountUser(user_id));
455 } else if (user_id != owner_email_ && !user &&
456 (AreEphemeralUsersEnabled() || browser_restart)) {
457 RegularUserLoggedInAsEphemeral(user_id);
458 } else {
459 RegularUserLoggedIn(user_id);
460 }
461
462 // Initialize the session length limiter and start it only if
463 // session limit is defined by the policy.
464 session_length_limiter_.reset(new SessionLengthLimiter(NULL,
465 browser_restart));
466 }
467 DCHECK(active_user_);
468 active_user_->set_is_logged_in(true);
469 active_user_->set_is_active(true);
470 active_user_->set_username_hash(username_hash);
471
472 // Place user who just signed in to the top of the logged in users.
473 logged_in_users_.insert(logged_in_users_.begin(), active_user_);
474 SetLRUUser(active_user_);
475
476 if (!primary_user_) {
477 primary_user_ = active_user_;
478 if (primary_user_->GetType() == User::USER_TYPE_REGULAR)
479 SendRegularUserLoginMetrics(user_id);
480 }
481
482 UMA_HISTOGRAM_ENUMERATION("UserManager.LoginUserType",
483 active_user_->GetType(), User::NUM_USER_TYPES);
484
485 g_browser_process->local_state()->SetString(kLastLoggedInRegularUser,
486 (active_user_->GetType() == User::USER_TYPE_REGULAR) ? user_id : "");
487
488 NotifyOnLogin();
489 }
490
491 void UserManagerImpl::SwitchActiveUser(const std::string& user_id) {
492 User* user = FindUserAndModify(user_id);
493 if (!user) {
494 NOTREACHED() << "Switching to a non-existing user";
495 return;
496 }
497 if (user == active_user_) {
498 NOTREACHED() << "Switching to a user who is already active";
499 return;
500 }
501 if (!user->is_logged_in()) {
502 NOTREACHED() << "Switching to a user that is not logged in";
503 return;
504 }
505 if (user->GetType() != User::USER_TYPE_REGULAR) {
506 NOTREACHED() << "Switching to a non-regular user";
507 return;
508 }
509 if (user->username_hash().empty()) {
510 NOTREACHED() << "Switching to a user that doesn't have username_hash set";
511 return;
512 }
513
514 DCHECK(active_user_);
515 active_user_->set_is_active(false);
516 user->set_is_active(true);
517 active_user_ = user;
518
519 // Move the user to the front.
520 SetLRUUser(active_user_);
521
522 NotifyActiveUserHashChanged(active_user_->username_hash());
523 NotifyActiveUserChanged(active_user_);
524 }
525
526 void UserManagerImpl::RestoreActiveSessions() {
527 DBusThreadManager::Get()->GetSessionManagerClient()->RetrieveActiveSessions(
528 base::Bind(&UserManagerImpl::OnRestoreActiveSessions,
529 base::Unretained(this)));
530 }
531
532 void UserManagerImpl::SessionStarted() {
533 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
534 session_started_ = true;
535 UpdateLoginState();
536 content::NotificationService::current()->Notify(
537 chrome::NOTIFICATION_SESSION_STARTED,
538 content::Source<UserManager>(this),
539 content::Details<const User>(active_user_));
540 if (is_current_user_new_) {
541 // Make sure that the new user's data is persisted to Local State.
542 g_browser_process->local_state()->CommitPendingWrite();
543 }
544 }
545
546 void UserManagerImpl::RemoveUser(const std::string& user_id,
547 RemoveUserDelegate* delegate) {
548 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
549
550 const User* user = FindUser(user_id);
551 if (!user || (user->GetType() != User::USER_TYPE_REGULAR &&
552 user->GetType() != User::USER_TYPE_LOCALLY_MANAGED))
553 return;
554
555 // Sanity check: we must not remove single user unless it's an enterprise
556 // device. This check may seem redundant at a first sight because
557 // this single user must be an owner and we perform special check later
558 // in order not to remove an owner. However due to non-instant nature of
559 // ownership assignment this later check may sometimes fail.
560 // See http://crosbug.com/12723
561 policy::BrowserPolicyConnectorChromeOS* connector =
562 g_browser_process->platform_part()
563 ->browser_policy_connector_chromeos();
564 if (users_.size() < 2 && !connector->IsEnterpriseManaged())
565 return;
566
567 // Sanity check: do not allow any of the the logged in users to be removed.
568 for (UserList::const_iterator it = logged_in_users_.begin();
569 it != logged_in_users_.end(); ++it) {
570 if ((*it)->email() == user_id)
571 return;
572 }
573
574 RemoveUserInternal(user_id, delegate);
575 }
576
577 void UserManagerImpl::RemoveUserInternal(const std::string& user_email,
578 RemoveUserDelegate* delegate) {
579 CrosSettings* cros_settings = CrosSettings::Get();
580
581 // Ensure the value of owner email has been fetched.
582 if (CrosSettingsProvider::TRUSTED != cros_settings->PrepareTrustedValues(
583 base::Bind(&UserManagerImpl::RemoveUserInternal,
584 base::Unretained(this),
585 user_email, delegate))) {
586 // Value of owner email is not fetched yet. RemoveUserInternal will be
587 // called again after fetch completion.
588 return;
589 }
590 std::string owner;
591 cros_settings->GetString(kDeviceOwner, &owner);
592 if (user_email == owner) {
593 // Owner is not allowed to be removed from the device.
594 return;
595 }
596 RemoveNonOwnerUserInternal(user_email, delegate);
597 }
598
599 void UserManagerImpl::RemoveNonOwnerUserInternal(const std::string& user_email,
600 RemoveUserDelegate* delegate) {
601 if (delegate)
602 delegate->OnBeforeUserRemoved(user_email);
603 RemoveUserFromList(user_email);
604 cryptohome::AsyncMethodCaller::GetInstance()->AsyncRemove(
605 user_email, base::Bind(&OnRemoveUserComplete, user_email));
606
607 if (delegate)
608 delegate->OnUserRemoved(user_email);
609 }
610
611 void UserManagerImpl::RemoveUserFromList(const std::string& user_id) {
612 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
613 RemoveNonCryptohomeData(user_id);
614 if (user_loading_stage_ == STAGE_LOADED) {
615 DeleteUser(RemoveRegularOrLocallyManagedUserFromList(user_id));
616 } else if (user_loading_stage_ == STAGE_LOADING) {
617 DCHECK(gaia::ExtractDomainName(user_id) ==
618 UserManager::kLocallyManagedUserDomain);
619 // Special case, removing partially-constructed supervised user during user
620 // list loading.
621 ListPrefUpdate users_update(g_browser_process->local_state(),
622 kRegularUsers);
623 users_update->Remove(base::StringValue(user_id), NULL);
624 } else {
625 NOTREACHED() << "Users are not loaded yet.";
626 return;
627 }
628 // Make sure that new data is persisted to Local State.
629 g_browser_process->local_state()->CommitPendingWrite();
630 }
631
632 bool UserManagerImpl::IsKnownUser(const std::string& user_id) const {
633 return FindUser(user_id) != NULL;
634 }
635
636 const User* UserManagerImpl::FindUser(const std::string& user_id) const {
637 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
638 if (active_user_ && active_user_->email() == user_id)
639 return active_user_;
640 return FindUserInList(user_id);
641 }
642
643 User* UserManagerImpl::FindUserAndModify(const std::string& user_id) {
644 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
645 if (active_user_ && active_user_->email() == user_id)
646 return active_user_;
647 return FindUserInListAndModify(user_id);
648 }
649
650 const User* UserManagerImpl::GetLoggedInUser() const {
651 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
652 return active_user_;
653 }
654
655 User* UserManagerImpl::GetLoggedInUser() {
656 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
657 return active_user_;
658 }
659
660 const User* UserManagerImpl::GetActiveUser() const {
661 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
662 return active_user_;
663 }
664
665 User* UserManagerImpl::GetActiveUser() {
666 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
667 return active_user_;
668 }
669
670 const User* UserManagerImpl::GetPrimaryUser() const {
671 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
672 return primary_user_;
673 }
674
675 User* UserManagerImpl::GetUserByProfile(Profile* profile) const {
676 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
677 if (ProfileHelper::IsSigninProfile(profile))
678 return NULL;
679
680 // Special case for non-CrOS tests that do create several profiles
681 // and don't really care about mapping to the real user.
682 // Without multi-profiles on Chrome OS such tests always got active_user_.
683 // Now these tests will specify special flag to continue working.
684 // In future those tests can get a proper CrOS configuration i.e. register
685 // and login several users if they want to work with an additional profile.
686 if (CommandLine::ForCurrentProcess()->HasSwitch(
687 switches::kIgnoreUserProfileMappingForTests)) {
688 return active_user_;
689 }
690
691 const std::string username_hash =
692 ProfileHelper::GetUserIdHashFromProfile(profile);
693 const UserList& users = GetUsers();
694 const UserList::const_iterator pos = std::find_if(
695 users.begin(), users.end(), UserHashMatcher(username_hash));
696 if (pos != users.end())
697 return *pos;
698
699 // Many tests do not have their users registered with UserManager and
700 // runs here. If |active_user_| matches |profile|, returns it.
701 return active_user_ &&
702 ProfileHelper::GetProfilePathByUserIdHash(
703 active_user_->username_hash()) == profile->GetPath()
704 ? active_user_
705 : NULL;
706 }
707
708 Profile* UserManagerImpl::GetProfileByUser(const User* user) const {
709 Profile* profile = NULL;
710 if (user->is_profile_created())
711 profile = ProfileHelper::GetProfileByUserIdHash(user->username_hash());
712 else
713 profile = ProfileManager::GetActiveUserProfile();
714
715 // GetActiveUserProfile() or GetProfileByUserIdHash() returns a new instance
716 // of ProfileImpl(), but actually its OffTheRecordProfile() should be used.
717 if (profile && IsLoggedInAsGuest())
718 profile = profile->GetOffTheRecordProfile();
719 return profile;
720 }
721
722 void UserManagerImpl::SaveUserOAuthStatus(
723 const std::string& user_id,
724 User::OAuthTokenStatus oauth_token_status) {
725 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
726
727 DVLOG(1) << "Saving user OAuth token status in Local State";
728 User* user = FindUserAndModify(user_id);
729 if (user)
730 user->set_oauth_token_status(oauth_token_status);
731
732 GetUserFlow(user_id)->HandleOAuthTokenStatusChange(oauth_token_status);
733
734 // Do not update local state if data stored or cached outside the user's
735 // cryptohome is to be treated as ephemeral.
736 if (IsUserNonCryptohomeDataEphemeral(user_id))
737 return;
738
739 PrefService* local_state = g_browser_process->local_state();
740
741 DictionaryPrefUpdate oauth_status_update(local_state, kUserOAuthTokenStatus);
742 oauth_status_update->SetWithoutPathExpansion(user_id,
743 new base::FundamentalValue(static_cast<int>(oauth_token_status)));
744 }
745
746 void UserManagerImpl::SaveForceOnlineSignin(const std::string& user_id,
747 bool force_online_signin) {
748 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
749
750 // Do not update local state if data stored or cached outside the user's
751 // cryptohome is to be treated as ephemeral.
752 if (IsUserNonCryptohomeDataEphemeral(user_id))
753 return;
754
755 DictionaryPrefUpdate force_online_update(g_browser_process->local_state(),
756 kUserForceOnlineSignin);
757 force_online_update->SetBooleanWithoutPathExpansion(user_id,
758 force_online_signin);
759 }
760
761 void UserManagerImpl::SaveUserDisplayName(const std::string& user_id,
762 const base::string16& display_name) {
763 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
764
765 if (User* user = FindUserAndModify(user_id)) {
766 user->set_display_name(display_name);
767
768 // Do not update local state if data stored or cached outside the user's
769 // cryptohome is to be treated as ephemeral.
770 if (!IsUserNonCryptohomeDataEphemeral(user_id)) {
771 PrefService* local_state = g_browser_process->local_state();
772
773 DictionaryPrefUpdate display_name_update(local_state, kUserDisplayName);
774 display_name_update->SetWithoutPathExpansion(
775 user_id,
776 new base::StringValue(display_name));
777
778 supervised_user_manager_->UpdateManagerName(user_id, display_name);
779 }
780 }
781 }
782
783 base::string16 UserManagerImpl::GetUserDisplayName(
784 const std::string& user_id) const {
785 const User* user = FindUser(user_id);
786 return user ? user->display_name() : base::string16();
787 }
788
789 void UserManagerImpl::SaveUserDisplayEmail(const std::string& user_id,
790 const std::string& display_email) {
791 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
792
793 User* user = FindUserAndModify(user_id);
794 if (!user)
795 return; // Ignore if there is no such user.
796
797 user->set_display_email(display_email);
798
799 // Do not update local state if data stored or cached outside the user's
800 // cryptohome is to be treated as ephemeral.
801 if (IsUserNonCryptohomeDataEphemeral(user_id))
802 return;
803
804 PrefService* local_state = g_browser_process->local_state();
805
806 DictionaryPrefUpdate display_email_update(local_state, kUserDisplayEmail);
807 display_email_update->SetWithoutPathExpansion(
808 user_id,
809 new base::StringValue(display_email));
810 }
811
812 std::string UserManagerImpl::GetUserDisplayEmail(
813 const std::string& user_id) const {
814 const User* user = FindUser(user_id);
815 return user ? user->display_email() : user_id;
816 }
817
818 void UserManagerImpl::UpdateUserAccountData(
819 const std::string& user_id,
820 const UserAccountData& account_data) {
821 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
822
823 SaveUserDisplayName(user_id, account_data.display_name());
824
825 if (User* user = FindUserAndModify(user_id)) {
826 base::string16 given_name = account_data.given_name();
827 user->set_given_name(given_name);
828 if (!IsUserNonCryptohomeDataEphemeral(user_id)) {
829 PrefService* local_state = g_browser_process->local_state();
830
831 DictionaryPrefUpdate given_name_update(local_state, kUserGivenName);
832 given_name_update->SetWithoutPathExpansion(
833 user_id,
834 new base::StringValue(given_name));
835 }
836 }
837
838 UpdateUserAccountLocale(user_id, account_data.locale());
839 }
840
841 // TODO(alemate): http://crbug.com/288941 : Respect preferred language list in
842 // the Google user profile.
843 //
844 // Returns true if callback will be called.
845 bool UserManagerImpl::RespectLocalePreference(
846 Profile* profile,
847 const User* user,
848 scoped_ptr<locale_util::SwitchLanguageCallback> callback) const {
849 if (g_browser_process == NULL)
850 return false;
851 if ((user == NULL) || (user != GetPrimaryUser()) ||
852 (!user->is_profile_created()))
853 return false;
854
855 // In case of Multi Profile mode we don't apply profile locale because it is
856 // unsafe.
857 if (GetLoggedInUsers().size() != 1)
858 return false;
859 const PrefService* prefs = profile->GetPrefs();
860 if (prefs == NULL)
861 return false;
862
863 std::string pref_locale;
864 const std::string pref_app_locale =
865 prefs->GetString(prefs::kApplicationLocale);
866 const std::string pref_bkup_locale =
867 prefs->GetString(prefs::kApplicationLocaleBackup);
868
869 pref_locale = pref_app_locale;
870 if (pref_locale.empty())
871 pref_locale = pref_bkup_locale;
872
873 const std::string* account_locale = NULL;
874 if (pref_locale.empty() && user->has_gaia_account()) {
875 if (user->GetAccountLocale() == NULL)
876 return false; // wait until Account profile is loaded.
877 account_locale = user->GetAccountLocale();
878 pref_locale = *account_locale;
879 }
880 const std::string global_app_locale =
881 g_browser_process->GetApplicationLocale();
882 if (pref_locale.empty())
883 pref_locale = global_app_locale;
884 DCHECK(!pref_locale.empty());
885 LOG(WARNING) << "RespectLocalePreference: "
886 << "app_locale='" << pref_app_locale << "', "
887 << "bkup_locale='" << pref_bkup_locale << "', "
888 << (account_locale != NULL
889 ? (std::string("account_locale='") + (*account_locale) +
890 "'. ")
891 : (std::string("account_locale - unused. ")))
892 << " Selected '" << pref_locale << "'";
893 profile->ChangeAppLocale(pref_locale, Profile::APP_LOCALE_CHANGED_VIA_LOGIN);
894
895 // Here we don't enable keyboard layouts for normal users. Input methods
896 // are set up when the user first logs in. Then the user may customize the
897 // input methods. Hence changing input methods here, just because the user's
898 // UI language is different from the login screen UI language, is not
899 // desirable. Note that input method preferences are synced, so users can use
900 // their farovite input methods as soon as the preferences are synced.
901 //
902 // For Guest mode, user locale preferences will never get initialized.
903 // So input methods should be enabled somewhere.
904 const bool enable_layouts = UserManager::Get()->IsLoggedInAsGuest();
905 locale_util::SwitchLanguage(pref_locale,
906 enable_layouts,
907 false /* login_layouts_only */,
908 callback.Pass());
909
910 return true;
911 }
912
913 void UserManagerImpl::StopPolicyObserverForTesting() {
914 avatar_policy_observer_.reset();
915 wallpaper_policy_observer_.reset();
916 }
917
918 void UserManagerImpl::Observe(int type,
919 const content::NotificationSource& source,
920 const content::NotificationDetails& details) {
921 switch (type) {
922 case chrome::NOTIFICATION_OWNERSHIP_STATUS_CHANGED:
923 if (!device_local_account_policy_service_) {
924 policy::BrowserPolicyConnectorChromeOS* connector =
925 g_browser_process->platform_part()
926 ->browser_policy_connector_chromeos();
927 device_local_account_policy_service_ =
928 connector->GetDeviceLocalAccountPolicyService();
929 if (device_local_account_policy_service_)
930 device_local_account_policy_service_->AddObserver(this);
931 }
932 RetrieveTrustedDevicePolicies();
933 UpdateOwnership();
934 break;
935 case chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED: {
936 Profile* profile = content::Details<Profile>(details).ptr();
937 if (IsUserLoggedIn() &&
938 !IsLoggedInAsGuest() &&
939 !IsLoggedInAsKioskApp()) {
940 if (IsLoggedInAsLocallyManagedUser())
941 ManagedUserPasswordServiceFactory::GetForProfile(profile);
942 if (IsLoggedInAsRegularUser())
943 ManagerPasswordServiceFactory::GetForProfile(profile);
944
945 if (!profile->IsOffTheRecord()) {
946 AuthSyncObserver* sync_observer =
947 AuthSyncObserverFactory::GetInstance()->GetForProfile(profile);
948 sync_observer->StartObserving();
949 multi_profile_user_controller_->StartObserving(profile);
950 }
951 }
952
953 // Now that the user profile has been initialized and
954 // |GetNSSCertDatabaseForProfile| is safe to be used, get the NSS cert
955 // database for the primary user and start certificate loader with it.
956 if (IsUserLoggedIn() &&
957 GetPrimaryUser() &&
958 profile == GetProfileByUser(GetPrimaryUser()) &&
959 CertLoader::IsInitialized() &&
960 base::SysInfo::IsRunningOnChromeOS()) {
961 GetNSSCertDatabaseForProfile(profile,
962 base::Bind(&OnGetNSSCertDatabaseForUser));
963 }
964 break;
965 }
966 case chrome::NOTIFICATION_PROFILE_CREATED: {
967 Profile* profile = content::Source<Profile>(source).ptr();
968 User* user = GetUserByProfile(profile);
969 if (user != NULL)
970 user->set_profile_is_created();
971 // If there is pending user switch, do it now.
972 if (!pending_user_switch_.empty()) {
973 // Call SwitchActiveUser async because otherwise it may cause
974 // ProfileManager::GetProfile before the profile gets registered
975 // in ProfileManager. It happens in case of sync profile load when
976 // NOTIFICATION_PROFILE_CREATED is called synchronously.
977 base::MessageLoop::current()->PostTask(FROM_HERE,
978 base::Bind(&UserManagerImpl::SwitchActiveUser,
979 base::Unretained(this),
980 pending_user_switch_));
981 pending_user_switch_.clear();
982 }
983 break;
984 }
985 default:
986 NOTREACHED();
987 }
988 }
989
990 void UserManagerImpl::OnExternalDataSet(const std::string& policy,
991 const std::string& user_id) {
992 if (policy == policy::key::kUserAvatarImage)
993 GetUserImageManager(user_id)->OnExternalDataSet(policy);
994 else if (policy == policy::key::kWallpaperImage)
995 WallpaperManager::Get()->OnPolicySet(policy, user_id);
996 else
997 NOTREACHED();
998 }
999
1000 void UserManagerImpl::OnExternalDataCleared(const std::string& policy,
1001 const std::string& user_id) {
1002 if (policy == policy::key::kUserAvatarImage)
1003 GetUserImageManager(user_id)->OnExternalDataCleared(policy);
1004 else if (policy == policy::key::kWallpaperImage)
1005 WallpaperManager::Get()->OnPolicyCleared(policy, user_id);
1006 else
1007 NOTREACHED();
1008 }
1009
1010 void UserManagerImpl::OnExternalDataFetched(const std::string& policy,
1011 const std::string& user_id,
1012 scoped_ptr<std::string> data) {
1013 if (policy == policy::key::kUserAvatarImage)
1014 GetUserImageManager(user_id)->OnExternalDataFetched(policy, data.Pass());
1015 else if (policy == policy::key::kWallpaperImage)
1016 WallpaperManager::Get()->OnPolicyFetched(policy, user_id, data.Pass());
1017 else
1018 NOTREACHED();
1019 }
1020
1021 void UserManagerImpl::OnPolicyUpdated(const std::string& user_id) {
1022 UpdatePublicAccountDisplayName(user_id);
1023 NotifyUserListChanged();
1024 }
1025
1026 void UserManagerImpl::OnDeviceLocalAccountsChanged() {
1027 // No action needed here, changes to the list of device-local accounts get
1028 // handled via the kAccountsPrefDeviceLocalAccounts device setting observer.
1029 }
1030
1031 bool UserManagerImpl::IsCurrentUserOwner() const {
1032 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1033 base::AutoLock lk(is_current_user_owner_lock_);
1034 return is_current_user_owner_;
1035 }
1036
1037 void UserManagerImpl::SetCurrentUserIsOwner(bool is_current_user_owner) {
1038 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1039 {
1040 base::AutoLock lk(is_current_user_owner_lock_);
1041 is_current_user_owner_ = is_current_user_owner;
1042 }
1043 UpdateLoginState();
1044 }
1045
1046 bool UserManagerImpl::IsCurrentUserNew() const {
1047 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1048 return is_current_user_new_;
1049 }
1050
1051 bool UserManagerImpl::IsCurrentUserNonCryptohomeDataEphemeral() const {
1052 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1053 return IsUserLoggedIn() &&
1054 IsUserNonCryptohomeDataEphemeral(GetLoggedInUser()->email());
1055 }
1056
1057 bool UserManagerImpl::CanCurrentUserLock() const {
1058 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1059 return IsUserLoggedIn() && active_user_->can_lock() &&
1060 GetCurrentUserFlow()->CanLockScreen();
1061 }
1062
1063 bool UserManagerImpl::IsUserLoggedIn() const {
1064 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1065 return active_user_;
1066 }
1067
1068 bool UserManagerImpl::IsLoggedInAsRegularUser() const {
1069 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1070 return IsUserLoggedIn() &&
1071 active_user_->GetType() == User::USER_TYPE_REGULAR;
1072 }
1073
1074 bool UserManagerImpl::IsLoggedInAsDemoUser() const {
1075 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1076 return IsUserLoggedIn() &&
1077 active_user_->GetType() == User::USER_TYPE_RETAIL_MODE;
1078 }
1079
1080 bool UserManagerImpl::IsLoggedInAsPublicAccount() const {
1081 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1082 return IsUserLoggedIn() &&
1083 active_user_->GetType() == User::USER_TYPE_PUBLIC_ACCOUNT;
1084 }
1085
1086 bool UserManagerImpl::IsLoggedInAsGuest() const {
1087 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1088 return IsUserLoggedIn() &&
1089 active_user_->GetType() == User::USER_TYPE_GUEST;
1090 }
1091
1092 bool UserManagerImpl::IsLoggedInAsLocallyManagedUser() const {
1093 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1094 return IsUserLoggedIn() &&
1095 active_user_->GetType() == User::USER_TYPE_LOCALLY_MANAGED;
1096 }
1097
1098 bool UserManagerImpl::IsLoggedInAsKioskApp() const {
1099 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1100 return IsUserLoggedIn() &&
1101 active_user_->GetType() == User::USER_TYPE_KIOSK_APP;
1102 }
1103
1104 bool UserManagerImpl::IsLoggedInAsStub() const {
1105 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1106 return IsUserLoggedIn() && active_user_->email() == kStubUser;
1107 }
1108
1109 bool UserManagerImpl::IsSessionStarted() const {
1110 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1111 return session_started_;
1112 }
1113
1114 bool UserManagerImpl::UserSessionsRestored() const {
1115 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1116 return user_sessions_restored_;
1117 }
1118
1119 bool UserManagerImpl::HasBrowserRestarted() const {
1120 CommandLine* command_line = CommandLine::ForCurrentProcess();
1121 return base::SysInfo::IsRunningOnChromeOS() &&
1122 command_line->HasSwitch(switches::kLoginUser) &&
1123 !command_line->HasSwitch(switches::kLoginPassword);
1124 }
1125
1126 bool UserManagerImpl::IsUserNonCryptohomeDataEphemeral(
1127 const std::string& user_id) const {
1128 // Data belonging to the guest, retail mode and stub users is always
1129 // ephemeral.
1130 if (user_id == UserManager::kGuestUserName ||
1131 user_id == UserManager::kRetailModeUserName ||
1132 user_id == kStubUser) {
1133 return true;
1134 }
1135
1136 // Data belonging to the owner, anyone found on the user list and obsolete
1137 // public accounts whose data has not been removed yet is not ephemeral.
1138 if (user_id == owner_email_ || UserExistsInList(user_id) ||
1139 user_id == g_browser_process->local_state()->
1140 GetString(kPublicAccountPendingDataRemoval)) {
1141 return false;
1142 }
1143
1144 // Data belonging to the currently logged-in user is ephemeral when:
1145 // a) The user logged into a regular account while the ephemeral users policy
1146 // was enabled.
1147 // - or -
1148 // b) The user logged into any other account type.
1149 if (IsUserLoggedIn() && (user_id == GetLoggedInUser()->email()) &&
1150 (is_current_user_ephemeral_regular_user_ || !IsLoggedInAsRegularUser())) {
1151 return true;
1152 }
1153
1154 // Data belonging to any other user is ephemeral when:
1155 // a) Going through the regular login flow and the ephemeral users policy is
1156 // enabled.
1157 // - or -
1158 // b) The browser is restarting after a crash.
1159 return AreEphemeralUsersEnabled() || HasBrowserRestarted();
1160 }
1161
1162 void UserManagerImpl::AddObserver(UserManager::Observer* obs) {
1163 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1164 observer_list_.AddObserver(obs);
1165 }
1166
1167 void UserManagerImpl::RemoveObserver(UserManager::Observer* obs) {
1168 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1169 observer_list_.RemoveObserver(obs);
1170 }
1171
1172 void UserManagerImpl::AddSessionStateObserver(
1173 UserManager::UserSessionStateObserver* obs) {
1174 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1175 session_state_observer_list_.AddObserver(obs);
1176 }
1177
1178 void UserManagerImpl::RemoveSessionStateObserver(
1179 UserManager::UserSessionStateObserver* obs) {
1180 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1181 session_state_observer_list_.RemoveObserver(obs);
1182 }
1183
1184 void UserManagerImpl::NotifyLocalStateChanged() {
1185 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1186 FOR_EACH_OBSERVER(UserManager::Observer, observer_list_,
1187 LocalStateChanged(this));
1188 }
1189
1190 void UserManagerImpl::OnProfilePrepared(Profile* profile) {
1191 LoginUtils::Get()->DoBrowserLaunch(profile,
1192 NULL); // host_, not needed here
1193
1194 if (!CommandLine::ForCurrentProcess()->HasSwitch(::switches::kTestName)) {
1195 // Did not log in (we crashed or are debugging), need to restore Sync.
1196 // TODO(nkostylev): Make sure that OAuth state is restored correctly for all
1197 // users once it is fully multi-profile aware. http://crbug.com/238987
1198 // For now if we have other user pending sessions they'll override OAuth
1199 // session restore for previous users.
1200 LoginUtils::Get()->RestoreAuthenticationSession(profile);
1201 }
1202
1203 // Restore other user sessions if any.
1204 RestorePendingUserSessions();
1205 }
1206
1207 void UserManagerImpl::EnsureUsersLoaded() {
1208 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1209 if (!g_browser_process || !g_browser_process->local_state())
1210 return;
1211
1212 if (user_loading_stage_ != STAGE_NOT_LOADED)
1213 return;
1214 user_loading_stage_ = STAGE_LOADING;
1215 // Clean up user list first. All code down the path should be synchronous,
1216 // so that local state after transaction rollback is in consistent state.
1217 // This process also should not trigger EnsureUsersLoaded again.
1218 if (supervised_user_manager_->HasFailedUserCreationTransaction())
1219 supervised_user_manager_->RollbackUserCreationTransaction();
1220
1221 PrefService* local_state = g_browser_process->local_state();
1222 const base::ListValue* prefs_regular_users =
1223 local_state->GetList(kRegularUsers);
1224 const base::ListValue* prefs_public_sessions =
1225 local_state->GetList(kPublicAccounts);
1226 const base::DictionaryValue* prefs_display_names =
1227 local_state->GetDictionary(kUserDisplayName);
1228 const base::DictionaryValue* prefs_given_names =
1229 local_state->GetDictionary(kUserGivenName);
1230 const base::DictionaryValue* prefs_display_emails =
1231 local_state->GetDictionary(kUserDisplayEmail);
1232
1233 // Load public sessions first.
1234 std::vector<std::string> public_sessions;
1235 std::set<std::string> public_sessions_set;
1236 ParseUserList(*prefs_public_sessions, std::set<std::string>(),
1237 &public_sessions, &public_sessions_set);
1238 for (std::vector<std::string>::const_iterator it = public_sessions.begin();
1239 it != public_sessions.end(); ++it) {
1240 users_.push_back(User::CreatePublicAccountUser(*it));
1241 UpdatePublicAccountDisplayName(*it);
1242 }
1243
1244 // Load regular users and locally managed users.
1245 std::vector<std::string> regular_users;
1246 std::set<std::string> regular_users_set;
1247 ParseUserList(*prefs_regular_users, public_sessions_set,
1248 &regular_users, &regular_users_set);
1249 for (std::vector<std::string>::const_iterator it = regular_users.begin();
1250 it != regular_users.end(); ++it) {
1251 User* user = NULL;
1252 const std::string domain = gaia::ExtractDomainName(*it);
1253 if (domain == UserManager::kLocallyManagedUserDomain)
1254 user = User::CreateLocallyManagedUser(*it);
1255 else
1256 user = User::CreateRegularUser(*it);
1257 user->set_oauth_token_status(LoadUserOAuthStatus(*it));
1258 user->set_force_online_signin(LoadForceOnlineSignin(*it));
1259 users_.push_back(user);
1260
1261 base::string16 display_name;
1262 if (prefs_display_names->GetStringWithoutPathExpansion(*it,
1263 &display_name)) {
1264 user->set_display_name(display_name);
1265 }
1266
1267 base::string16 given_name;
1268 if (prefs_given_names->GetStringWithoutPathExpansion(*it, &given_name)) {
1269 user->set_given_name(given_name);
1270 }
1271
1272 std::string display_email;
1273 if (prefs_display_emails->GetStringWithoutPathExpansion(*it,
1274 &display_email)) {
1275 user->set_display_email(display_email);
1276 }
1277 }
1278
1279 user_loading_stage_ = STAGE_LOADED;
1280
1281 for (UserList::iterator ui = users_.begin(), ue = users_.end();
1282 ui != ue; ++ui) {
1283 GetUserImageManager((*ui)->email())->LoadUserImage();
1284 }
1285 }
1286
1287 void UserManagerImpl::RetrieveTrustedDevicePolicies() {
1288 ephemeral_users_enabled_ = false;
1289 owner_email_ = "";
1290
1291 // Schedule a callback if device policy has not yet been verified.
1292 if (CrosSettingsProvider::TRUSTED != cros_settings_->PrepareTrustedValues(
1293 base::Bind(&UserManagerImpl::RetrieveTrustedDevicePolicies,
1294 base::Unretained(this)))) {
1295 return;
1296 }
1297
1298 cros_settings_->GetBoolean(kAccountsPrefEphemeralUsersEnabled,
1299 &ephemeral_users_enabled_);
1300 cros_settings_->GetString(kDeviceOwner, &owner_email_);
1301
1302 EnsureUsersLoaded();
1303
1304 bool changed = UpdateAndCleanUpPublicAccounts(
1305 policy::GetDeviceLocalAccounts(cros_settings_));
1306
1307 // If ephemeral users are enabled and we are on the login screen, take this
1308 // opportunity to clean up by removing all regular users except the owner.
1309 if (ephemeral_users_enabled_ && !IsUserLoggedIn()) {
1310 ListPrefUpdate prefs_users_update(g_browser_process->local_state(),
1311 kRegularUsers);
1312 prefs_users_update->Clear();
1313 for (UserList::iterator it = users_.begin(); it != users_.end(); ) {
1314 const std::string user_email = (*it)->email();
1315 if ((*it)->GetType() == User::USER_TYPE_REGULAR &&
1316 user_email != owner_email_) {
1317 RemoveNonCryptohomeData(user_email);
1318 DeleteUser(*it);
1319 it = users_.erase(it);
1320 changed = true;
1321 } else {
1322 if ((*it)->GetType() != User::USER_TYPE_PUBLIC_ACCOUNT)
1323 prefs_users_update->Append(new base::StringValue(user_email));
1324 ++it;
1325 }
1326 }
1327 }
1328
1329 if (changed)
1330 NotifyUserListChanged();
1331 }
1332
1333 bool UserManagerImpl::AreEphemeralUsersEnabled() const {
1334 policy::BrowserPolicyConnectorChromeOS* connector =
1335 g_browser_process->platform_part()->browser_policy_connector_chromeos();
1336 return ephemeral_users_enabled_ &&
1337 (connector->IsEnterpriseManaged() || !owner_email_.empty());
1338 }
1339
1340 UserList& UserManagerImpl::GetUsersAndModify() {
1341 EnsureUsersLoaded();
1342 return users_;
1343 }
1344
1345 const User* UserManagerImpl::FindUserInList(const std::string& user_id) const {
1346 const UserList& users = GetUsers();
1347 for (UserList::const_iterator it = users.begin(); it != users.end(); ++it) {
1348 if ((*it)->email() == user_id)
1349 return *it;
1350 }
1351 return NULL;
1352 }
1353
1354 const bool UserManagerImpl::UserExistsInList(const std::string& user_id) const {
1355 PrefService* local_state = g_browser_process->local_state();
1356 const base::ListValue* user_list = local_state->GetList(kRegularUsers);
1357 for (size_t i = 0; i < user_list->GetSize(); ++i) {
1358 std::string email;
1359 if (user_list->GetString(i, &email) && (user_id == email))
1360 return true;
1361 }
1362 return false;
1363 }
1364
1365 User* UserManagerImpl::FindUserInListAndModify(const std::string& user_id) {
1366 UserList& users = GetUsersAndModify();
1367 for (UserList::iterator it = users.begin(); it != users.end(); ++it) {
1368 if ((*it)->email() == user_id)
1369 return *it;
1370 }
1371 return NULL;
1372 }
1373
1374 void UserManagerImpl::GuestUserLoggedIn() {
1375 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1376 active_user_ = User::CreateGuestUser();
1377 // TODO(nkostylev): Add support for passing guest session cryptohome
1378 // mount point. Legacy (--login-profile) value will be used for now.
1379 // http://crosbug.com/230859
1380 active_user_->SetStubImage(User::kInvalidImageIndex, false);
1381 // Initializes wallpaper after active_user_ is set.
1382 WallpaperManager::Get()->SetUserWallpaperNow(UserManager::kGuestUserName);
1383 }
1384
1385 void UserManagerImpl::AddUserRecord(User* user) {
1386 // Add the user to the front of the user list.
1387 ListPrefUpdate prefs_users_update(g_browser_process->local_state(),
1388 kRegularUsers);
1389 prefs_users_update->Insert(0, new base::StringValue(user->email()));
1390 users_.insert(users_.begin(), user);
1391 }
1392
1393 void UserManagerImpl::RegularUserLoggedIn(const std::string& user_id) {
1394 // Remove the user from the user list.
1395 active_user_ = RemoveRegularOrLocallyManagedUserFromList(user_id);
1396
1397 // If the user was not found on the user list, create a new user.
1398 is_current_user_new_ = !active_user_;
1399 if (!active_user_) {
1400 active_user_ = User::CreateRegularUser(user_id);
1401 active_user_->set_oauth_token_status(LoadUserOAuthStatus(user_id));
1402 SaveUserDisplayName(active_user_->email(),
1403 base::UTF8ToUTF16(active_user_->GetAccountName(true)));
1404 WallpaperManager::Get()->SetUserWallpaperNow(user_id);
1405 }
1406
1407 AddUserRecord(active_user_);
1408
1409 GetUserImageManager(user_id)->UserLoggedIn(is_current_user_new_, false);
1410
1411 WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded();
1412
1413 // Make sure that new data is persisted to Local State.
1414 g_browser_process->local_state()->CommitPendingWrite();
1415 }
1416
1417 void UserManagerImpl::RegularUserLoggedInAsEphemeral(
1418 const std::string& user_id) {
1419 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1420 is_current_user_new_ = true;
1421 is_current_user_ephemeral_regular_user_ = true;
1422 active_user_ = User::CreateRegularUser(user_id);
1423 GetUserImageManager(user_id)->UserLoggedIn(is_current_user_new_, false);
1424 WallpaperManager::Get()->SetUserWallpaperNow(user_id);
1425 }
1426
1427 void UserManagerImpl::LocallyManagedUserLoggedIn(
1428 const std::string& user_id) {
1429 // TODO(nkostylev): Refactor, share code with RegularUserLoggedIn().
1430
1431 // Remove the user from the user list.
1432 active_user_ = RemoveRegularOrLocallyManagedUserFromList(user_id);
1433 // If the user was not found on the user list, create a new user.
1434 if (!active_user_) {
1435 is_current_user_new_ = true;
1436 active_user_ = User::CreateLocallyManagedUser(user_id);
1437 // Leaving OAuth token status at the default state = unknown.
1438 WallpaperManager::Get()->SetUserWallpaperNow(user_id);
1439 } else {
1440 if (supervised_user_manager_->CheckForFirstRun(user_id)) {
1441 is_current_user_new_ = true;
1442 WallpaperManager::Get()->SetUserWallpaperNow(user_id);
1443 } else {
1444 is_current_user_new_ = false;
1445 }
1446 }
1447
1448 // Add the user to the front of the user list.
1449 ListPrefUpdate prefs_users_update(g_browser_process->local_state(),
1450 kRegularUsers);
1451 prefs_users_update->Insert(0, new base::StringValue(user_id));
1452 users_.insert(users_.begin(), active_user_);
1453
1454 // Now that user is in the list, save display name.
1455 if (is_current_user_new_) {
1456 SaveUserDisplayName(active_user_->email(),
1457 active_user_->GetDisplayName());
1458 }
1459
1460 GetUserImageManager(user_id)->UserLoggedIn(is_current_user_new_, true);
1461 WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded();
1462
1463 // Make sure that new data is persisted to Local State.
1464 g_browser_process->local_state()->CommitPendingWrite();
1465 }
1466
1467 void UserManagerImpl::PublicAccountUserLoggedIn(User* user) {
1468 is_current_user_new_ = true;
1469 active_user_ = user;
1470 // The UserImageManager chooses a random avatar picture when a user logs in
1471 // for the first time. Tell the UserImageManager that this user is not new to
1472 // prevent the avatar from getting changed.
1473 GetUserImageManager(user->email())->UserLoggedIn(false, true);
1474 WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded();
1475 }
1476
1477 void UserManagerImpl::KioskAppLoggedIn(const std::string& app_id) {
1478 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1479 policy::DeviceLocalAccount::Type device_local_account_type;
1480 DCHECK(policy::IsDeviceLocalAccountUser(app_id,
1481 &device_local_account_type));
1482 DCHECK_EQ(policy::DeviceLocalAccount::TYPE_KIOSK_APP,
1483 device_local_account_type);
1484
1485 active_user_ = User::CreateKioskAppUser(app_id);
1486 active_user_->SetStubImage(User::kInvalidImageIndex, false);
1487
1488 WallpaperManager::Get()->SetUserWallpaperNow(app_id);
1489
1490 // TODO(bartfab): Add KioskAppUsers to the users_ list and keep metadata like
1491 // the kiosk_app_id in these objects, removing the need to re-parse the
1492 // device-local account list here to extract the kiosk_app_id.
1493 const std::vector<policy::DeviceLocalAccount> device_local_accounts =
1494 policy::GetDeviceLocalAccounts(cros_settings_);
1495 const policy::DeviceLocalAccount* account = NULL;
1496 for (std::vector<policy::DeviceLocalAccount>::const_iterator
1497 it = device_local_accounts.begin();
1498 it != device_local_accounts.end(); ++it) {
1499 if (it->user_id == app_id) {
1500 account = &*it;
1501 break;
1502 }
1503 }
1504 std::string kiosk_app_id;
1505 if (account) {
1506 kiosk_app_id = account->kiosk_app_id;
1507 } else {
1508 LOG(ERROR) << "Logged into nonexistent kiosk-app account: " << app_id;
1509 NOTREACHED();
1510 }
1511
1512 CommandLine* command_line = CommandLine::ForCurrentProcess();
1513 command_line->AppendSwitch(::switches::kForceAppMode);
1514 command_line->AppendSwitchASCII(::switches::kAppId, kiosk_app_id);
1515
1516 // Disable window animation since kiosk app runs in a single full screen
1517 // window and window animation causes start-up janks.
1518 command_line->AppendSwitch(
1519 wm::switches::kWindowAnimationsDisabled);
1520 }
1521
1522 void UserManagerImpl::DemoAccountLoggedIn() {
1523 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1524 active_user_ = User::CreateKioskAppUser(DemoAppLauncher::kDemoUserName);
1525 active_user_->SetStubImage(User::kInvalidImageIndex, false);
1526 WallpaperManager::Get()->SetUserWallpaperNow(DemoAppLauncher::kDemoUserName);
1527
1528 CommandLine* command_line = CommandLine::ForCurrentProcess();
1529 command_line->AppendSwitch(::switches::kForceAppMode);
1530 command_line->AppendSwitchASCII(::switches::kAppId,
1531 DemoAppLauncher::kDemoAppId);
1532
1533 // Disable window animation since the demo app runs in a single full screen
1534 // window and window animation causes start-up janks.
1535 CommandLine::ForCurrentProcess()->AppendSwitch(
1536 wm::switches::kWindowAnimationsDisabled);
1537 }
1538
1539 void UserManagerImpl::RetailModeUserLoggedIn() {
1540 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1541 is_current_user_new_ = true;
1542 active_user_ = User::CreateRetailModeUser();
1543 GetUserImageManager(UserManager::kRetailModeUserName)->UserLoggedIn(
1544 is_current_user_new_,
1545 true);
1546 WallpaperManager::Get()->SetUserWallpaperNow(
1547 UserManager::kRetailModeUserName);
1548 }
1549
1550 void UserManagerImpl::NotifyOnLogin() {
1551 UpdateNumberOfUsers();
1552 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1553 NotifyActiveUserHashChanged(active_user_->username_hash());
1554 NotifyActiveUserChanged(active_user_);
1555
1556 UpdateLoginState();
1557 // TODO(nkostylev): Deprecate this notification in favor of
1558 // ActiveUserChanged() observer call.
1559 content::NotificationService::current()->Notify(
1560 chrome::NOTIFICATION_LOGIN_USER_CHANGED,
1561 content::Source<UserManager>(this),
1562 content::Details<const User>(active_user_));
1563
1564 // Owner must be first user in session. DeviceSettingsService can't deal with
1565 // multiple user and will mix up ownership, crbug.com/230018.
1566 if (GetLoggedInUsers().size() == 1) {
1567 // Indicate to DeviceSettingsService that the owner key may have become
1568 // available.
1569 DeviceSettingsService::Get()->SetUsername(active_user_->email());
1570
1571 if (NetworkPortalDetector::IsInitialized()) {
1572 NetworkPortalDetector::Get()->SetStrategy(
1573 PortalDetectorStrategy::STRATEGY_ID_SESSION);
1574 }
1575 }
1576 }
1577
1578 User::OAuthTokenStatus UserManagerImpl::LoadUserOAuthStatus(
1579 const std::string& user_id) const {
1580 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1581
1582 PrefService* local_state = g_browser_process->local_state();
1583 const base::DictionaryValue* prefs_oauth_status =
1584 local_state->GetDictionary(kUserOAuthTokenStatus);
1585 int oauth_token_status = User::OAUTH_TOKEN_STATUS_UNKNOWN;
1586 if (prefs_oauth_status &&
1587 prefs_oauth_status->GetIntegerWithoutPathExpansion(
1588 user_id, &oauth_token_status)) {
1589 User::OAuthTokenStatus result =
1590 static_cast<User::OAuthTokenStatus>(oauth_token_status);
1591 if (result == User::OAUTH2_TOKEN_STATUS_INVALID)
1592 GetUserFlow(user_id)->HandleOAuthTokenStatusChange(result);
1593 return result;
1594 }
1595 return User::OAUTH_TOKEN_STATUS_UNKNOWN;
1596 }
1597
1598 bool UserManagerImpl::LoadForceOnlineSignin(const std::string& user_id) const {
1599 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1600
1601 PrefService* local_state = g_browser_process->local_state();
1602 const base::DictionaryValue* prefs_force_online =
1603 local_state->GetDictionary(kUserForceOnlineSignin);
1604 bool force_online_signin = false;
1605 if (prefs_force_online) {
1606 prefs_force_online->GetBooleanWithoutPathExpansion(user_id,
1607 &force_online_signin);
1608 }
1609 return force_online_signin;
1610 }
1611
1612 void UserManagerImpl::UpdateOwnership() {
1613 bool is_owner = DeviceSettingsService::Get()->HasPrivateOwnerKey();
1614 VLOG(1) << "Current user " << (is_owner ? "is owner" : "is not owner");
1615
1616 SetCurrentUserIsOwner(is_owner);
1617 }
1618
1619 void UserManagerImpl::RemoveNonCryptohomeData(const std::string& user_id) {
1620 WallpaperManager::Get()->RemoveUserWallpaperInfo(user_id);
1621 GetUserImageManager(user_id)->DeleteUserImage();
1622
1623 PrefService* prefs = g_browser_process->local_state();
1624 DictionaryPrefUpdate prefs_display_name_update(prefs, kUserDisplayName);
1625 prefs_display_name_update->RemoveWithoutPathExpansion(user_id, NULL);
1626
1627 DictionaryPrefUpdate prefs_given_name_update(prefs, kUserGivenName);
1628 prefs_given_name_update->RemoveWithoutPathExpansion(user_id, NULL);
1629
1630 DictionaryPrefUpdate prefs_display_email_update(prefs, kUserDisplayEmail);
1631 prefs_display_email_update->RemoveWithoutPathExpansion(user_id, NULL);
1632
1633 DictionaryPrefUpdate prefs_oauth_update(prefs, kUserOAuthTokenStatus);
1634 prefs_oauth_update->RemoveWithoutPathExpansion(user_id, NULL);
1635
1636 DictionaryPrefUpdate prefs_force_online_update(prefs, kUserForceOnlineSignin);
1637 prefs_force_online_update->RemoveWithoutPathExpansion(user_id, NULL);
1638
1639 supervised_user_manager_->RemoveNonCryptohomeData(user_id);
1640
1641 multi_profile_user_controller_->RemoveCachedValues(user_id);
1642 }
1643
1644 User* UserManagerImpl::RemoveRegularOrLocallyManagedUserFromList(
1645 const std::string& user_id) {
1646 ListPrefUpdate prefs_users_update(g_browser_process->local_state(),
1647 kRegularUsers);
1648 prefs_users_update->Clear();
1649 User* user = NULL;
1650 for (UserList::iterator it = users_.begin(); it != users_.end(); ) {
1651 const std::string user_email = (*it)->email();
1652 if (user_email == user_id) {
1653 user = *it;
1654 it = users_.erase(it);
1655 } else {
1656 if ((*it)->GetType() == User::USER_TYPE_REGULAR ||
1657 (*it)->GetType() == User::USER_TYPE_LOCALLY_MANAGED) {
1658 prefs_users_update->Append(new base::StringValue(user_email));
1659 }
1660 ++it;
1661 }
1662 }
1663 return user;
1664 }
1665
1666 void UserManagerImpl::CleanUpPublicAccountNonCryptohomeDataPendingRemoval() {
1667 PrefService* local_state = g_browser_process->local_state();
1668 const std::string public_account_pending_data_removal =
1669 local_state->GetString(kPublicAccountPendingDataRemoval);
1670 if (public_account_pending_data_removal.empty() ||
1671 (IsUserLoggedIn() &&
1672 public_account_pending_data_removal == GetActiveUser()->email())) {
1673 return;
1674 }
1675
1676 RemoveNonCryptohomeData(public_account_pending_data_removal);
1677 local_state->ClearPref(kPublicAccountPendingDataRemoval);
1678 }
1679
1680 void UserManagerImpl::CleanUpPublicAccountNonCryptohomeData(
1681 const std::vector<std::string>& old_public_accounts) {
1682 std::set<std::string> users;
1683 for (UserList::const_iterator it = users_.begin(); it != users_.end(); ++it)
1684 users.insert((*it)->email());
1685
1686 // If the user is logged into a public account that has been removed from the
1687 // user list, mark the account's data as pending removal after logout.
1688 if (IsLoggedInAsPublicAccount()) {
1689 const std::string active_user_id = GetActiveUser()->email();
1690 if (users.find(active_user_id) == users.end()) {
1691 g_browser_process->local_state()->SetString(
1692 kPublicAccountPendingDataRemoval, active_user_id);
1693 users.insert(active_user_id);
1694 }
1695 }
1696
1697 // Remove the data belonging to any other public accounts that are no longer
1698 // found on the user list.
1699 for (std::vector<std::string>::const_iterator
1700 it = old_public_accounts.begin();
1701 it != old_public_accounts.end(); ++it) {
1702 if (users.find(*it) == users.end())
1703 RemoveNonCryptohomeData(*it);
1704 }
1705 }
1706
1707 bool UserManagerImpl::UpdateAndCleanUpPublicAccounts(
1708 const std::vector<policy::DeviceLocalAccount>& device_local_accounts) {
1709 // Try to remove any public account data marked as pending removal.
1710 CleanUpPublicAccountNonCryptohomeDataPendingRemoval();
1711
1712 // Get the current list of public accounts.
1713 std::vector<std::string> old_public_accounts;
1714 for (UserList::const_iterator it = users_.begin(); it != users_.end(); ++it) {
1715 if ((*it)->GetType() == User::USER_TYPE_PUBLIC_ACCOUNT)
1716 old_public_accounts.push_back((*it)->email());
1717 }
1718
1719 // Get the new list of public accounts from policy.
1720 std::vector<std::string> new_public_accounts;
1721 for (std::vector<policy::DeviceLocalAccount>::const_iterator it =
1722 device_local_accounts.begin();
1723 it != device_local_accounts.end(); ++it) {
1724 // TODO(mnissler, nkostylev, bartfab): Process Kiosk Apps within the
1725 // standard login framework: http://crbug.com/234694
1726 if (it->type == policy::DeviceLocalAccount::TYPE_PUBLIC_SESSION)
1727 new_public_accounts.push_back(it->user_id);
1728 }
1729
1730 // If the list of public accounts has not changed, return.
1731 if (new_public_accounts.size() == old_public_accounts.size()) {
1732 bool changed = false;
1733 for (size_t i = 0; i < new_public_accounts.size(); ++i) {
1734 if (new_public_accounts[i] != old_public_accounts[i]) {
1735 changed = true;
1736 break;
1737 }
1738 }
1739 if (!changed)
1740 return false;
1741 }
1742
1743 // Persist the new list of public accounts in a pref.
1744 ListPrefUpdate prefs_public_accounts_update(g_browser_process->local_state(),
1745 kPublicAccounts);
1746 prefs_public_accounts_update->Clear();
1747 for (std::vector<std::string>::const_iterator it =
1748 new_public_accounts.begin();
1749 it != new_public_accounts.end(); ++it) {
1750 prefs_public_accounts_update->AppendString(*it);
1751 }
1752
1753 // Remove the old public accounts from the user list.
1754 for (UserList::iterator it = users_.begin(); it != users_.end();) {
1755 if ((*it)->GetType() == User::USER_TYPE_PUBLIC_ACCOUNT) {
1756 if (*it != GetLoggedInUser())
1757 DeleteUser(*it);
1758 it = users_.erase(it);
1759 } else {
1760 ++it;
1761 }
1762 }
1763
1764 // Add the new public accounts to the front of the user list.
1765 for (std::vector<std::string>::const_reverse_iterator it =
1766 new_public_accounts.rbegin();
1767 it != new_public_accounts.rend(); ++it) {
1768 if (IsLoggedInAsPublicAccount() && *it == GetActiveUser()->email())
1769 users_.insert(users_.begin(), GetLoggedInUser());
1770 else
1771 users_.insert(users_.begin(), User::CreatePublicAccountUser(*it));
1772 UpdatePublicAccountDisplayName(*it);
1773 }
1774
1775 for (UserList::iterator ui = users_.begin(),
1776 ue = users_.begin() + new_public_accounts.size();
1777 ui != ue; ++ui) {
1778 GetUserImageManager((*ui)->email())->LoadUserImage();
1779 }
1780
1781 // Remove data belonging to public accounts that are no longer found on the
1782 // user list.
1783 CleanUpPublicAccountNonCryptohomeData(old_public_accounts);
1784
1785 return true;
1786 }
1787
1788 void UserManagerImpl::UpdatePublicAccountDisplayName(
1789 const std::string& user_id) {
1790 std::string display_name;
1791
1792 if (device_local_account_policy_service_) {
1793 policy::DeviceLocalAccountPolicyBroker* broker =
1794 device_local_account_policy_service_->GetBrokerForUser(user_id);
1795 if (broker)
1796 display_name = broker->GetDisplayName();
1797 }
1798
1799 // Set or clear the display name.
1800 SaveUserDisplayName(user_id, base::UTF8ToUTF16(display_name));
1801 }
1802
1803 UserFlow* UserManagerImpl::GetCurrentUserFlow() const {
1804 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1805 if (!IsUserLoggedIn())
1806 return GetDefaultUserFlow();
1807 return GetUserFlow(GetLoggedInUser()->email());
1808 }
1809
1810 UserFlow* UserManagerImpl::GetUserFlow(const std::string& user_id) const {
1811 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1812 FlowMap::const_iterator it = specific_flows_.find(user_id);
1813 if (it != specific_flows_.end())
1814 return it->second;
1815 return GetDefaultUserFlow();
1816 }
1817
1818 void UserManagerImpl::SetUserFlow(const std::string& user_id, UserFlow* flow) {
1819 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1820 ResetUserFlow(user_id);
1821 specific_flows_[user_id] = flow;
1822 }
1823
1824 void UserManagerImpl::ResetUserFlow(const std::string& user_id) {
1825 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1826 FlowMap::iterator it = specific_flows_.find(user_id);
1827 if (it != specific_flows_.end()) {
1828 delete it->second;
1829 specific_flows_.erase(it);
1830 }
1831 }
1832
1833 bool UserManagerImpl::GetAppModeChromeClientOAuthInfo(
1834 std::string* chrome_client_id, std::string* chrome_client_secret) {
1835 if (!chrome::IsRunningInForcedAppMode() ||
1836 chrome_client_id_.empty() ||
1837 chrome_client_secret_.empty()) {
1838 return false;
1839 }
1840
1841 *chrome_client_id = chrome_client_id_;
1842 *chrome_client_secret = chrome_client_secret_;
1843 return true;
1844 }
1845
1846 void UserManagerImpl::SetAppModeChromeClientOAuthInfo(
1847 const std::string& chrome_client_id,
1848 const std::string& chrome_client_secret) {
1849 if (!chrome::IsRunningInForcedAppMode())
1850 return;
1851
1852 chrome_client_id_ = chrome_client_id;
1853 chrome_client_secret_ = chrome_client_secret;
1854 }
1855
1856 bool UserManagerImpl::AreLocallyManagedUsersAllowed() const {
1857 bool locally_managed_users_allowed = false;
1858 cros_settings_->GetBoolean(kAccountsPrefSupervisedUsersEnabled,
1859 &locally_managed_users_allowed);
1860 policy::BrowserPolicyConnectorChromeOS* connector =
1861 g_browser_process->platform_part()->browser_policy_connector_chromeos();
1862 return locally_managed_users_allowed || !connector->IsEnterpriseManaged();
1863 }
1864
1865 base::FilePath UserManagerImpl::GetUserProfileDir(
1866 const std::string& user_id) const {
1867 // TODO(dpolukhin): Remove Chrome OS specific profile path logic from
1868 // ProfileManager and use only this function to construct profile path.
1869 // TODO(nkostylev): Cleanup profile dir related code paths crbug.com/294233
1870 base::FilePath profile_dir;
1871 const User* user = FindUser(user_id);
1872 if (user && !user->username_hash().empty())
1873 profile_dir = ProfileHelper::GetUserProfileDir(user->username_hash());
1874
1875 ProfileManager* profile_manager = g_browser_process->profile_manager();
1876 profile_dir = profile_manager->user_data_dir().Append(profile_dir);
1877
1878 return profile_dir;
1879 }
1880
1881 UserFlow* UserManagerImpl::GetDefaultUserFlow() const {
1882 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1883 if (!default_flow_.get())
1884 default_flow_.reset(new DefaultUserFlow());
1885 return default_flow_.get();
1886 }
1887
1888 void UserManagerImpl::NotifyUserListChanged() {
1889 content::NotificationService::current()->Notify(
1890 chrome::NOTIFICATION_USER_LIST_CHANGED,
1891 content::Source<UserManager>(this),
1892 content::NotificationService::NoDetails());
1893 }
1894
1895 void UserManagerImpl::NotifyActiveUserChanged(const User* active_user) {
1896 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1897 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
1898 session_state_observer_list_,
1899 ActiveUserChanged(active_user));
1900 }
1901
1902 void UserManagerImpl::NotifyUserAddedToSession(const User* added_user) {
1903 UpdateNumberOfUsers();
1904 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1905 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
1906 session_state_observer_list_,
1907 UserAddedToSession(added_user));
1908 }
1909
1910 void UserManagerImpl::NotifyActiveUserHashChanged(const std::string& hash) {
1911 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1912 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
1913 session_state_observer_list_,
1914 ActiveUserHashChanged(hash));
1915 }
1916
1917 void UserManagerImpl::NotifyPendingUserSessionsRestoreFinished() {
1918 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1919 user_sessions_restored_ = true;
1920 FOR_EACH_OBSERVER(UserManager::UserSessionStateObserver,
1921 session_state_observer_list_,
1922 PendingUserSessionsRestoreFinished());
1923 }
1924
1925 void UserManagerImpl::UpdateLoginState() {
1926 if (!LoginState::IsInitialized())
1927 return; // LoginState may not be intialized in tests.
1928 LoginState::LoggedInState logged_in_state;
1929 logged_in_state = active_user_ ? LoginState::LOGGED_IN_ACTIVE
1930 : LoginState::LOGGED_IN_NONE;
1931
1932 LoginState::LoggedInUserType login_user_type;
1933 if (logged_in_state == LoginState::LOGGED_IN_NONE)
1934 login_user_type = LoginState::LOGGED_IN_USER_NONE;
1935 else if (is_current_user_owner_)
1936 login_user_type = LoginState::LOGGED_IN_USER_OWNER;
1937 else if (active_user_->GetType() == User::USER_TYPE_GUEST)
1938 login_user_type = LoginState::LOGGED_IN_USER_GUEST;
1939 else if (active_user_->GetType() == User::USER_TYPE_RETAIL_MODE)
1940 login_user_type = LoginState::LOGGED_IN_USER_RETAIL_MODE;
1941 else if (active_user_->GetType() == User::USER_TYPE_PUBLIC_ACCOUNT)
1942 login_user_type = LoginState::LOGGED_IN_USER_PUBLIC_ACCOUNT;
1943 else if (active_user_->GetType() == User::USER_TYPE_LOCALLY_MANAGED)
1944 login_user_type = LoginState::LOGGED_IN_USER_LOCALLY_MANAGED;
1945 else if (active_user_->GetType() == User::USER_TYPE_KIOSK_APP)
1946 login_user_type = LoginState::LOGGED_IN_USER_KIOSK_APP;
1947 else
1948 login_user_type = LoginState::LOGGED_IN_USER_REGULAR;
1949
1950 LoginState::Get()->SetLoggedInState(logged_in_state, login_user_type);
1951 }
1952
1953 void UserManagerImpl::SetLRUUser(User* user) {
1954 UserList::iterator it = std::find(lru_logged_in_users_.begin(),
1955 lru_logged_in_users_.end(),
1956 user);
1957 if (it != lru_logged_in_users_.end())
1958 lru_logged_in_users_.erase(it);
1959 lru_logged_in_users_.insert(lru_logged_in_users_.begin(), user);
1960 }
1961
1962 void UserManagerImpl::OnRestoreActiveSessions(
1963 const SessionManagerClient::ActiveSessionsMap& sessions,
1964 bool success) {
1965 if (!success) {
1966 LOG(ERROR) << "Could not get list of active user sessions after crash.";
1967 // If we could not get list of active user sessions it is safer to just
1968 // sign out so that we don't get in the inconsistent state.
1969 DBusThreadManager::Get()->GetSessionManagerClient()->StopSession();
1970 return;
1971 }
1972
1973 // One profile has been already loaded on browser start.
1974 DCHECK(GetLoggedInUsers().size() == 1);
1975 DCHECK(GetActiveUser());
1976 std::string active_user_id = GetActiveUser()->email();
1977
1978 SessionManagerClient::ActiveSessionsMap::const_iterator it;
1979 for (it = sessions.begin(); it != sessions.end(); ++it) {
1980 if (active_user_id == it->first)
1981 continue;
1982 pending_user_sessions_[it->first] = it->second;
1983 }
1984 RestorePendingUserSessions();
1985 }
1986
1987 void UserManagerImpl::RestorePendingUserSessions() {
1988 if (pending_user_sessions_.empty()) {
1989 NotifyPendingUserSessionsRestoreFinished();
1990 return;
1991 }
1992
1993 // Get next user to restore sessions and delete it from list.
1994 SessionManagerClient::ActiveSessionsMap::const_iterator it =
1995 pending_user_sessions_.begin();
1996 std::string user_id = it->first;
1997 std::string user_id_hash = it->second;
1998 DCHECK(!user_id.empty());
1999 DCHECK(!user_id_hash.empty());
2000 pending_user_sessions_.erase(user_id);
2001
2002 // Check that this user is not logged in yet.
2003 UserList logged_in_users = GetLoggedInUsers();
2004 bool user_already_logged_in = false;
2005 for (UserList::const_iterator it = logged_in_users.begin();
2006 it != logged_in_users.end(); ++it) {
2007 const User* user = (*it);
2008 if (user->email() == user_id) {
2009 user_already_logged_in = true;
2010 break;
2011 }
2012 }
2013 DCHECK(!user_already_logged_in);
2014
2015 if (!user_already_logged_in) {
2016 // Will call OnProfilePrepared() once profile has been loaded.
2017 LoginUtils::Get()->PrepareProfile(
2018 UserContext(user_id,
2019 std::string(), // password
2020 std::string(), // auth_code
2021 user_id_hash,
2022 false, // using_oauth
2023 UserContext::AUTH_FLOW_OFFLINE),
2024 std::string(), // display_email
2025 false, // has_cookies
2026 true, // has_active_session
2027 this);
2028 } else {
2029 RestorePendingUserSessions();
2030 }
2031 }
2032
2033 void UserManagerImpl::SendRegularUserLoginMetrics(const std::string& user_id) {
2034 // If this isn't the first time Chrome was run after the system booted,
2035 // assume that Chrome was restarted because a previous session ended.
2036 if (!CommandLine::ForCurrentProcess()->HasSwitch(
2037 switches::kFirstExecAfterBoot)) {
2038 const std::string last_email =
2039 g_browser_process->local_state()->GetString(kLastLoggedInRegularUser);
2040 const base::TimeDelta time_to_login =
2041 base::TimeTicks::Now() - manager_creation_time_;
2042 if (!last_email.empty() && user_id != last_email &&
2043 time_to_login.InSeconds() <= kLogoutToLoginDelayMaxSec) {
2044 UMA_HISTOGRAM_CUSTOM_COUNTS("UserManager.LogoutToLoginDelay",
2045 time_to_login.InSeconds(), 0, kLogoutToLoginDelayMaxSec, 50);
2046 }
2047 }
2048 }
2049
2050 void UserManagerImpl::OnUserNotAllowed(const std::string& user_email) {
2051 LOG(ERROR) << "Shutdown session because a user is not allowed to be in the "
2052 "current session";
2053 chromeos::ShowMultiprofilesSessionAbortedDialog(user_email);
2054 }
2055
2056 void UserManagerImpl::UpdateUserAccountLocale(const std::string& user_id,
2057 const std::string& locale) {
2058 if (!locale.empty() &&
2059 locale != g_browser_process->GetApplicationLocale()) {
2060 BrowserThread::PostBlockingPoolTask(
2061 FROM_HERE,
2062 base::Bind(ResolveLocale, locale,
2063 base::Bind(&UserManagerImpl::DoUpdateAccountLocale,
2064 base::Unretained(this),
2065 user_id)));
2066 } else {
2067 DoUpdateAccountLocale(user_id, locale);
2068 }
2069 }
2070
2071 void UserManagerImpl::DoUpdateAccountLocale(
2072 const std::string& user_id,
2073 const std::string& resolved_locale) {
2074 if (User* user = FindUserAndModify(user_id))
2075 user->SetAccountLocale(resolved_locale);
2076 }
2077
2078 void UserManagerImpl::UpdateNumberOfUsers() {
2079 size_t users = GetLoggedInUsers().size();
2080 if (users) {
2081 // Write the user number as UMA stat when a multi user session is possible.
2082 if ((users + GetUsersAdmittedForMultiProfile().size()) > 1)
2083 ash::MultiProfileUMA::RecordUserCount(users);
2084 }
2085
2086 base::debug::SetCrashKeyValue(crash_keys::kNumberOfUsers,
2087 base::StringPrintf("%" PRIuS, GetLoggedInUsers().size()));
2088 }
2089
2090 void UserManagerImpl::DeleteUser(User* user) {
2091 const bool is_active_user = (user == active_user_);
2092 delete user;
2093 if (is_active_user)
2094 active_user_ = NULL;
2095 }
2096
2097 } // namespace chromeos
OLDNEW
« no previous file with comments | « chrome/browser/chromeos/login/user_manager_impl.h ('k') | chrome/browser/chromeos/login/user_manager_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698