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.
5 #include "chrome/browser/chromeos/login/oauth2_login_verifier.h"
9 #include "base/logging.h"
10 #include "base/metrics/histogram.h"
11 #include "base/strings/string_util.h"
12 #include "base/strings/stringprintf.h"
13 #include "base/time/time.h"
14 #include "chrome/browser/chromeos/net/network_portal_detector.h"
15 #include "chrome/browser/signin/profile_oauth2_token_service.h"
16 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
17 #include "chrome/browser/signin/signin_manager.h"
18 #include "chrome/browser/signin/signin_manager_factory.h"
19 #include "chromeos/network/network_handler.h"
20 #include "chromeos/network/network_state.h"
21 #include "chromeos/network/network_state_handler.h"
22 #include "content/public/browser/browser_thread.h"
23 #include "google_apis/gaia/gaia_constants.h"
24 #include "google_apis/gaia/gaia_urls.h"
25 #include "third_party/cros_system_api/dbus/service_constants.h"
27 using content::BrowserThread;
31 // OAuth token request max retry count.
32 const int kMaxRequestAttemptCount = 5;
34 // OAuth token request retry delay in milliseconds.
35 const int kRequestRestartDelay = 3000;
37 // Post merge session verification delay.
39 const int kPostResoreVerificationDelay = 1000;
41 const int kPostResoreVerificationDelay = 1000*60*3;
44 bool IsConnectionOrServiceError(const GoogleServiceAuthError& error) {
45 return error.state() == GoogleServiceAuthError::CONNECTION_FAILED ||
46 error.state() == GoogleServiceAuthError::SERVICE_UNAVAILABLE ||
47 error.state() == GoogleServiceAuthError::REQUEST_CANCELED;
54 OAuth2LoginVerifier::OAuth2LoginVerifier(
55 OAuth2LoginVerifier::Delegate* delegate,
56 net::URLRequestContextGetter* system_request_context,
57 net::URLRequestContextGetter* user_request_context,
58 const std::string& oauthlogin_access_token)
59 : OAuth2TokenService::Consumer("cros_login_verifier"),
61 system_request_context_(system_request_context),
62 user_request_context_(user_request_context),
63 access_token_(oauthlogin_access_token),
68 OAuth2LoginVerifier::~OAuth2LoginVerifier() {
71 void OAuth2LoginVerifier::VerifyProfileTokens(Profile* profile) {
72 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
74 // Delay the verification if the network is not connected or on a captive
76 const NetworkState* default_network =
77 NetworkHandler::Get()->network_state_handler()->DefaultNetwork();
78 NetworkPortalDetector* detector = NetworkPortalDetector::Get();
79 if (!default_network ||
80 default_network->connection_state() == shill::kStatePortal ||
81 (detector && detector->GetCaptivePortalState(default_network).status !=
82 NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_ONLINE)) {
83 // If network is offline, defer the token fetching until online.
84 LOG(WARNING) << "Network is offline. Deferring OAuth2 access token fetch.";
85 BrowserThread::PostDelayedTask(
89 &OAuth2LoginVerifier::VerifyProfileTokens, AsWeakPtr(), profile),
90 base::TimeDelta::FromMilliseconds(kRequestRestartDelay));
95 if (access_token_.empty()) {
96 // Fetch /OAuthLogin scoped access token.
97 StartFetchingOAuthLoginAccessToken(profile);
99 // If OAuthLogin-scoped access token already exists (if it's generated
100 // together with freshly minted refresh token), then fetch GAIA uber token.
101 StartOAuthLoginForUberToken();
105 void OAuth2LoginVerifier::StartFetchingOAuthLoginAccessToken(Profile* profile) {
106 OAuth2TokenService::ScopeSet scopes;
107 scopes.insert(GaiaUrls::GetInstance()->oauth1_login_scope());
108 ProfileOAuth2TokenService* token_service =
109 ProfileOAuth2TokenServiceFactory::GetForProfile(profile);
110 SigninManagerBase* signin_manager =
111 SigninManagerFactory::GetForProfile(profile);
112 login_token_request_ = token_service->StartRequestWithContext(
113 signin_manager->GetAuthenticatedAccountId(),
114 system_request_context_.get(),
119 void OAuth2LoginVerifier::StartOAuthLoginForUberToken() {
120 // No service will fetch us uber auth token.
122 new GaiaAuthFetcher(this,
123 std::string(GaiaConstants::kChromeOSSource),
124 user_request_context_.get()));
125 gaia_fetcher_->StartTokenFetchForUberAuthExchange(access_token_);
129 void OAuth2LoginVerifier::OnUberAuthTokenSuccess(
130 const std::string& uber_token) {
131 VLOG(1) << "OAuthLogin(uber_token) successful!";
133 gaia_token_ = uber_token;
137 void OAuth2LoginVerifier::OnUberAuthTokenFailure(
138 const GoogleServiceAuthError& error) {
139 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
140 LOG(WARNING) << "OAuthLogin(uber_token) failed,"
141 << " error: " << error.state();
142 RetryOnError("OAuthLoginUberToken", error,
143 base::Bind(&OAuth2LoginVerifier::StartOAuthLoginForUberToken,
145 base::Bind(&Delegate::OnSessionMergeFailure,
146 base::Unretained(delegate_)));
149 void OAuth2LoginVerifier::StartMergeSession() {
150 DCHECK(!gaia_token_.empty());
152 new GaiaAuthFetcher(this,
153 std::string(GaiaConstants::kChromeOSSource),
154 user_request_context_.get()));
155 gaia_fetcher_->StartMergeSession(gaia_token_);
158 void OAuth2LoginVerifier::OnMergeSessionSuccess(const std::string& data) {
159 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
160 VLOG(1) << "MergeSession successful.";
161 delegate_->OnSessionMergeSuccess();
162 // Schedule post-merge verification to analyze how many LSID/SID overruns
163 // were created by the session restore.
164 SchedulePostMergeVerification();
167 void OAuth2LoginVerifier::SchedulePostMergeVerification() {
168 BrowserThread::PostDelayedTask(
172 &OAuth2LoginVerifier::StartPostRestoreVerification, AsWeakPtr()),
173 base::TimeDelta::FromMilliseconds(kPostResoreVerificationDelay));
176 void OAuth2LoginVerifier::StartPostRestoreVerification() {
178 new GaiaAuthFetcher(this,
179 std::string(GaiaConstants::kChromeOSSource),
180 user_request_context_.get()));
181 gaia_fetcher_->StartListAccounts();
184 void OAuth2LoginVerifier::OnMergeSessionFailure(
185 const GoogleServiceAuthError& error) {
186 LOG(WARNING) << "Failed MergeSession request," << " error: " << error.state();
187 // If MergeSession from GAIA service token fails, retry the session restore
188 // from OAuth2 refresh token. If that failed too, signal the delegate.
192 base::Bind(&OAuth2LoginVerifier::StartMergeSession,
194 base::Bind(&Delegate::OnSessionMergeFailure,
195 base::Unretained(delegate_)));
198 void OAuth2LoginVerifier::OnGetTokenSuccess(
199 const OAuth2TokenService::Request* request,
200 const std::string& access_token,
201 const base::Time& expiration_time) {
202 DCHECK_EQ(login_token_request_.get(), request);
203 login_token_request_.reset();
205 VLOG(1) << "Got OAuth2 access token!";
207 access_token_ = access_token;
208 StartOAuthLoginForUberToken();
211 void OAuth2LoginVerifier::OnGetTokenFailure(
212 const OAuth2TokenService::Request* request,
213 const GoogleServiceAuthError& error) {
214 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
215 DCHECK_EQ(login_token_request_.get(), request);
216 login_token_request_.reset();
218 LOG(WARNING) << "Failed to get OAuth2 access token, "
219 << " error: " << error.state();
220 UMA_HISTOGRAM_ENUMERATION(
221 base::StringPrintf("OAuth2Login.%sFailure", "GetOAuth2AccessToken"),
223 GoogleServiceAuthError::NUM_STATES);
224 delegate_->OnSessionMergeFailure(IsConnectionOrServiceError(error));
227 void OAuth2LoginVerifier::OnListAccountsSuccess(
228 const std::string& data) {
229 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
230 VLOG(1) << "ListAccounts successful.";
231 delegate_->OnListAccountsSuccess(data);
234 void OAuth2LoginVerifier::OnListAccountsFailure(
235 const GoogleServiceAuthError& error) {
236 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
237 LOG(WARNING) << "Failed to get list of session accounts, "
238 << " error: " << error.state();
242 base::Bind(&OAuth2LoginVerifier::StartPostRestoreVerification,
244 base::Bind(&Delegate::OnListAccountsFailure,
245 base::Unretained(delegate_)));
248 void OAuth2LoginVerifier::RetryOnError(const char* operation_id,
249 const GoogleServiceAuthError& error,
250 const base::Closure& task_to_retry,
251 const ErrorHandler& error_handler) {
252 if (IsConnectionOrServiceError(error) &&
253 retry_count_ < kMaxRequestAttemptCount) {
255 UMA_HISTOGRAM_ENUMERATION(
256 base::StringPrintf("OAuth2Login.%sRetry", operation_id),
258 GoogleServiceAuthError::NUM_STATES);
259 BrowserThread::PostDelayedTask(
260 BrowserThread::UI, FROM_HERE, task_to_retry,
261 base::TimeDelta::FromMilliseconds(kRequestRestartDelay));
265 LOG(WARNING) << "Unrecoverable error or retry count max reached for "
267 UMA_HISTOGRAM_ENUMERATION(
268 base::StringPrintf("OAuth2Login.%sFailure", operation_id),
270 GoogleServiceAuthError::NUM_STATES);
272 error_handler.Run(IsConnectionOrServiceError(error));
275 } // namespace chromeos