Upstream version 9.37.197.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / chromeos / login / users / user_manager_impl.h
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 #ifndef CHROME_BROWSER_CHROMEOS_LOGIN_USERS_USER_MANAGER_IMPL_H_
6 #define CHROME_BROWSER_CHROMEOS_LOGIN_USERS_USER_MANAGER_IMPL_H_
7
8 #include <map>
9 #include <string>
10 #include <vector>
11
12 #include "base/basictypes.h"
13 #include "base/containers/hash_tables.h"
14 #include "base/memory/linked_ptr.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/observer_list.h"
17 #include "base/synchronization/lock.h"
18 #include "base/time/time.h"
19 #include "chrome/browser/chromeos/login/login_utils.h"
20 #include "chrome/browser/chromeos/login/users/avatar/user_image_manager_impl.h"
21 #include "chrome/browser/chromeos/login/users/multi_profile_user_controller_delegate.h"
22 #include "chrome/browser/chromeos/login/users/user.h"
23 #include "chrome/browser/chromeos/login/users/user_manager.h"
24 #include "chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager.h"
25 #include "chrome/browser/chromeos/policy/cloud_external_data_policy_observer.h"
26 #include "chrome/browser/chromeos/policy/device_local_account_policy_service.h"
27 #include "chrome/browser/chromeos/settings/cros_settings.h"
28 #include "chrome/browser/chromeos/settings/device_settings_service.h"
29 #include "chromeos/dbus/session_manager_client.h"
30 #include "content/public/browser/notification_observer.h"
31 #include "content/public/browser/notification_registrar.h"
32
33 class PrefService;
34 class ProfileSyncService;
35
36 namespace policy {
37 struct DeviceLocalAccount;
38 }
39
40 namespace chromeos {
41
42 class MultiProfileUserController;
43 class RemoveUserDelegate;
44 class SupervisedUserManagerImpl;
45 class SessionLengthLimiter;
46
47 // Implementation of the UserManager.
48 class UserManagerImpl
49     : public UserManager,
50       public LoginUtils::Delegate,
51       public content::NotificationObserver,
52       public policy::CloudExternalDataPolicyObserver::Delegate,
53       public policy::DeviceLocalAccountPolicyService::Observer,
54       public MultiProfileUserControllerDelegate {
55  public:
56   virtual ~UserManagerImpl();
57
58   // UserManager implementation:
59   virtual void Shutdown() OVERRIDE;
60   virtual MultiProfileUserController* GetMultiProfileUserController() OVERRIDE;
61   virtual UserImageManager* GetUserImageManager(
62       const std::string& user_id) OVERRIDE;
63   virtual SupervisedUserManager* GetSupervisedUserManager() OVERRIDE;
64   virtual const UserList& GetUsers() const OVERRIDE;
65   virtual UserList GetUsersAdmittedForMultiProfile() const OVERRIDE;
66   virtual const UserList& GetLoggedInUsers() const OVERRIDE;
67   virtual const UserList& GetLRULoggedInUsers() OVERRIDE;
68   virtual UserList GetUnlockUsers() const OVERRIDE;
69   virtual const std::string& GetOwnerEmail() OVERRIDE;
70   virtual void UserLoggedIn(const std::string& user_id,
71                             const std::string& user_id_hash,
72                             bool browser_restart) OVERRIDE;
73   virtual void SwitchActiveUser(const std::string& user_id) OVERRIDE;
74   virtual void RestoreActiveSessions() OVERRIDE;
75   virtual void SessionStarted() OVERRIDE;
76   virtual void RemoveUser(const std::string& user_id,
77                           RemoveUserDelegate* delegate) OVERRIDE;
78   virtual void RemoveUserFromList(const std::string& user_id) OVERRIDE;
79   virtual bool IsKnownUser(const std::string& user_id) const OVERRIDE;
80   virtual const User* FindUser(const std::string& user_id) const OVERRIDE;
81   virtual User* FindUserAndModify(const std::string& user_id) OVERRIDE;
82   virtual const User* GetLoggedInUser() const OVERRIDE;
83   virtual User* GetLoggedInUser() OVERRIDE;
84   virtual const User* GetActiveUser() const OVERRIDE;
85   virtual User* GetActiveUser() OVERRIDE;
86   virtual const User* GetPrimaryUser() const OVERRIDE;
87   virtual User* GetUserByProfile(Profile* profile) const OVERRIDE;
88   virtual Profile* GetProfileByUser(const User* user) const OVERRIDE;
89   virtual void SaveUserOAuthStatus(
90       const std::string& user_id,
91       User::OAuthTokenStatus oauth_token_status) OVERRIDE;
92   virtual void SaveForceOnlineSignin(const std::string& user_id,
93                                      bool force_online_signin) OVERRIDE;
94   virtual void SaveUserDisplayName(const std::string& user_id,
95                                    const base::string16& display_name) OVERRIDE;
96   virtual base::string16 GetUserDisplayName(
97       const std::string& user_id) const OVERRIDE;
98   virtual void SaveUserDisplayEmail(const std::string& user_id,
99                                     const std::string& display_email) OVERRIDE;
100   virtual std::string GetUserDisplayEmail(
101       const std::string& user_id) const OVERRIDE;
102   virtual void UpdateUserAccountData(
103       const std::string& user_id,
104       const UserAccountData& account_data) OVERRIDE;
105   virtual bool IsCurrentUserOwner() const OVERRIDE;
106   virtual bool IsCurrentUserNew() const OVERRIDE;
107   virtual bool IsCurrentUserNonCryptohomeDataEphemeral() const OVERRIDE;
108   virtual bool CanCurrentUserLock() const OVERRIDE;
109   virtual bool IsUserLoggedIn() const OVERRIDE;
110   virtual bool IsLoggedInAsRegularUser() const OVERRIDE;
111   virtual bool IsLoggedInAsDemoUser() const OVERRIDE;
112   virtual bool IsLoggedInAsPublicAccount() const OVERRIDE;
113   virtual bool IsLoggedInAsGuest() const OVERRIDE;
114   virtual bool IsLoggedInAsLocallyManagedUser() const OVERRIDE;
115   virtual bool IsLoggedInAsKioskApp() const OVERRIDE;
116   virtual bool IsLoggedInAsStub() const OVERRIDE;
117   virtual bool IsSessionStarted() const OVERRIDE;
118   virtual bool UserSessionsRestored() const OVERRIDE;
119   virtual bool HasBrowserRestarted() const OVERRIDE;
120   virtual bool IsUserNonCryptohomeDataEphemeral(
121       const std::string& user_id) const OVERRIDE;
122   virtual void AddObserver(UserManager::Observer* obs) OVERRIDE;
123   virtual void RemoveObserver(UserManager::Observer* obs) OVERRIDE;
124   virtual void AddSessionStateObserver(
125       UserManager::UserSessionStateObserver* obs) OVERRIDE;
126   virtual void RemoveSessionStateObserver(
127       UserManager::UserSessionStateObserver* obs) OVERRIDE;
128   virtual void NotifyLocalStateChanged() OVERRIDE;
129
130   virtual UserFlow* GetCurrentUserFlow() const OVERRIDE;
131   virtual UserFlow* GetUserFlow(const std::string& user_id) const OVERRIDE;
132   virtual void SetUserFlow(const std::string& user_id, UserFlow* flow) OVERRIDE;
133   virtual void ResetUserFlow(const std::string& user_id) OVERRIDE;
134   virtual bool GetAppModeChromeClientOAuthInfo(
135       std::string* chrome_client_id,
136       std::string* chrome_client_secret) OVERRIDE;
137   virtual void SetAppModeChromeClientOAuthInfo(
138       const std::string& chrome_client_id,
139       const std::string& chrome_client_secret) OVERRIDE;
140   virtual bool AreLocallyManagedUsersAllowed() const OVERRIDE;
141   virtual base::FilePath GetUserProfileDir(
142       const std::string& user_id) const OVERRIDE;
143
144   // content::NotificationObserver implementation.
145   virtual void Observe(int type,
146                        const content::NotificationSource& source,
147                        const content::NotificationDetails& details) OVERRIDE;
148
149   // policy::CloudExternalDataPolicyObserver::Delegate:
150   virtual void OnExternalDataSet(const std::string& policy,
151                                  const std::string& user_id) OVERRIDE;
152   virtual void OnExternalDataCleared(const std::string& policy,
153                                      const std::string& user_id) OVERRIDE;
154   virtual void OnExternalDataFetched(const std::string& policy,
155                                      const std::string& user_id,
156                                      scoped_ptr<std::string> data) OVERRIDE;
157
158   // policy::DeviceLocalAccountPolicyService::Observer implementation.
159   virtual void OnPolicyUpdated(const std::string& user_id) OVERRIDE;
160   virtual void OnDeviceLocalAccountsChanged() OVERRIDE;
161
162   virtual bool RespectLocalePreference(
163       Profile* profile,
164       const User* user,
165       scoped_ptr<locale_util::SwitchLanguageCallback> callback) const OVERRIDE;
166
167   void StopPolicyObserverForTesting();
168
169  private:
170   friend class SupervisedUserManagerImpl;
171   friend class UserManager;
172   friend class WallpaperManager;
173   friend class UserManagerTest;
174   friend class WallpaperManagerTest;
175
176   typedef base::hash_map<std::string,
177       linked_ptr<UserImageManager> > UserImageManagerMap;
178
179   // Stages of loading user list from preferences. Some methods can have
180   // different behavior depending on stage.
181   enum UserLoadStage {
182     STAGE_NOT_LOADED = 0,
183     STAGE_LOADING,
184     STAGE_LOADED
185   };
186
187   UserManagerImpl();
188
189   // LoginUtils::Delegate implementation:
190   // Used when restoring user sessions after crash.
191   virtual void OnProfilePrepared(Profile* profile) OVERRIDE;
192
193   // Loads |users_| from Local State if the list has not been loaded yet.
194   // Subsequent calls have no effect. Must be called on the UI thread.
195   void EnsureUsersLoaded();
196
197   // Retrieves trusted device policies and removes users from the persistent
198   // list if ephemeral users are enabled. Schedules a callback to itself if
199   // trusted device policies are not yet available.
200   void RetrieveTrustedDevicePolicies();
201
202   // Returns true if trusted device policies have successfully been retrieved
203   // and ephemeral users are enabled.
204   bool AreEphemeralUsersEnabled() const;
205
206   // Returns a list of users who have logged into this device previously.
207   // Same as GetUsers but used if you need to modify User from that list.
208   UserList& GetUsersAndModify();
209
210   // Returns the user with the given email address if found in the persistent
211   // list. Returns |NULL| otherwise.
212   const User* FindUserInList(const std::string& user_id) const;
213
214   // Returns |true| if user with the given id is found in the persistent list.
215   // Returns |false| otherwise. Does not trigger user loading.
216   const bool UserExistsInList(const std::string& user_id) const;
217
218   // Same as FindUserInList but returns non-const pointer to User object.
219   User* FindUserInListAndModify(const std::string& user_id);
220
221   // Indicates that a user just logged in as guest.
222   void GuestUserLoggedIn();
223
224   // Indicates that a regular user just logged in.
225   void RegularUserLoggedIn(const std::string& user_id);
226
227   // Indicates that a regular user just logged in as ephemeral.
228   void RegularUserLoggedInAsEphemeral(const std::string& user_id);
229
230   // Indicates that a locally managed user just logged in.
231   void LocallyManagedUserLoggedIn(const std::string& user_id);
232
233   // Indicates that a user just logged into a public session.
234   void PublicAccountUserLoggedIn(User* user);
235
236   // Indicates that a kiosk app robot just logged in.
237   void KioskAppLoggedIn(const std::string& app_id);
238
239   // Indicates that the demo account has just logged in.
240   void DemoAccountLoggedIn();
241
242   // Indicates that a user just logged into a retail mode session.
243   void RetailModeUserLoggedIn();
244
245   // Notifies that user has logged in.
246   // Sends NOTIFICATION_LOGIN_USER_CHANGED notification.
247   void NotifyOnLogin();
248
249   // Reads user's oauth token status from local state preferences.
250   User::OAuthTokenStatus LoadUserOAuthStatus(const std::string& user_id) const;
251
252   // Read a flag indicating whether online authentication against GAIA should
253   // be enforced during the user's next sign-in from local state preferences.
254   bool LoadForceOnlineSignin(const std::string& user_id) const;
255
256   void SetCurrentUserIsOwner(bool is_current_user_owner);
257
258   // Updates current user ownership on UI thread.
259   void UpdateOwnership();
260
261   // Removes data stored or cached outside the user's cryptohome (wallpaper,
262   // avatar, OAuth token status, display name, display email).
263   void RemoveNonCryptohomeData(const std::string& user_id);
264
265   // Removes a regular or locally managed user from the user list.
266   // Returns the user if found or NULL otherwise.
267   // Also removes the user from the persistent user list.
268   User* RemoveRegularOrLocallyManagedUserFromList(const std::string& user_id);
269
270   // If data for a public account is marked as pending removal and the user is
271   // no longer logged into that account, removes the data.
272   void CleanUpPublicAccountNonCryptohomeDataPendingRemoval();
273
274   // Removes data belonging to public accounts that are no longer found on the
275   // user list. If the user is currently logged into one of these accounts, the
276   // data for that account is not removed immediately but marked as pending
277   // removal after logout.
278   void CleanUpPublicAccountNonCryptohomeData(
279       const std::vector<std::string>& old_public_accounts);
280
281   // Replaces the list of public accounts with those found in
282   // |device_local_accounts|. Ensures that data belonging to accounts no longer
283   // on the list is removed. Returns |true| if the list has changed.
284   // Public accounts are defined by policy. This method is called whenever an
285   // updated list of public accounts is received from policy.
286   bool UpdateAndCleanUpPublicAccounts(
287       const std::vector<policy::DeviceLocalAccount>& device_local_accounts);
288
289   // Updates the display name for public account |username| from policy settings
290   // associated with that username.
291   void UpdatePublicAccountDisplayName(const std::string& user_id);
292
293   // Notifies the UI about a change to the user list.
294   void NotifyUserListChanged();
295
296   // Notifies observers that merge session state had changed.
297   void NotifyMergeSessionStateChanged();
298
299   // Notifies observers that active user has changed.
300   void NotifyActiveUserChanged(const User* active_user);
301
302   // Notifies observers that another user was added to the session.
303   void NotifyUserAddedToSession(const User* added_user);
304
305   // Notifies observers that active user_id hash has changed.
306   void NotifyActiveUserHashChanged(const std::string& hash);
307
308   // Notifies observers that user pending sessions restore has finished.
309   void NotifyPendingUserSessionsRestoreFinished();
310
311   // Lazily creates default user flow.
312   UserFlow* GetDefaultUserFlow() const;
313
314   // Update the global LoginState.
315   void UpdateLoginState();
316
317   // Insert |user| at the front of the LRU user list.
318   void SetLRUUser(User* user);
319
320   // Adds |user| to users list, and adds it to front of LRU list. It is assumed
321   // that there is no user with same id.
322   void AddUserRecord(User* user);
323
324   // Callback to process RetrieveActiveSessions() request results.
325   void OnRestoreActiveSessions(
326       const SessionManagerClient::ActiveSessionsMap& sessions,
327       bool success);
328
329   // Called by OnRestoreActiveSessions() when there're user sessions in
330   // |pending_user_sessions_| that has to be restored one by one.
331   // Also called after first user session from that list is restored and so on.
332   // Process continues till |pending_user_sessions_| map is not empty.
333   void RestorePendingUserSessions();
334
335   // Sends metrics in response to a regular user logging in.
336   void SendRegularUserLoginMetrics(const std::string& user_id);
337
338   // Implementation for RemoveUser method. This is an asynchronous part of the
339   // method, that verifies that owner will not get deleted, and calls
340   // |RemoveNonOwnerUserInternal|.
341   void RemoveUserInternal(const std::string& user_email,
342                           RemoveUserDelegate* delegate);
343
344   // Implementation for RemoveUser method. It is synchronous. It is called from
345   // RemoveUserInternal after owner check.
346   void RemoveNonOwnerUserInternal(const std::string& user_email,
347                                   RemoveUserDelegate* delegate);
348
349   // MultiProfileUserControllerDelegate implementation:
350   virtual void OnUserNotAllowed(const std::string& user_email) OVERRIDE;
351
352   // Sets account locale for user with id |user_id|.
353   virtual void UpdateUserAccountLocale(const std::string& user_id,
354                                        const std::string& locale);
355
356   // Updates user account after locale was resolved.
357   void DoUpdateAccountLocale(const std::string& user_id,
358                              const std::string& resolved_locale);
359
360   // Update the number of users.
361   void UpdateNumberOfUsers();
362
363   // A wrapper around C++ delete operator. Deletes |user|, and when |user|
364   // equals to active_user_, active_user_ is reset to NULL.
365   void DeleteUser(User* user);
366
367   // Interface to the signed settings store.
368   CrosSettings* cros_settings_;
369
370   // Interface to device-local account definitions and associated policy.
371   policy::DeviceLocalAccountPolicyService* device_local_account_policy_service_;
372
373   // Indicates stage of loading user from prefs.
374   UserLoadStage user_loading_stage_;
375
376   // List of all known users. User instances are owned by |this|. Regular users
377   // are removed by |RemoveUserFromList|, public accounts by
378   // |UpdateAndCleanUpPublicAccounts|.
379   UserList users_;
380
381   // List of all users that are logged in current session. These point to User
382   // instances in |users_|. Only one of them could be marked as active.
383   UserList logged_in_users_;
384
385   // A list of all users that are logged in the current session. In contrast to
386   // |logged_in_users|, the order of this list is least recently used so that
387   // the active user should always be the first one in the list.
388   UserList lru_logged_in_users_;
389
390   // The list which gets reported when the |lru_logged_in_users_| list is empty.
391   UserList temp_single_logged_in_users_;
392
393   // The logged-in user that is currently active in current session.
394   // NULL until a user has logged in, then points to one
395   // of the User instances in |users_|, the |guest_user_| instance or an
396   // ephemeral user instance.
397   User* active_user_;
398
399   // The primary user of the current session. It is recorded for the first
400   // signed-in user and does not change thereafter.
401   User* primary_user_;
402
403   // True if SessionStarted() has been called.
404   bool session_started_;
405
406   // True is user sessions has been restored after crash.
407   // On a normal boot then login into user sessions this will be false.
408   bool user_sessions_restored_;
409
410   // Cached flag of whether currently logged-in user is owner or not.
411   // May be accessed on different threads, requires locking.
412   bool is_current_user_owner_;
413   mutable base::Lock is_current_user_owner_lock_;
414
415   // Cached flag of whether the currently logged-in user existed before this
416   // login.
417   bool is_current_user_new_;
418
419   // Cached flag of whether the currently logged-in user is a regular user who
420   // logged in as ephemeral. Storage of persistent information is avoided for
421   // such users by not adding them to the persistent user list, not downloading
422   // their custom avatars and mounting their cryptohomes using tmpfs. Defaults
423   // to |false|.
424   bool is_current_user_ephemeral_regular_user_;
425
426   // Cached flag indicating whether the ephemeral user policy is enabled.
427   // Defaults to |false| if the value has not been read from trusted device
428   // policy yet.
429   bool ephemeral_users_enabled_;
430
431   // Cached name of device owner. Defaults to empty string if the value has not
432   // been read from trusted device policy yet.
433   std::string owner_email_;
434
435   // Chrome oauth client id and secret - override values for kiosk mode.
436   std::string chrome_client_id_;
437   std::string chrome_client_secret_;
438
439   content::NotificationRegistrar registrar_;
440
441   ObserverList<UserManager::Observer> observer_list_;
442
443   // TODO(nkostylev): Merge with session state refactoring CL.
444   ObserverList<UserManager::UserSessionStateObserver>
445       session_state_observer_list_;
446
447   // User avatar managers.
448   UserImageManagerMap user_image_managers_;
449
450   // Supervised user manager.
451   scoped_ptr<SupervisedUserManagerImpl> supervised_user_manager_;
452
453   // Session length limiter.
454   scoped_ptr<SessionLengthLimiter> session_length_limiter_;
455
456   typedef std::map<std::string, UserFlow*> FlowMap;
457
458   // Lazy-initialized default flow.
459   mutable scoped_ptr<UserFlow> default_flow_;
460
461   // Specific flows by user e-mail. Keys should be canonicalized before
462   // access.
463   FlowMap specific_flows_;
464
465   // User sessions that have to be restored after browser crash.
466   // [user_id] > [user_id_hash]
467   SessionManagerClient::ActiveSessionsMap pending_user_sessions_;
468
469   // Time at which this object was created.
470   base::TimeTicks manager_creation_time_;
471
472   scoped_ptr<CrosSettings::ObserverSubscription>
473       local_accounts_subscription_;
474
475   scoped_ptr<MultiProfileUserController> multi_profile_user_controller_;
476
477   // Observer for the policy that can be used to manage user images.
478   scoped_ptr<policy::CloudExternalDataPolicyObserver> avatar_policy_observer_;
479
480   // Observer for the policy that can be used to manage wallpapers.
481   scoped_ptr<policy::CloudExternalDataPolicyObserver>
482       wallpaper_policy_observer_;
483
484   // ID of the user just added to the session that needs to be activated
485   // as soon as user's profile is loaded.
486   std::string pending_user_switch_;
487
488   DISALLOW_COPY_AND_ASSIGN(UserManagerImpl);
489 };
490
491 }  // namespace chromeos
492
493 #endif  // CHROME_BROWSER_CHROMEOS_LOGIN_USERS_USER_MANAGER_IMPL_H_