1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef CHROME_BROWSER_CHROMEOS_LOGIN_SESSION_USER_SESSION_MANAGER_H_
6 #define CHROME_BROWSER_CHROMEOS_LOGIN_SESSION_USER_SESSION_MANAGER_H_
10 #include "base/basictypes.h"
11 #include "base/callback.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/memory/singleton.h"
14 #include "base/memory/weak_ptr.h"
15 #include "base/observer_list.h"
16 #include "chrome/browser/chromeos/base/locale_util.h"
17 #include "chrome/browser/chromeos/login/signin/oauth2_login_manager.h"
18 #include "chrome/browser/chromeos/login/signin/token_handle_util.h"
19 #include "chromeos/dbus/session_manager_client.h"
20 #include "chromeos/login/auth/authenticator.h"
21 #include "chromeos/login/auth/user_context.h"
22 #include "components/user_manager/user.h"
23 #include "components/user_manager/user_manager.h"
24 #include "net/base/network_change_notifier.h"
25 #include "ui/base/ime/chromeos/input_method_manager.h"
28 class PrefRegistrySimple
;
31 class TokenHandleFetcher
;
34 class URLRequestContextGetter
;
37 namespace user_manager
{
39 } // namespace user_manager
44 class UserSessionManagerTestApi
;
47 class EasyUnlockKeyManager
;
48 class InputEventsBlocker
;
49 class LoginDisplayHost
;
51 class UserSessionManagerDelegate
{
53 // Called after profile is loaded and prepared for the session.
54 // |browser_launched| will be true is browser has been launched, otherwise
55 // it will return false and client is responsible on launching browser.
56 virtual void OnProfilePrepared(Profile
* profile
,
57 bool browser_launched
) = 0;
60 virtual ~UserSessionManagerDelegate();
63 class UserSessionStateObserver
{
65 // Called when UserManager finishes restoring user sessions after crash.
66 virtual void PendingUserSessionsRestoreFinished();
69 virtual ~UserSessionStateObserver();
72 // UserSessionManager is responsible for starting user session which includes:
73 // * load and initialize Profile (including custom Profile preferences),
74 // * mark user as logged in and notify observers,
75 // * initialize OAuth2 authentication session,
76 // * initialize and launch user session based on the user type.
77 // Also supports restoring active user sessions after browser crash:
78 // load profile, restore OAuth authentication session etc.
79 class UserSessionManager
80 : public OAuth2LoginManager::Observer
,
81 public net::NetworkChangeNotifier::ConnectionTypeObserver
,
82 public base::SupportsWeakPtr
<UserSessionManager
>,
83 public UserSessionManagerDelegate
,
84 public user_manager::UserManager::UserSessionStateObserver
{
86 // Context of StartSession calls.
88 // Starting primary user session, through login UI.
91 // Starting secondary user session, through multi-profiles login UI.
92 SECONDARY_USER_SESSION
,
94 // Starting primary user session after browser crash.
95 PRIMARY_USER_SESSION_AFTER_CRASH
,
97 // Starting secondary user session after browser crash.
98 SECONDARY_USER_SESSION_AFTER_CRASH
,
101 // Returns UserSessionManager instance.
102 static UserSessionManager
* GetInstance();
104 // Called when user is logged in to override base::DIR_HOME path.
105 static void OverrideHomedir();
107 // Registers session related preferences.
108 static void RegisterPrefs(PrefRegistrySimple
* registry
);
110 // Invoked after the tmpfs is successfully mounted.
111 // Asks session_manager to restart Chrome in Guest session mode.
112 // |start_url| is an optional URL to be opened in Guest session browser.
113 void CompleteGuestSessionLogin(const GURL
& start_url
);
115 // Creates and returns the authenticator to use.
116 // Single Authenticator instance is used for entire login process,
117 // even for multiple retries. Authenticator instance holds reference to
118 // login profile and is later used during fetching of OAuth tokens.
119 scoped_refptr
<Authenticator
> CreateAuthenticator(
120 AuthStatusConsumer
* consumer
);
122 // Start user session given |user_context|.
123 // OnProfilePrepared() will be called on |delegate| once Profile is ready.
124 void StartSession(const UserContext
& user_context
,
125 StartSessionType start_session_type
,
126 bool has_auth_cookies
,
127 bool has_active_session
,
128 UserSessionManagerDelegate
* delegate
);
130 // Invalidates |delegate|, which was passed to StartSession method call.
131 void DelegateDeleted(UserSessionManagerDelegate
* delegate
);
133 // Perform additional actions once system wide notification
134 // "UserLoggedIn" has been sent.
135 void PerformPostUserLoggedInActions();
137 // Restores authentication session after crash.
138 void RestoreAuthenticationSession(Profile
* profile
);
140 // Usually is called when Chrome is restarted after a crash and there's an
141 // active session. First user (one that is passed with --login-user) Chrome
142 // session has been already restored at this point. This method asks session
143 // manager for all active user sessions, marks them as logged in
144 // and notifies observers.
145 void RestoreActiveSessions();
147 // Returns true iff browser has been restarted after crash and
148 // UserSessionManager finished restoring user sessions.
149 bool UserSessionsRestored() const;
151 // Returns true iff browser has been restarted after crash and
152 // user sessions restoration is in progress.
153 bool UserSessionsRestoreInProgress() const;
156 void InitRlz(Profile
* profile
);
158 // Get the NSS cert database for the user represented with |profile|
159 // and start certificate loader with it.
160 void InitializeCerts(Profile
* profile
);
162 // Starts loading CRL set.
163 void InitializeCRLSetFetcher(const user_manager::User
* user
);
165 // Starts loading EV Certificates whitelist.
166 void InitializeEVCertificatesWhitelistComponent(
167 const user_manager::User
* user
);
169 // Invoked when the user is logging in for the first time, or is logging in to
170 // an ephemeral session type, such as guest or a public session.
171 void SetFirstLoginPrefs(Profile
* profile
,
172 const std::string
& public_session_locale
,
173 const std::string
& public_session_input_method
);
175 // Gets/sets Chrome OAuth client id and secret for kiosk app mode. The default
176 // values can be overridden with kiosk auth file.
177 bool GetAppModeChromeClientOAuthInfo(
178 std::string
* chrome_client_id
,
179 std::string
* chrome_client_secret
);
180 void SetAppModeChromeClientOAuthInfo(
181 const std::string
& chrome_client_id
,
182 const std::string
& chrome_client_secret
);
184 // Thin wrapper around StartupBrowserCreator::LaunchBrowser(). Meant to be
185 // used in a Task posted to the UI thread. Once the browser is launched the
186 // login host is deleted.
187 void DoBrowserLaunch(Profile
* profile
, LoginDisplayHost
* login_host
);
189 // Changes browser locale (selects best suitable locale from different
190 // user settings). Returns true if callback will be called.
191 bool RespectLocalePreference(
193 const user_manager::User
* user
,
194 const locale_util::SwitchLanguageCallback
& callback
) const;
196 // Switch to the locale that |profile| wishes to use and invoke |callback|.
197 void RespectLocalePreferenceWrapper(Profile
* profile
,
198 const base::Closure
& callback
);
200 // Restarts Chrome if needed. This happens when user session has custom
201 // flags/switches enabled. Another case when owner has setup custom flags,
202 // they are applied on login screen as well but not to user session.
203 // |early_restart| is true if this restart attempt happens before user profile
204 // is fully initialized.
205 // Might not return if restart is possible right now.
206 // Returns true if restart was scheduled.
207 // Returns false if no restart is needed.
208 bool RestartToApplyPerSessionFlagsIfNeed(Profile
* profile
,
211 // Returns true if Easy unlock keys needs to be updated.
212 bool NeedsToUpdateEasyUnlockKeys() const;
214 // Returns true if there are pending Easy unlock key operations and
215 // |callback| will be invoked when it is done.
216 bool CheckEasyUnlockKeyOps(const base::Closure
& callback
);
218 void AddSessionStateObserver(chromeos::UserSessionStateObserver
* observer
);
219 void RemoveSessionStateObserver(chromeos::UserSessionStateObserver
* observer
);
221 void ActiveUserChanged(const user_manager::User
* active_user
) override
;
223 // This method will be called when user have obtained oauth2 tokens.
224 void OnOAuth2TokensFetched(UserContext context
);
226 // Returns default IME state for user session.
227 scoped_refptr
<input_method::InputMethodManager::State
> GetDefaultIMEState(
230 // Note this could return NULL if not enabled.
231 EasyUnlockKeyManager
* GetEasyUnlockKeyManager();
233 // Update Easy unlock cryptohome keys for given user context.
234 void UpdateEasyUnlockKeys(const UserContext
& user_context
);
236 // Returns the auth request context associated with auth data.
237 net::URLRequestContextGetter
* GetAuthRequestContext() const;
239 // Removes a profile from the per-user input methods states map.
240 void RemoveProfileForTesting(Profile
* profile
);
242 const UserContext
& user_context() const { return user_context_
; }
243 bool has_auth_cookies() const { return has_auth_cookies_
; }
248 friend class test::UserSessionManagerTestApi
;
249 friend struct DefaultSingletonTraits
<UserSessionManager
>;
251 typedef std::set
<std::string
> SigninSessionRestoreStateSet
;
253 UserSessionManager();
254 ~UserSessionManager() override
;
256 // OAuth2LoginManager::Observer overrides:
257 void OnSessionRestoreStateChanged(
258 Profile
* user_profile
,
259 OAuth2LoginManager::SessionRestoreState state
) override
;
261 // net::NetworkChangeNotifier::ConnectionTypeObserver overrides:
262 void OnConnectionTypeChanged(
263 net::NetworkChangeNotifier::ConnectionType type
) override
;
265 // UserSessionManagerDelegate overrides:
266 // Used when restoring user sessions after crash.
267 void OnProfilePrepared(Profile
* profile
, bool browser_launched
) override
;
269 void ChildAccountStatusReceivedCallback(Profile
* profile
);
271 void StopChildStatusObserving(Profile
* profile
);
273 void CreateUserSession(const UserContext
& user_context
,
274 bool has_auth_cookies
);
275 void PreStartSession();
277 // Store any useful UserContext data early on when profile has not been
278 // created yet and user services were not yet initialized. Can store
279 // information in Local State like GAIA ID.
280 void StoreUserContextDataBeforeProfileIsCreated();
282 void StartCrosSession();
283 void NotifyUserLoggedIn();
284 void PrepareProfile();
286 // Callback for asynchronous profile creation.
287 void OnProfileCreated(const UserContext
& user_context
,
288 bool is_incognito_profile
,
290 Profile::CreateStatus status
);
292 // Callback for Profile::CREATE_STATUS_CREATED profile state.
293 // Initializes basic preferences for newly created profile. Any other
294 // early profile initialization that needs to happen before
295 // ProfileManager::DoFinalInit() gets called is done here.
296 void InitProfilePreferences(Profile
* profile
,
297 const UserContext
& user_context
);
299 // Callback for Profile::CREATE_STATUS_INITIALIZED profile state.
300 // Profile is created, extensions and promo resources are initialized.
301 void UserProfileInitialized(Profile
* profile
,
302 bool is_incognito_profile
,
303 const std::string
& user_id
);
305 // Callback to resume profile creation after transferring auth data from
306 // the authentication profile.
307 void CompleteProfileCreateAfterAuthTransfer(Profile
* profile
);
309 // Finalized profile preparation.
310 void FinalizePrepareProfile(Profile
* profile
);
312 // Starts out-of-box flow with the specified screen.
313 void ActivateWizard(const std::string
& screen_name
);
315 // Adds first-time login URLs.
316 void InitializeStartUrls() const;
318 // Perform session initialization and either move to additional login flows
319 // such as TOS (public sessions), priority pref sync UI (new users) or
321 // Returns true if browser has been launched or false otherwise.
322 bool InitializeUserSession(Profile
* profile
);
324 // Initializes member variables needed for session restore process via
325 // OAuthLoginManager.
326 void InitSessionRestoreStrategy();
328 // Restores GAIA auth cookies for the created user profile from OAuth2 token.
329 void RestoreAuthSessionImpl(Profile
* profile
,
330 bool restore_from_auth_cookies
);
332 // Initializes RLZ. If |disabled| is true, RLZ pings are disabled.
333 void InitRlzImpl(Profile
* profile
, bool disabled
);
335 // Callback to process RetrieveActiveSessions() request results.
336 void OnRestoreActiveSessions(
337 const SessionManagerClient::ActiveSessionsMap
& sessions
,
340 // Called by OnRestoreActiveSessions() when there're user sessions in
341 // |pending_user_sessions_| that has to be restored one by one.
342 // Also called after first user session from that list is restored and so on.
343 // Process continues till |pending_user_sessions_| map is not empty.
344 void RestorePendingUserSessions();
346 // Notifies observers that user pending sessions restore has finished.
347 void NotifyPendingUserSessionsRestoreFinished();
349 // Attempts restarting the browser process and esures that this does
350 // not happen while we are still fetching new OAuth refresh tokens.
351 void AttemptRestart(Profile
* profile
);
353 // Callback invoked when Easy unlock key operations are finished.
354 void OnEasyUnlockKeyOpsFinished(const std::string
& user_id
,
357 // Internal implementation of DoBrowserLaunch. Initially should be called with
358 // |locale_pref_checked| set to false which will result in postponing browser
359 // launch till user locale is applied if needed. After locale check has
360 // completed this method is called with |locale_pref_checked| set to true.
361 void DoBrowserLaunchInternal(Profile
* profile
,
362 LoginDisplayHost
* login_host
,
363 bool locale_pref_checked
);
365 static void RunCallbackOnLocaleLoaded(
366 const base::Closure
& callback
,
367 InputEventsBlocker
* input_events_blocker
,
368 const locale_util::LanguageSwitchResult
& result
);
370 // Callback invoked when |token_handle_util_| has finished.
371 void OnTokenHandleObtained(const user_manager::UserID
& id
, bool success
);
373 // Returns |true| if token handles should be used on this device.
374 bool TokenHandlesEnabled();
376 void CreateTokenUtilIfMissing();
380 // Injects |user_context| that will be used to create StubAuthenticator
381 // instance when CreateAuthenticator() is called.
382 void InjectStubUserContext(const UserContext
& user_context
);
384 // Controls whether browser instance should be launched after sign in
386 void set_should_launch_browser_in_tests(bool should_launch_browser
) {
387 should_launch_browser_
= should_launch_browser
;
390 // Controls whether token handle fetching is enabled (used in tests).
391 void SetShouldObtainHandleInTests(bool should_obtain_handles
);
393 // The user pods display type for histogram.
394 enum UserPodsDisplay
{
395 // User pods enabling or disabling is possible either via local settings or
396 // via domain policy. The former method only applies to regular devices,
397 // whereas the latter is for enterprise-managed devices. Therefore, we have
398 // four possible combiations.
399 USER_PODS_DISPLAY_ENABLED_REGULAR
= 0,
400 USER_PODS_DISPLAY_ENABLED_MANAGED
= 1,
401 USER_PODS_DISPLAY_DISABLED_REGULAR
= 2,
402 USER_PODS_DISPLAY_DISABLED_MANAGED
= 3,
403 // Maximum histogram value.
404 NUM_USER_PODS_DISPLAY
= 4
407 // Sends metrics for user pods display when existing user has logged in.
408 void SendUserPodsMetrics();
410 UserSessionManagerDelegate
* delegate_
;
412 // Authentication/user context.
413 UserContext user_context_
;
414 scoped_refptr
<Authenticator
> authenticator_
;
415 StartSessionType start_session_type_
;
417 // Injected user context for stub authenticator.
418 scoped_ptr
<UserContext
> injected_user_context_
;
420 // True if the authentication context's cookie jar contains authentication
421 // cookies from the authentication extension login flow.
422 bool has_auth_cookies_
;
424 // Active user session restoration related members.
426 // True if user sessions has been restored after crash.
427 // On a normal boot then login into user sessions this will be false.
428 bool user_sessions_restored_
;
430 // True if user sessions restoration after crash is in progress.
431 bool user_sessions_restore_in_progress_
;
433 // User sessions that have to be restored after browser crash.
434 // [user_id] > [user_id_hash]
435 SessionManagerClient::ActiveSessionsMap pending_user_sessions_
;
437 base::ObserverList
<chromeos::UserSessionStateObserver
>
438 session_state_observer_list_
;
440 // OAuth2 session related members.
442 // True if we should restart chrome right after session restore.
443 bool exit_after_session_restore_
;
445 // Sesion restore strategy.
446 OAuth2LoginManager::SessionRestoreStrategy session_restore_strategy_
;
448 // Set of user_id for those users that we should restore authentication
449 // session when notified about online state change.
450 SigninSessionRestoreStateSet pending_signin_restore_sessions_
;
452 // Kiosk mode related members.
453 // Chrome oauth client id and secret - override values for kiosk mode.
454 std::string chrome_client_id_
;
455 std::string chrome_client_secret_
;
457 // Per-user-session Input Methods states.
458 std::map
<Profile
*, scoped_refptr
<input_method::InputMethodManager::State
>,
459 ProfileCompare
> default_ime_states_
;
461 // Manages Easy unlock cryptohome keys.
462 scoped_ptr
<EasyUnlockKeyManager
> easy_unlock_key_manager_
;
463 bool running_easy_unlock_key_ops_
;
464 base::Closure easy_unlock_key_ops_finished_callback_
;
466 // Whether should fetch token handles, tests may override this value.
467 bool should_obtain_handles_
;
469 scoped_ptr
<TokenHandleUtil
> token_handle_util_
;
470 scoped_ptr
<TokenHandleFetcher
> token_handle_fetcher_
;
472 // Whether should launch browser, tests may override this value.
473 bool should_launch_browser_
;
475 // Child account status is necessary for InitializeStartUrls call.
476 bool waiting_for_child_account_status_
;
478 base::WeakPtrFactory
<UserSessionManager
> weak_factory_
;
480 DISALLOW_COPY_AND_ASSIGN(UserSessionManager
);
483 } // namespace chromeos
485 #endif // CHROME_BROWSER_CHROMEOS_LOGIN_SESSION_USER_SESSION_MANAGER_H_