Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / chromeos / login / oauth2_login_verifier.cc
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "chrome/browser/chromeos/login/oauth2_login_verifier.h"
6
7 #include <vector>
8
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"
26
27 using content::BrowserThread;
28
29 namespace {
30
31 // OAuth token request max retry count.
32 const int kMaxRequestAttemptCount = 5;
33
34 // OAuth token request retry delay in milliseconds.
35 const int kRequestRestartDelay = 3000;
36
37 // Post merge session verification delay.
38 #ifndef NDEBUG
39 const int kPostResoreVerificationDelay = 1000;
40 #else
41 const int kPostResoreVerificationDelay = 1000*60*3;
42 #endif
43
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;
48 }
49
50 }  // namespace
51
52 namespace chromeos {
53
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"),
60       delegate_(delegate),
61       system_request_context_(system_request_context),
62       user_request_context_(user_request_context),
63       access_token_(oauthlogin_access_token),
64       retry_count_(0) {
65   DCHECK(delegate);
66 }
67
68 OAuth2LoginVerifier::~OAuth2LoginVerifier() {
69 }
70
71 void OAuth2LoginVerifier::VerifyProfileTokens(Profile* profile) {
72   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
73
74   // Delay the verification if the network is not connected or on a captive
75   // portal.
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(
86         BrowserThread::UI,
87         FROM_HERE,
88         base::Bind(
89             &OAuth2LoginVerifier::VerifyProfileTokens, AsWeakPtr(), profile),
90         base::TimeDelta::FromMilliseconds(kRequestRestartDelay));
91     return;
92   }
93
94   gaia_token_.clear();
95   if (access_token_.empty()) {
96     // Fetch /OAuthLogin scoped access token.
97     StartFetchingOAuthLoginAccessToken(profile);
98   } else {
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();
102   }
103 }
104
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(),
115       scopes,
116       this);
117 }
118
119 void OAuth2LoginVerifier::StartOAuthLoginForUberToken() {
120   // No service will fetch us uber auth token.
121   gaia_fetcher_.reset(
122       new GaiaAuthFetcher(this,
123                           std::string(GaiaConstants::kChromeOSSource),
124                           user_request_context_.get()));
125   gaia_fetcher_->StartTokenFetchForUberAuthExchange(access_token_);
126 }
127
128
129 void OAuth2LoginVerifier::OnUberAuthTokenSuccess(
130     const std::string& uber_token) {
131   VLOG(1) << "OAuthLogin(uber_token) successful!";
132   retry_count_ = 0;
133   gaia_token_ = uber_token;
134   StartMergeSession();
135 }
136
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,
144                           AsWeakPtr()),
145                base::Bind(&Delegate::OnSessionMergeFailure,
146                           base::Unretained(delegate_)));
147 }
148
149 void OAuth2LoginVerifier::StartMergeSession() {
150   DCHECK(!gaia_token_.empty());
151   gaia_fetcher_.reset(
152       new GaiaAuthFetcher(this,
153                           std::string(GaiaConstants::kChromeOSSource),
154                           user_request_context_.get()));
155   gaia_fetcher_->StartMergeSession(gaia_token_);
156 }
157
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();
165 }
166
167 void OAuth2LoginVerifier::SchedulePostMergeVerification() {
168   BrowserThread::PostDelayedTask(
169       BrowserThread::UI,
170       FROM_HERE,
171       base::Bind(
172           &OAuth2LoginVerifier::StartPostRestoreVerification, AsWeakPtr()),
173       base::TimeDelta::FromMilliseconds(kPostResoreVerificationDelay));
174 }
175
176 void OAuth2LoginVerifier::StartPostRestoreVerification() {
177   gaia_fetcher_.reset(
178       new GaiaAuthFetcher(this,
179                           std::string(GaiaConstants::kChromeOSSource),
180                           user_request_context_.get()));
181   gaia_fetcher_->StartListAccounts();
182 }
183
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.
189   RetryOnError(
190       "MergeSession",
191       error,
192       base::Bind(&OAuth2LoginVerifier::StartMergeSession,
193                  AsWeakPtr()),
194       base::Bind(&Delegate::OnSessionMergeFailure,
195                  base::Unretained(delegate_)));
196 }
197
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();
204
205   VLOG(1) << "Got OAuth2 access token!";
206   retry_count_ = 0;
207   access_token_ = access_token;
208   StartOAuthLoginForUberToken();
209 }
210
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();
217
218   LOG(WARNING) << "Failed to get OAuth2 access token, "
219                << " error: " << error.state();
220   UMA_HISTOGRAM_ENUMERATION(
221       base::StringPrintf("OAuth2Login.%sFailure", "GetOAuth2AccessToken"),
222       error.state(),
223       GoogleServiceAuthError::NUM_STATES);
224   delegate_->OnSessionMergeFailure(IsConnectionOrServiceError(error));
225 }
226
227 void OAuth2LoginVerifier::OnListAccountsSuccess(
228     const std::string& data) {
229   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
230   VLOG(1) << "ListAccounts successful.";
231   delegate_->OnListAccountsSuccess(data);
232 }
233
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();
239   RetryOnError(
240       "ListAccounts",
241       error,
242       base::Bind(&OAuth2LoginVerifier::StartPostRestoreVerification,
243                  AsWeakPtr()),
244       base::Bind(&Delegate::OnListAccountsFailure,
245                  base::Unretained(delegate_)));
246 }
247
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) {
254     retry_count_++;
255     UMA_HISTOGRAM_ENUMERATION(
256         base::StringPrintf("OAuth2Login.%sRetry", operation_id),
257         error.state(),
258         GoogleServiceAuthError::NUM_STATES);
259     BrowserThread::PostDelayedTask(
260         BrowserThread::UI, FROM_HERE, task_to_retry,
261         base::TimeDelta::FromMilliseconds(kRequestRestartDelay));
262     return;
263   }
264
265   LOG(WARNING) << "Unrecoverable error or retry count max reached for "
266                << operation_id;
267   UMA_HISTOGRAM_ENUMERATION(
268       base::StringPrintf("OAuth2Login.%sFailure", operation_id),
269       error.state(),
270       GoogleServiceAuthError::NUM_STATES);
271
272   error_handler.Run(IsConnectionOrServiceError(error));
273 }
274
275 }  // namespace chromeos