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

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

Issue 11649055: OAuth2 sign-in flow for ChromeOS (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: clang fix Created 7 years, 11 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
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/chromeos/login/login_utils.h" 5 #include "chrome/browser/chromeos/login/login_utils.h"
6 6
7 #include <algorithm> 7 #include <algorithm>
8 #include <vector> 8 #include <vector>
9 9
10 #include "ash/ash_switches.h" 10 #include "ash/ash_switches.h"
(...skipping 12 matching lines...) Expand all
23 #include "base/stringprintf.h" 23 #include "base/stringprintf.h"
24 #include "base/synchronization/lock.h" 24 #include "base/synchronization/lock.h"
25 #include "base/task_runner_util.h" 25 #include "base/task_runner_util.h"
26 #include "base/threading/worker_pool.h" 26 #include "base/threading/worker_pool.h"
27 #include "base/time.h" 27 #include "base/time.h"
28 #include "base/utf_string_conversions.h" 28 #include "base/utf_string_conversions.h"
29 #include "cc/switches.h" 29 #include "cc/switches.h"
30 #include "chrome/browser/browser_process.h" 30 #include "chrome/browser/browser_process.h"
31 #include "chrome/browser/browser_shutdown.h" 31 #include "chrome/browser/browser_shutdown.h"
32 #include "chrome/browser/chromeos/boot_times_loader.h" 32 #include "chrome/browser/chromeos/boot_times_loader.h"
33 #include "chrome/browser/chromeos/cros/cert_library.h"
34 #include "chrome/browser/chromeos/cros/cros_library.h" 33 #include "chrome/browser/chromeos/cros/cros_library.h"
35 #include "chrome/browser/chromeos/cros/cryptohome_library.h" 34 #include "chrome/browser/chromeos/cros/cryptohome_library.h"
36 #include "chrome/browser/chromeos/cros/network_library.h" 35 #include "chrome/browser/chromeos/cros/network_library.h"
37 #include "chrome/browser/chromeos/input_method/input_method_configuration.h" 36 #include "chrome/browser/chromeos/input_method/input_method_configuration.h"
38 #include "chrome/browser/chromeos/input_method/input_method_manager.h" 37 #include "chrome/browser/chromeos/input_method/input_method_manager.h"
39 #include "chrome/browser/chromeos/input_method/input_method_util.h" 38 #include "chrome/browser/chromeos/input_method/input_method_util.h"
40 #include "chrome/browser/chromeos/login/language_switch_menu.h" 39 #include "chrome/browser/chromeos/login/language_switch_menu.h"
41 #include "chrome/browser/chromeos/login/login_display_host.h" 40 #include "chrome/browser/chromeos/login/login_display_host.h"
42 #include "chrome/browser/chromeos/login/oauth1_token_fetcher.h" 41 #include "chrome/browser/chromeos/login/oauth_login_manager.h"
43 #include "chrome/browser/chromeos/login/oauth_login_verifier.h"
44 #include "chrome/browser/chromeos/login/parallel_authenticator.h" 42 #include "chrome/browser/chromeos/login/parallel_authenticator.h"
45 #include "chrome/browser/chromeos/login/policy_oauth_fetcher.h"
46 #include "chrome/browser/chromeos/login/profile_auth_data.h" 43 #include "chrome/browser/chromeos/login/profile_auth_data.h"
47 #include "chrome/browser/chromeos/login/screen_locker.h" 44 #include "chrome/browser/chromeos/login/screen_locker.h"
48 #include "chrome/browser/chromeos/login/user_manager.h" 45 #include "chrome/browser/chromeos/login/user_manager.h"
49 #include "chrome/browser/chromeos/settings/cros_settings.h" 46 #include "chrome/browser/chromeos/settings/cros_settings.h"
50 #include "chrome/browser/chromeos/settings/cros_settings_names.h" 47 #include "chrome/browser/chromeos/settings/cros_settings_names.h"
51 #include "chrome/browser/extensions/extension_service.h" 48 #include "chrome/browser/extensions/extension_service.h"
52 #include "chrome/browser/first_run/first_run.h" 49 #include "chrome/browser/first_run/first_run.h"
53 #include "chrome/browser/google/google_util_chromeos.h" 50 #include "chrome/browser/google/google_util_chromeos.h"
54 #include "chrome/browser/net/chrome_url_request_context.h" 51 #include "chrome/browser/net/chrome_url_request_context.h"
55 #include "chrome/browser/net/preconnect.h" 52 #include "chrome/browser/net/preconnect.h"
(...skipping 19 matching lines...) Expand all
75 #include "chrome/common/pref_names.h" 72 #include "chrome/common/pref_names.h"
76 #include "chrome/common/url_constants.h" 73 #include "chrome/common/url_constants.h"
77 #include "chromeos/chromeos_switches.h" 74 #include "chromeos/chromeos_switches.h"
78 #include "chromeos/dbus/dbus_thread_manager.h" 75 #include "chromeos/dbus/dbus_thread_manager.h"
79 #include "chromeos/dbus/session_manager_client.h" 76 #include "chromeos/dbus/session_manager_client.h"
80 #include "content/public/browser/browser_thread.h" 77 #include "content/public/browser/browser_thread.h"
81 #include "content/public/browser/notification_observer.h" 78 #include "content/public/browser/notification_observer.h"
82 #include "content/public/browser/notification_service.h" 79 #include "content/public/browser/notification_service.h"
83 #include "content/public/common/content_switches.h" 80 #include "content/public/common/content_switches.h"
84 #include "google_apis/gaia/gaia_auth_consumer.h" 81 #include "google_apis/gaia/gaia_auth_consumer.h"
82 #include "google_apis/gaia/gaia_constants.h"
85 #include "google_apis/gaia/gaia_urls.h" 83 #include "google_apis/gaia/gaia_urls.h"
86 #include "googleurl/src/gurl.h" 84 #include "googleurl/src/gurl.h"
87 #include "media/base/media_switches.h" 85 #include "media/base/media_switches.h"
88 #include "net/base/network_change_notifier.h" 86 #include "net/base/network_change_notifier.h"
89 #include "net/url_request/url_request_context.h" 87 #include "net/url_request/url_request_context.h"
90 #include "net/url_request/url_request_context_getter.h" 88 #include "net/url_request/url_request_context_getter.h"
91 #include "ui/base/ui_base_switches.h" 89 #include "ui/base/ui_base_switches.h"
92 #include "ui/compositor/compositor_switches.h" 90 #include "ui/compositor/compositor_switches.h"
93 #include "ui/gfx/switches.h" 91 #include "ui/gfx/switches.h"
94 #include "ui/gl/gl_switches.h" 92 #include "ui/gl/gl_switches.h"
(...skipping 77 matching lines...) Expand 10 before | Expand all | Expand 10 after
172 } 170 }
173 171
174 int pid_; 172 int pid_;
175 std::string command_line_; 173 std::string command_line_;
176 PrefService* local_state_; 174 PrefService* local_state_;
177 base::OneShotTimer<JobRestartRequest> timer_; 175 base::OneShotTimer<JobRestartRequest> timer_;
178 }; 176 };
179 177
180 class LoginUtilsImpl 178 class LoginUtilsImpl
181 : public LoginUtils, 179 : public LoginUtils,
182 public OAuth1TokenFetcher::Delegate, 180 public OAuthLoginManager::Delegate,
183 public OAuthLoginVerifier::Delegate,
184 public net::NetworkChangeNotifier::ConnectionTypeObserver, 181 public net::NetworkChangeNotifier::ConnectionTypeObserver,
185 public content::NotificationObserver, 182 public content::NotificationObserver,
186 public base::SupportsWeakPtr<LoginUtilsImpl> { 183 public base::SupportsWeakPtr<LoginUtilsImpl> {
187 public: 184 public:
188 LoginUtilsImpl() 185 LoginUtilsImpl()
189 : pending_requests_(false), 186 : using_oauth_(false),
190 using_oauth_(false),
191 has_web_auth_cookies_(false), 187 has_web_auth_cookies_(false),
188 login_manager_(OAuthLoginManager::Create(this)),
192 delegate_(NULL), 189 delegate_(NULL),
193 job_restart_request_(NULL), 190 job_restart_request_(NULL),
194 should_restore_auth_session_(false), 191 should_restore_auth_session_(false),
195 url_request_context_getter_(NULL) { 192 url_request_context_getter_(NULL) {
196 net::NetworkChangeNotifier::AddConnectionTypeObserver(this); 193 net::NetworkChangeNotifier::AddConnectionTypeObserver(this);
197 // During tests, the browser_process may not be initialized yet causing 194 // During tests, the browser_process may not be initialized yet causing
198 // this to fail. 195 // this to fail.
199 if (g_browser_process) { 196 if (g_browser_process) {
200 registrar_.Add( 197 registrar_.Add(
201 this, 198 this,
202 chrome::NOTIFICATION_PROFILE_URL_REQUEST_CONTEXT_GETTER_INITIALIZED, 199 chrome::NOTIFICATION_PROFILE_URL_REQUEST_CONTEXT_GETTER_INITIALIZED,
203 content::Source<Profile>(ProfileManager::GetDefaultProfile())); 200 content::Source<Profile>(ProfileManager::GetDefaultProfile()));
204 } 201 }
205 } 202 }
206 203
207 virtual ~LoginUtilsImpl() { 204 virtual ~LoginUtilsImpl() {
208 net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this); 205 net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
209 } 206 }
210 207
211 // LoginUtils implementation: 208 // LoginUtils implementation:
212 virtual void DoBrowserLaunch(Profile* profile, 209 virtual void DoBrowserLaunch(Profile* profile,
213 LoginDisplayHost* login_host) OVERRIDE; 210 LoginDisplayHost* login_host) OVERRIDE;
214 virtual void PrepareProfile( 211 virtual void PrepareProfile(
215 const std::string& username, 212 const std::string& username,
216 const std::string& display_email, 213 const std::string& display_email,
217 const std::string& password, 214 const std::string& password,
218 bool pending_requests,
219 bool using_oauth, 215 bool using_oauth,
220 bool has_cookies, 216 bool has_cookies,
221 LoginUtils::Delegate* delegate) OVERRIDE; 217 LoginUtils::Delegate* delegate) OVERRIDE;
222 virtual void DelegateDeleted(LoginUtils::Delegate* delegate) OVERRIDE; 218 virtual void DelegateDeleted(LoginUtils::Delegate* delegate) OVERRIDE;
223 virtual void CompleteOffTheRecordLogin(const GURL& start_url) OVERRIDE; 219 virtual void CompleteOffTheRecordLogin(const GURL& start_url) OVERRIDE;
224 virtual void SetFirstLoginPrefs(PrefService* prefs) OVERRIDE; 220 virtual void SetFirstLoginPrefs(PrefService* prefs) OVERRIDE;
225 virtual scoped_refptr<Authenticator> CreateAuthenticator( 221 virtual scoped_refptr<Authenticator> CreateAuthenticator(
226 LoginStatusConsumer* consumer) OVERRIDE; 222 LoginStatusConsumer* consumer) OVERRIDE;
227 virtual void PrewarmAuthentication() OVERRIDE; 223 virtual void PrewarmAuthentication() OVERRIDE;
228 virtual void RestoreAuthenticationSession(Profile* profile) OVERRIDE; 224 virtual void RestoreAuthenticationSession(Profile* profile) OVERRIDE;
229 virtual void StartTokenServices(Profile* user_profile) OVERRIDE;
230 virtual void StartSignedInServices(
231 Profile* profile,
232 const GaiaAuthConsumer::ClientLoginResult& credentials) OVERRIDE;
233 virtual void StopBackgroundFetchers() OVERRIDE; 225 virtual void StopBackgroundFetchers() OVERRIDE;
234 virtual void InitRlzDelayed(Profile* user_profile) OVERRIDE; 226 virtual void InitRlzDelayed(Profile* user_profile) OVERRIDE;
235 227
236 // OAuth1TokenFetcher::Delegate overrides. 228 // OAuthLoginManager::Delegate overrides.
237 void OnOAuth1AccessTokenAvailable(const std::string& token, 229 virtual void OnCompletedAuthentication(Profile* user_profile) OVERRIDE;
238 const std::string& secret) OVERRIDE; 230 virtual void OnFoundStoredTokens() OVERRIDE;
239 void OnOAuth1AccessTokenFetchFailed() OVERRIDE;
240
241 // OAuthLoginVerifier::Delegate overrides.
242 virtual void OnOAuthVerificationSucceeded(const std::string& user_name,
243 const std::string& sid,
244 const std::string& lsid,
245 const std::string& auth) OVERRIDE;
246 virtual void OnOAuthVerificationFailed(const std::string& user_name) OVERRIDE;
247 231
248 // net::NetworkChangeNotifier::ConnectionTypeObserver overrides. 232 // net::NetworkChangeNotifier::ConnectionTypeObserver overrides.
249 virtual void OnConnectionTypeChanged( 233 virtual void OnConnectionTypeChanged(
250 net::NetworkChangeNotifier::ConnectionType type) OVERRIDE; 234 net::NetworkChangeNotifier::ConnectionType type) OVERRIDE;
251 235
252 // content::NotificationObserver overrides. 236 // content::NotificationObserver overrides.
253 virtual void Observe(int type, 237 virtual void Observe(int type,
254 const content::NotificationSource& source, 238 const content::NotificationSource& source,
255 const content::NotificationDetails& details) OVERRIDE; 239 const content::NotificationDetails& details) OVERRIDE;
256 240
257 protected: 241 protected:
258 virtual std::string GetOffTheRecordCommandLine( 242 virtual std::string GetOffTheRecordCommandLine(
259 const GURL& start_url, 243 const GURL& start_url,
260 const CommandLine& base_command_line, 244 const CommandLine& base_command_line,
261 CommandLine *command_line); 245 CommandLine *command_line);
262 246
263 private: 247 private:
264 // Restarts OAuth session authentication check. 248 // Restarts OAuth session authentication check.
265 void KickStartAuthentication(Profile* profile); 249 void KickStartAuthentication(Profile* profile);
266 250
267 // Reads OAuth1 token from user profile's prefs.
268 bool ReadOAuth1AccessToken(Profile* user_profile,
269 std::string* token,
270 std::string* secret);
271
272 // Stores OAuth1 token + secret in profile's prefs.
273 void StoreOAuth1AccessToken(Profile* user_profile,
274 const std::string& token,
275 const std::string& secret);
276
277 // Verifies OAuth1 token by doing OAuthLogin and fetching credentials.
278 void VerifyOAuth1AccessToken(Profile* user_profile,
279 const std::string& token,
280 const std::string& secret);
281
282 // Fetch all secondary (OAuth2) tokens given OAuth1 access |token| and
283 // |secret|.
284 void FetchSecondaryTokens(Profile* offrecord_profile,
285 const std::string& token,
286 const std::string& secret);
287
288 // Fetch user credentials (sid/lsid) given OAuth1 access |token| and |secret|.
289 void FetchCredentials(Profile* user_profile,
290 const std::string& token,
291 const std::string& secret);
292
293 // Fetch enterprise policy OAuth2 given OAuth1 access |token| and |secret|.
294 void FetchPolicyToken(Profile* offrecord_profile,
295 const std::string& token,
296 const std::string& secret);
297
298 // Check user's profile for kApplicationLocale setting. 251 // Check user's profile for kApplicationLocale setting.
299 void RespectLocalePreference(Profile* pref); 252 void RespectLocalePreference(Profile* pref);
300 253
301 // Initializes basic preferences for newly created profile. 254 // Initializes basic preferences for newly created profile.
302 void InitProfilePreferences(Profile* user_profile); 255 void InitProfilePreferences(Profile* user_profile);
303 256
304 // Callback for asynchronous profile creation. 257 // Callback for asynchronous profile creation.
305 void OnProfileCreated(Profile* profile, 258 void OnProfileCreated(Profile* profile,
306 Profile::CreateStatus status); 259 Profile::CreateStatus status);
307 260
308 // Callback to resume profile creation after transferring auth data from 261 // Callback to resume profile creation after transferring auth data from
309 // the authentication profile. 262 // the authentication profile.
310 void CompleteProfileCreate(Profile* user_profile); 263 void CompleteProfileCreate(Profile* user_profile);
311 264
312 // Finalized profile preparation. 265 // Finalized profile preparation.
313 void FinalizePrepareProfile(Profile* user_profile); 266 void FinalizePrepareProfile(Profile* user_profile);
314 267
315 // Restores GAIA auth cookies for the created profile. 268 // Restores GAIA auth cookies for the created user profile from OAuth2 token.
316 void RestoreAuthCookies(Profile* user_profile); 269 void RestoreAuthSession(Profile* user_profile,
270 bool restore_from_auth_cookies);
317 271
318 // Initializes RLZ. If |disabled| is true, RLZ pings are disabled. 272 // Initializes RLZ. If |disabled| is true, RLZ pings are disabled.
319 void InitRlz(Profile* user_profile, bool disabled); 273 void InitRlz(Profile* user_profile, bool disabled);
320 274
275 // Starts signing related services. Initiates TokenService token retrieval.
276 void StartSignedInServices(Profile* profile);
277
321 std::string password_; 278 std::string password_;
322 bool pending_requests_;
323 bool using_oauth_; 279 bool using_oauth_;
324 // True if the authentication profile's cookie jar should contain 280 // True if the authentication profile's cookie jar should contain
325 // authentication cookies from the authentication extension log in flow. 281 // authentication cookies from the authentication extension log in flow.
326 bool has_web_auth_cookies_; 282 bool has_web_auth_cookies_;
327 // Has to be scoped_refptr, see comment for CreateAuthenticator(...). 283 // Has to be scoped_refptr, see comment for CreateAuthenticator(...).
328 scoped_refptr<Authenticator> authenticator_; 284 scoped_refptr<Authenticator> authenticator_;
329 scoped_ptr<PolicyOAuthFetcher> policy_oauth_fetcher_; 285 scoped_ptr<OAuthLoginManager> login_manager_;
330 scoped_ptr<OAuth1TokenFetcher> oauth1_token_fetcher_;
331 scoped_ptr<OAuthLoginVerifier> oauth_login_verifier_;
332 286
333 // Delegate to be fired when the profile will be prepared. 287 // Delegate to be fired when the profile will be prepared.
334 LoginUtils::Delegate* delegate_; 288 LoginUtils::Delegate* delegate_;
335 289
336 // Used to restart Chrome to switch to the guest mode. 290 // Used to restart Chrome to switch to the guest mode.
337 JobRestartRequest* job_restart_request_; 291 JobRestartRequest* job_restart_request_;
338 292
339 // True if should restore authentication session when notified about 293 // True if should restore authentication session when notified about
340 // online state change. 294 // online state change.
341 bool should_restore_auth_session_; 295 bool should_restore_auth_session_;
(...skipping 64 matching lines...) Expand 10 before | Expand all | Expand 10 after
406 // browser before it is dereferenced by the login host. 360 // browser before it is dereferenced by the login host.
407 if (login_host) 361 if (login_host)
408 login_host->OnSessionStart(); 362 login_host->OnSessionStart();
409 UserManager::Get()->SessionStarted(); 363 UserManager::Get()->SessionStarted();
410 } 364 }
411 365
412 void LoginUtilsImpl::PrepareProfile( 366 void LoginUtilsImpl::PrepareProfile(
413 const std::string& username, 367 const std::string& username,
414 const std::string& display_email, 368 const std::string& display_email,
415 const std::string& password, 369 const std::string& password,
416 bool pending_requests,
417 bool using_oauth, 370 bool using_oauth,
418 bool has_cookies, 371 bool has_cookies,
419 LoginUtils::Delegate* delegate) { 372 LoginUtils::Delegate* delegate) {
420 BootTimesLoader* btl = BootTimesLoader::Get(); 373 BootTimesLoader* btl = BootTimesLoader::Get();
421 374
422 VLOG(1) << "Completing login for " << username; 375 VLOG(1) << "Completing login for " << username;
423 376
424 btl->AddLoginTimeMarker("StartSession-Start", false); 377 btl->AddLoginTimeMarker("StartSession-Start", false);
425 DBusThreadManager::Get()->GetSessionManagerClient()->StartSession( 378 DBusThreadManager::Get()->GetSessionManagerClient()->StartSession(
426 username); 379 username);
427 btl->AddLoginTimeMarker("StartSession-End", false); 380 btl->AddLoginTimeMarker("StartSession-End", false);
428 381
429 btl->AddLoginTimeMarker("UserLoggedIn-Start", false); 382 btl->AddLoginTimeMarker("UserLoggedIn-Start", false);
430 UserManager* user_manager = UserManager::Get(); 383 UserManager* user_manager = UserManager::Get();
431 user_manager->UserLoggedIn(username, false); 384 user_manager->UserLoggedIn(username, false);
432 btl->AddLoginTimeMarker("UserLoggedIn-End", false); 385 btl->AddLoginTimeMarker("UserLoggedIn-End", false);
433 386
434 // Switch log file as soon as possible. 387 // Switch log file as soon as possible.
435 if (base::chromeos::IsRunningOnChromeOS()) 388 if (base::chromeos::IsRunningOnChromeOS())
436 logging::RedirectChromeLogging(*(CommandLine::ForCurrentProcess())); 389 logging::RedirectChromeLogging(*(CommandLine::ForCurrentProcess()));
437 390
438 // Update user's displayed email. 391 // Update user's displayed email.
439 if (!display_email.empty()) 392 if (!display_email.empty())
440 user_manager->SaveUserDisplayEmail(username, display_email); 393 user_manager->SaveUserDisplayEmail(username, display_email);
441 394
442 password_ = password; 395 password_ = password;
443 396
444 pending_requests_ = pending_requests;
445 using_oauth_ = using_oauth; 397 using_oauth_ = using_oauth;
446 has_web_auth_cookies_ = has_cookies; 398 has_web_auth_cookies_ = has_cookies;
447 delegate_ = delegate; 399 delegate_ = delegate;
448 400
449 policy::BrowserPolicyConnector* connector = 401 policy::BrowserPolicyConnector* connector =
450 g_browser_process->browser_policy_connector(); 402 g_browser_process->browser_policy_connector();
451 403
452 // If this is an enterprise device and the user belongs to the enterprise 404 // If this is an enterprise device and the user belongs to the enterprise
453 // domain, then wait for a policy fetch before logging the user in. This 405 // domain, then wait for a policy fetch before logging the user in. This
454 // will delay Profile creation until the policy is fetched, so that features 406 // will delay Profile creation until the policy is fetched, so that features
(...skipping 22 matching lines...) Expand all
477 // requires the DeviceManagement token. Try to fetch it now. 429 // requires the DeviceManagement token. Try to fetch it now.
478 // TODO(atwilson): This is somewhat racy, as we are trying to fetch a 430 // TODO(atwilson): This is somewhat racy, as we are trying to fetch a
479 // DMToken in parallel with loading the cached policy blob (there could 431 // DMToken in parallel with loading the cached policy blob (there could
480 // already be a DMToken in the cached policy). Once the legacy policy 432 // already be a DMToken in the cached policy). Once the legacy policy
481 // framework is removed, this code can register a 433 // framework is removed, this code can register a
482 // CloudPolicyService::Observer to check whether the CloudPolicyClient was 434 // CloudPolicyService::Observer to check whether the CloudPolicyClient was
483 // able to register itself using the cached policy data, and then only 435 // able to register itself using the cached policy data, and then only
484 // create a PolicyOAuthFetcher if the client is still unregistered 436 // create a PolicyOAuthFetcher if the client is still unregistered
485 // (http://crbug.com/143187). 437 // (http://crbug.com/143187).
486 VLOG(1) << "Profile creation requires policy token, fetching now"; 438 VLOG(1) << "Profile creation requires policy token, fetching now";
487 policy_oauth_fetcher_.reset( 439 login_manager_->RestorePolicyTokens(
488 new PolicyOAuthFetcher(authenticator_->authentication_profile())); 440 authenticator_->authentication_profile()->GetRequestContext());
489 policy_oauth_fetcher_->Start();
490 } 441 }
491 } 442 }
492 443
493 void LoginUtilsImpl::DelegateDeleted(LoginUtils::Delegate* delegate) { 444 void LoginUtilsImpl::DelegateDeleted(LoginUtils::Delegate* delegate) {
494 if (delegate_ == delegate) 445 if (delegate_ == delegate)
495 delegate_ = NULL; 446 delegate_ = NULL;
496 } 447 }
497 448
498 void LoginUtilsImpl::InitProfilePreferences(Profile* user_profile) { 449 void LoginUtilsImpl::InitProfilePreferences(Profile* user_profile) {
499 if (UserManager::Get()->IsCurrentUserNew()) 450 if (UserManager::Get()->IsCurrentUserNew())
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
535 case Profile::CREATE_STATUS_FAIL: 486 case Profile::CREATE_STATUS_FAIL:
536 default: 487 default:
537 NOTREACHED(); 488 NOTREACHED();
538 return; 489 return;
539 } 490 }
540 491
541 BootTimesLoader* btl = BootTimesLoader::Get(); 492 BootTimesLoader* btl = BootTimesLoader::Get();
542 btl->AddLoginTimeMarker("UserProfileGotten", false); 493 btl->AddLoginTimeMarker("UserProfileGotten", false);
543 494
544 if (using_oauth_) { 495 if (using_oauth_) {
545 // Reuse the access token fetched by the PolicyOAuthFetcher, if it was
546 // used to fetch policies before Profile creation.
547 if (policy_oauth_fetcher_.get() &&
548 !policy_oauth_fetcher_->oauth1_token().empty()) {
549 VLOG(1) << "Resuming profile creation after fetching policy token";
550 StoreOAuth1AccessToken(user_profile,
551 policy_oauth_fetcher_->oauth1_token(),
552 policy_oauth_fetcher_->oauth1_secret());
553 }
554
555 // Transfer proxy authentication cache, cookies (optionally) and server 496 // Transfer proxy authentication cache, cookies (optionally) and server
556 // bound certs from the profile that was used for authentication. This 497 // bound certs from the profile that was used for authentication. This
557 // profile contains cookies that auth extension should have already put in 498 // profile contains cookies that auth extension should have already put in
558 // place that will ensure that the newly created session is authenticated 499 // place that will ensure that the newly created session is authenticated
559 // for the websites that work with the used authentication schema. 500 // for the websites that work with the used authentication schema.
560 ProfileAuthData::Transfer(authenticator_->authentication_profile(), 501 ProfileAuthData::Transfer(authenticator_->authentication_profile(),
561 user_profile, 502 user_profile,
562 has_web_auth_cookies_, // transfer_cookies 503 has_web_auth_cookies_, // transfer_cookies
563 base::Bind( 504 base::Bind(
564 &LoginUtilsImpl::CompleteProfileCreate, 505 &LoginUtilsImpl::CompleteProfileCreate,
565 AsWeakPtr(), 506 AsWeakPtr(),
566 user_profile)); 507 user_profile));
567 return; 508 return;
568 } 509 }
569 510
570 FinalizePrepareProfile(user_profile); 511 FinalizePrepareProfile(user_profile);
571 } 512 }
572 513
573 void LoginUtilsImpl::RestoreAuthCookies(Profile* user_profile) { 514 void LoginUtilsImpl::CompleteProfileCreate(Profile* user_profile) {
574 std::string oauth1_token; 515 RestoreAuthSession(user_profile, has_web_auth_cookies_);
575 std::string oauth1_secret; 516 FinalizePrepareProfile(user_profile);
576 if (ReadOAuth1AccessToken(user_profile, &oauth1_token, &oauth1_secret) ||
577 !has_web_auth_cookies_) {
578 // Verify OAuth access token when we find it in the profile and always if
579 // if we don't have cookies.
580 // TODO(xiyuan): Change back to use authenticator to verify token when
581 // we support Gaia in lock screen.
582 VerifyOAuth1AccessToken(user_profile, oauth1_token, oauth1_secret);
583 } else {
584 // If we don't have it, fetch OAuth1 access token.
585 // Once we get that, we will kick off individual requests for OAuth2
586 // tokens for all our services.
587 // Use off-the-record profile that was used for this step. It should
588 // already contain all needed cookies that will let us skip GAIA's user
589 // authentication UI.
590 //
591 // TODO(rickcam) We should use an isolated App here.
592 oauth1_token_fetcher_.reset(
593 new OAuth1TokenFetcher(this,
594 authenticator_->authentication_profile()));
595 oauth1_token_fetcher_->Start();
596 }
597 } 517 }
598 518
599 void LoginUtilsImpl::CompleteProfileCreate(Profile* user_profile) { 519 void LoginUtilsImpl::RestoreAuthSession(Profile* user_profile,
600 RestoreAuthCookies(user_profile); 520 bool restore_from_auth_cookies) {
601 FinalizePrepareProfile(user_profile); 521 DCHECK(authenticator_ || !restore_from_auth_cookies);
522 // Remove legacy OAuth1 token if we have one. If it's valid, we should already
523 // have OAuth2 refresh token in TokenService that could be used to retrieve
524 // all other tokens and credentials.
525 login_manager_->RestoreSession(
526 user_profile,
527 authenticator_ ?
528 authenticator_->authentication_profile()->GetRequestContext() :
529 NULL,
530 restore_from_auth_cookies);
602 } 531 }
603 532
604 void LoginUtilsImpl::FinalizePrepareProfile(Profile* user_profile) { 533 void LoginUtilsImpl::FinalizePrepareProfile(Profile* user_profile) {
605 BootTimesLoader* btl = BootTimesLoader::Get(); 534 BootTimesLoader* btl = BootTimesLoader::Get();
606 // Own TPM device if, for any reason, it has not been done in EULA 535 // Own TPM device if, for any reason, it has not been done in EULA
607 // wizard screen. 536 // wizard screen.
608 CryptohomeLibrary* cryptohome = CrosLibrary::Get()->GetCryptohomeLibrary(); 537 CryptohomeLibrary* cryptohome = CrosLibrary::Get()->GetCryptohomeLibrary();
609 btl->AddLoginTimeMarker("TPMOwn-Start", false); 538 btl->AddLoginTimeMarker("TPMOwn-Start", false);
610 if (cryptohome->TpmIsEnabled() && !cryptohome->TpmIsBeingOwned()) { 539 if (cryptohome->TpmIsEnabled() && !cryptohome->TpmIsBeingOwned()) {
611 if (cryptohome->TpmIsOwned()) { 540 if (cryptohome->TpmIsOwned()) {
(...skipping 59 matching lines...) Expand 10 before | Expand all | Expand 10 after
671 // Negative ping delay means to send ping immediately after a first search is 600 // Negative ping delay means to send ping immediately after a first search is
672 // recorded. 601 // recorded.
673 RLZTracker::InitRlzFromProfileDelayed( 602 RLZTracker::InitRlzFromProfileDelayed(
674 user_profile, UserManager::Get()->IsCurrentUserNew(), 603 user_profile, UserManager::Get()->IsCurrentUserNew(),
675 ping_delay < 0, base::TimeDelta::FromMilliseconds(abs(ping_delay))); 604 ping_delay < 0, base::TimeDelta::FromMilliseconds(abs(ping_delay)));
676 if (delegate_) 605 if (delegate_)
677 delegate_->OnRlzInitialized(user_profile); 606 delegate_->OnRlzInitialized(user_profile);
678 #endif 607 #endif
679 } 608 }
680 609
681 void LoginUtilsImpl::StartTokenServices(Profile* user_profile) { 610 void LoginUtilsImpl::StartSignedInServices(Profile* user_profile) {
682 std::string oauth1_token;
683 std::string oauth1_secret;
684 if (!ReadOAuth1AccessToken(user_profile, &oauth1_token, &oauth1_secret))
685 return;
686
687 FetchSecondaryTokens(user_profile->GetOffTheRecordProfile(),
688 oauth1_token, oauth1_secret);
689 }
690
691 void LoginUtilsImpl::StartSignedInServices(
692 Profile* user_profile,
693 const GaiaAuthConsumer::ClientLoginResult& credentials) {
694 // Fetch/Create the SigninManager - this will cause the TokenService to load 611 // Fetch/Create the SigninManager - this will cause the TokenService to load
695 // tokens for the currently signed-in user if the SigninManager hasn't already 612 // tokens for the currently signed-in user if the SigninManager hasn't already
696 // been initialized. 613 // been initialized.
697 SigninManager* signin = SigninManagerFactory::GetForProfile(user_profile); 614 SigninManager* signin = SigninManagerFactory::GetForProfile(user_profile);
698 DCHECK(signin); 615 DCHECK(signin);
699 // Make sure SigninManager is connected to our current user (this should 616 // Make sure SigninManager is connected to our current user (this should
700 // happen automatically because we set kGoogleServicesUsername in 617 // happen automatically because we set kGoogleServicesUsername in
701 // OnProfileCreated()). 618 // OnProfileCreated()).
702 DCHECK_EQ(UserManager::Get()->GetLoggedInUser()->display_email(), 619 DCHECK_EQ(UserManager::Get()->GetLoggedInUser()->display_email(),
703 signin->GetAuthenticatedUsername()); 620 signin->GetAuthenticatedUsername());
(...skipping 11 matching lines...) Expand all
715 GoogleServiceSigninSuccessDetails details( 632 GoogleServiceSigninSuccessDetails details(
716 signin->GetAuthenticatedUsername(), 633 signin->GetAuthenticatedUsername(),
717 password_); 634 password_);
718 content::NotificationService::current()->Notify( 635 content::NotificationService::current()->Notify(
719 chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL, 636 chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL,
720 content::Source<Profile>(user_profile), 637 content::Source<Profile>(user_profile),
721 content::Details<const GoogleServiceSigninSuccessDetails>(&details)); 638 content::Details<const GoogleServiceSigninSuccessDetails>(&details));
722 } 639 }
723 } 640 }
724 password_.clear(); 641 password_.clear();
725 TokenService* token_service =
726 TokenServiceFactory::GetForProfile(user_profile);
727 token_service->UpdateCredentials(credentials);
728 if (token_service->AreCredentialsValid())
729 token_service->StartFetchingTokens();
730 } 642 }
731 643
732 void LoginUtilsImpl::RespectLocalePreference(Profile* profile) { 644 void LoginUtilsImpl::RespectLocalePreference(Profile* profile) {
733 DCHECK(profile != NULL); 645 DCHECK(profile != NULL);
734 PrefService* prefs = profile->GetPrefs(); 646 PrefService* prefs = profile->GetPrefs();
735 DCHECK(prefs != NULL); 647 DCHECK(prefs != NULL);
736 if (g_browser_process == NULL) 648 if (g_browser_process == NULL)
737 return; 649 return;
738 650
739 std::string pref_locale = prefs->GetString(prefs::kApplicationLocale); 651 std::string pref_locale = prefs->GetString(prefs::kApplicationLocale);
(...skipping 278 matching lines...) Expand 10 before | Expand all | Expand 10 after
1018 void LoginUtilsImpl::RestoreAuthenticationSession(Profile* user_profile) { 930 void LoginUtilsImpl::RestoreAuthenticationSession(Profile* user_profile) {
1019 // We don't need to restore session for demo/guest users. 931 // We don't need to restore session for demo/guest users.
1020 if (!UserManager::Get()->IsUserLoggedIn() || 932 if (!UserManager::Get()->IsUserLoggedIn() ||
1021 UserManager::Get()->IsLoggedInAsGuest() || 933 UserManager::Get()->IsLoggedInAsGuest() ||
1022 UserManager::Get()->IsLoggedInAsDemoUser()) { 934 UserManager::Get()->IsLoggedInAsDemoUser()) {
1023 return; 935 return;
1024 } 936 }
1025 937
1026 if (!net::NetworkChangeNotifier::IsOffline()) { 938 if (!net::NetworkChangeNotifier::IsOffline()) {
1027 should_restore_auth_session_ = false; 939 should_restore_auth_session_ = false;
1028 KickStartAuthentication(user_profile); 940 RestoreAuthSession(user_profile, false);
1029 } else { 941 } else {
1030 // Even if we're online we should wait till initial 942 // Even if we're online we should wait till initial
1031 // OnConnectionTypeChanged() call. Otherwise starting fetchers too early may 943 // OnConnectionTypeChanged() call. Otherwise starting fetchers too early may
1032 // end up cancelling all request when initial network connection type is 944 // end up cancelling all request when initial network connection type is
1033 // processed. See http://crbug.com/121643. 945 // processed. See http://crbug.com/121643.
1034 should_restore_auth_session_ = true; 946 should_restore_auth_session_ = true;
1035 } 947 }
1036 } 948 }
1037 949
1038 void LoginUtilsImpl::KickStartAuthentication(Profile* user_profile) { 950 void LoginUtilsImpl::StopBackgroundFetchers() {
1039 std::string oauth1_token; 951 login_manager_.reset();
1040 std::string oauth1_secret;
1041 if (ReadOAuth1AccessToken(user_profile, &oauth1_token, &oauth1_secret))
1042 VerifyOAuth1AccessToken(user_profile, oauth1_token, oauth1_secret);
1043 } 952 }
1044 953
1045 void LoginUtilsImpl::StopBackgroundFetchers() { 954 void LoginUtilsImpl::OnCompletedAuthentication(Profile* user_profile) {
1046 policy_oauth_fetcher_.reset(); 955 StartSignedInServices(user_profile);
1047 oauth1_token_fetcher_.reset();
1048 oauth_login_verifier_.reset();
1049 } 956 }
1050 957
1051 void LoginUtilsImpl::FetchSecondaryTokens(Profile* offrecord_profile, 958 void LoginUtilsImpl::OnFoundStoredTokens() {
1052 const std::string& token, 959 // We don't need authenticator instance any more since its cookie jar
1053 const std::string& secret) { 960 // is not going to needed to mint OAuth tokens. Reset it so that
1054 FetchPolicyToken(offrecord_profile, token, secret);
1055 // TODO(rickcam, zelidrag): Wire TokenService there when it becomes
1056 // capable of handling OAuth1 tokens directly.
1057 }
1058
1059 bool LoginUtilsImpl::ReadOAuth1AccessToken(Profile* user_profile,
1060 std::string* token,
1061 std::string* secret) {
1062 // Skip reading oauth token if user does not have a valid status.
1063 if (UserManager::Get()->IsUserLoggedIn() &&
1064 UserManager::Get()->GetLoggedInUser()->oauth_token_status() !=
1065 User::OAUTH_TOKEN_STATUS_VALID) {
1066 return false;
1067 }
1068
1069 PrefService* pref_service = user_profile->GetPrefs();
1070 std::string encoded_token = pref_service->GetString(prefs::kOAuth1Token);
1071 std::string encoded_secret = pref_service->GetString(prefs::kOAuth1Secret);
1072 if (!encoded_token.length() || !encoded_secret.length())
1073 return false;
1074
1075 std::string decoded_token =
1076 CrosLibrary::Get()->GetCertLibrary()->DecryptToken(encoded_token);
1077 std::string decoded_secret =
1078 CrosLibrary::Get()->GetCertLibrary()->DecryptToken(encoded_secret);
1079 if (!decoded_token.length() || !decoded_secret.length())
1080 return false;
1081
1082 *token = decoded_token;
1083 *secret = decoded_secret;
1084 return true;
1085 }
1086
1087 void LoginUtilsImpl::StoreOAuth1AccessToken(Profile* user_profile,
1088 const std::string& token,
1089 const std::string& secret) {
1090 // First store OAuth1 token + service for the current user profile...
1091 std::string encrypted_token =
1092 CrosLibrary::Get()->GetCertLibrary()->EncryptToken(token);
1093 std::string encrypted_secret =
1094 CrosLibrary::Get()->GetCertLibrary()->EncryptToken(secret);
1095 PrefService* pref_service = user_profile->GetPrefs();
1096 User* user = UserManager::Get()->GetLoggedInUser();
1097 if (!encrypted_token.empty() && !encrypted_secret.empty()) {
1098 pref_service->SetString(prefs::kOAuth1Token, encrypted_token);
1099 pref_service->SetString(prefs::kOAuth1Secret, encrypted_secret);
1100
1101 // ...then record the presence of valid OAuth token for this account in
1102 // local state as well.
1103 UserManager::Get()->SaveUserOAuthStatus(
1104 user->email(), User::OAUTH_TOKEN_STATUS_VALID);
1105 } else {
1106 LOG(WARNING) << "Failed to get OAuth1 token/secret encrypted.";
1107 // Set the OAuth status invalid so that the user will go through full
1108 // GAIA login next time.
1109 UserManager::Get()->SaveUserOAuthStatus(
1110 user->email(), User::OAUTH_TOKEN_STATUS_INVALID);
1111 }
1112 }
1113
1114 void LoginUtilsImpl::VerifyOAuth1AccessToken(Profile* user_profile,
1115 const std::string& token,
1116 const std::string& secret) {
1117 // Kick off verification of OAuth1 access token (via OAuthLogin), this should
1118 // let us fetch credentials that will be used to initialize sync engine.
1119 FetchCredentials(user_profile, token, secret);
1120
1121 FetchSecondaryTokens(user_profile->GetOffTheRecordProfile(), token, secret);
1122 }
1123
1124 void LoginUtilsImpl::FetchCredentials(Profile* user_profile,
1125 const std::string& token,
1126 const std::string& secret) {
1127 oauth_login_verifier_.reset(new OAuthLoginVerifier(
1128 this, user_profile, token, secret,
1129 UserManager::Get()->GetLoggedInUser()->email()));
1130 oauth_login_verifier_->StartOAuthVerification();
1131 }
1132
1133
1134 void LoginUtilsImpl::FetchPolicyToken(Profile* offrecord_profile,
1135 const std::string& token,
1136 const std::string& secret) {
1137 // Fetch dm service token now, if it hasn't been fetched yet.
1138 if (!policy_oauth_fetcher_.get() || policy_oauth_fetcher_->failed()) {
1139 // Get the default system profile to use with the policy fetching. If there
1140 // is no |authenticator_| profile, manually load default system profile.
1141 // Otherwise, just use |authenticator_|'s profile.
1142 Profile* profile = NULL;
1143 if (authenticator_)
1144 profile = authenticator_->authentication_profile();
1145
1146 if (!profile) {
1147 FilePath user_data_dir;
1148 PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
1149 ProfileManager* profile_manager = g_browser_process->profile_manager();
1150 // Temporarily allow until fix: http://crosbug.com/30391.
1151 base::ThreadRestrictions::ScopedAllowIO allow_io;
1152 profile = profile_manager->GetProfile(user_data_dir)->
1153 GetOffTheRecordProfile();
1154 }
1155
1156 // Trigger oauth token fetch for user policy.
1157 policy_oauth_fetcher_.reset(new PolicyOAuthFetcher(profile, token, secret));
1158 policy_oauth_fetcher_->Start();
1159 }
1160
1161 // TODO(zelidrag): We should add initialization of other services somewhere
1162 // here as well. This could be handled with TokenService class once it is
1163 // ready to handle OAuth tokens.
1164
1165 // We don't need authenticator instance any more, reset it so that
1166 // ScreenLocker would create a separate instance. 961 // ScreenLocker would create a separate instance.
1167 // TODO(nkostylev): There's a potential race if SL would be created before
1168 // OAuth tokens are fetched. It would use incorrect Authenticator instance.
1169 authenticator_ = NULL; 962 authenticator_ = NULL;
1170 } 963 }
1171 964
1172 void LoginUtilsImpl::OnOAuthVerificationFailed(const std::string& user_name) {
1173 UserManager::Get()->SaveUserOAuthStatus(user_name,
1174 User::OAUTH_TOKEN_STATUS_INVALID);
1175 }
1176
1177 void LoginUtilsImpl::OnOAuth1AccessTokenAvailable(const std::string& token,
1178 const std::string& secret) {
1179 Profile* user_profile = ProfileManager::GetDefaultProfile();
1180 StoreOAuth1AccessToken(user_profile, token, secret);
1181
1182 // Verify OAuth1 token by doing OAuthLogin and fetching credentials. If we
1183 // have just transfered auth cookies out of authenticated cookie jar, there
1184 // is no need to try to mint them from OAuth token again.
1185 VerifyOAuth1AccessToken(user_profile, token, secret);
1186 }
1187
1188 void LoginUtilsImpl::OnOAuth1AccessTokenFetchFailed() {
1189 // TODO(kochi): Show failure notification UI here?
1190 LOG(ERROR) << "Failed to fetch OAuth1 access token.";
1191 g_browser_process->browser_policy_connector()->RegisterForUserPolicy(
1192 EmptyString());
1193 }
1194
1195 void LoginUtilsImpl::OnOAuthVerificationSucceeded(
1196 const std::string& user_name, const std::string& sid,
1197 const std::string& lsid, const std::string& auth) {
1198 // Kick off sync engine.
1199 GaiaAuthConsumer::ClientLoginResult credentials(sid, lsid, auth,
1200 std::string());
1201 StartSignedInServices(ProfileManager::GetDefaultProfile(), credentials);
1202 }
1203
1204
1205 void LoginUtilsImpl::OnConnectionTypeChanged( 965 void LoginUtilsImpl::OnConnectionTypeChanged(
1206 net::NetworkChangeNotifier::ConnectionType type) { 966 net::NetworkChangeNotifier::ConnectionType type) {
967 if (!login_manager_.get())
968 return;
969
1207 if (type != net::NetworkChangeNotifier::CONNECTION_NONE && 970 if (type != net::NetworkChangeNotifier::CONNECTION_NONE &&
1208 UserManager::Get()->IsUserLoggedIn()) { 971 UserManager::Get()->IsUserLoggedIn()) {
1209 if (oauth_login_verifier_.get() && 972 if (login_manager_->state() ==
1210 !oauth_login_verifier_->is_done()) { 973 OAuthLoginManager::SESSION_RESTORE_IN_PROGRESS) {
1211 // If we come online for the first time after successful offline login, 974 // If we come online for the first time after successful offline login,
1212 // we need to kick off OAuth token verification process again. 975 // we need to kick off OAuth token verification process again.
1213 oauth_login_verifier_->ContinueVerification(); 976 login_manager_->ContinueSessionRestore();
1214 } else if (should_restore_auth_session_) { 977 } else if (should_restore_auth_session_) {
1215 should_restore_auth_session_ = false; 978 should_restore_auth_session_ = false;
1216 Profile* user_profile = ProfileManager::GetDefaultProfile(); 979 Profile* user_profile = ProfileManager::GetDefaultProfile();
1217 KickStartAuthentication(user_profile); 980 RestoreAuthSession(user_profile, has_web_auth_cookies_);
1218 } 981 }
1219 } 982 }
1220 } 983 }
1221 984
1222 void LoginUtilsImpl::Observe(int type, 985 void LoginUtilsImpl::Observe(int type,
1223 const content::NotificationSource& source, 986 const content::NotificationSource& source,
1224 const content::NotificationDetails& details) { 987 const content::NotificationDetails& details) {
1225 switch (type) { 988 switch (type) {
1226 case chrome::NOTIFICATION_PROFILE_URL_REQUEST_CONTEXT_GETTER_INITIALIZED: { 989 case chrome::NOTIFICATION_PROFILE_URL_REQUEST_CONTEXT_GETTER_INITIALIZED: {
1227 Profile* profile = content::Source<Profile>(source).ptr(); 990 Profile* profile = content::Source<Profile>(source).ptr();
(...skipping 23 matching lines...) Expand all
1251 bool LoginUtils::IsWhitelisted(const std::string& username) { 1014 bool LoginUtils::IsWhitelisted(const std::string& username) {
1252 CrosSettings* cros_settings = CrosSettings::Get(); 1015 CrosSettings* cros_settings = CrosSettings::Get();
1253 bool allow_new_user = false; 1016 bool allow_new_user = false;
1254 cros_settings->GetBoolean(kAccountsPrefAllowNewUser, &allow_new_user); 1017 cros_settings->GetBoolean(kAccountsPrefAllowNewUser, &allow_new_user);
1255 if (allow_new_user) 1018 if (allow_new_user)
1256 return true; 1019 return true;
1257 return cros_settings->FindEmailInList(kAccountsPrefUsers, username); 1020 return cros_settings->FindEmailInList(kAccountsPrefUsers, username);
1258 } 1021 }
1259 1022
1260 } // namespace chromeos 1023 } // namespace chromeos
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698