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
3 // found in the LICENSE file.
5 #include "google_apis/gaia/gaia_auth_fetcher.h"
11 #include "base/json/json_reader.h"
12 #include "base/json/json_writer.h"
13 #include "base/strings/string_split.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/values.h"
17 #include "google_apis/gaia/gaia_auth_consumer.h"
18 #include "google_apis/gaia/gaia_constants.h"
19 #include "google_apis/gaia/gaia_urls.h"
20 #include "google_apis/gaia/google_service_auth_error.h"
21 #include "net/base/escape.h"
22 #include "net/base/load_flags.h"
23 #include "net/http/http_response_headers.h"
24 #include "net/http/http_status_code.h"
25 #include "net/url_request/url_fetcher.h"
26 #include "net/url_request/url_request_context_getter.h"
27 #include "net/url_request/url_request_status.h"
30 const int kLoadFlagsIgnoreCookies
= net::LOAD_DO_NOT_SEND_COOKIES
|
31 net::LOAD_DO_NOT_SAVE_COOKIES
;
33 static bool CookiePartsContains(const std::vector
<std::string
>& parts
,
35 for (std::vector
<std::string
>::const_iterator it
= parts
.begin();
36 it
!= parts
.end(); ++it
) {
37 if (LowerCaseEqualsASCII(*it
, part
))
43 bool ExtractOAuth2TokenPairResponse(base::DictionaryValue
* dict
,
44 std::string
* refresh_token
,
45 std::string
* access_token
,
46 int* expires_in_secs
) {
47 DCHECK(refresh_token
);
49 DCHECK(expires_in_secs
);
51 if (!dict
->GetStringWithoutPathExpansion("refresh_token", refresh_token
) ||
52 !dict
->GetStringWithoutPathExpansion("access_token", access_token
) ||
53 !dict
->GetIntegerWithoutPathExpansion("expires_in", expires_in_secs
)) {
62 // TODO(chron): Add sourceless version of this formatter.
64 const char GaiaAuthFetcher::kClientLoginFormat
[] =
67 "PersistentCookie=%s&"
72 const char GaiaAuthFetcher::kClientLoginCaptchaFormat
[] =
75 "PersistentCookie=%s&"
82 const char GaiaAuthFetcher::kIssueAuthTokenFormat
[] =
88 const char GaiaAuthFetcher::kClientLoginToOAuth2BodyFormat
[] =
89 "scope=%s&client_id=%s";
91 const char GaiaAuthFetcher::kClientLoginToOAuth2WithDeviceTypeBodyFormat
[] =
92 "scope=%s&client_id=%s&device_type=chrome";
94 const char GaiaAuthFetcher::kOAuth2CodeToTokenPairBodyFormat
[] =
96 "grant_type=authorization_code&"
101 const char GaiaAuthFetcher::kOAuth2RevokeTokenBodyFormat
[] =
104 const char GaiaAuthFetcher::kGetUserInfoFormat
[] =
107 const char GaiaAuthFetcher::kMergeSessionFormat
[] =
112 const char GaiaAuthFetcher::kUberAuthTokenURLFormat
[] =
116 const char GaiaAuthFetcher::kOAuthLoginFormat
[] = "service=%s&source=%s";
119 const char GaiaAuthFetcher::kAccountDeletedError
[] = "AccountDeleted";
121 const char GaiaAuthFetcher::kAccountDisabledError
[] = "AccountDisabled";
123 const char GaiaAuthFetcher::kBadAuthenticationError
[] = "BadAuthentication";
125 const char GaiaAuthFetcher::kCaptchaError
[] = "CaptchaRequired";
127 const char GaiaAuthFetcher::kServiceUnavailableError
[] =
128 "ServiceUnavailable";
130 const char GaiaAuthFetcher::kErrorParam
[] = "Error";
132 const char GaiaAuthFetcher::kErrorUrlParam
[] = "Url";
134 const char GaiaAuthFetcher::kCaptchaUrlParam
[] = "CaptchaUrl";
136 const char GaiaAuthFetcher::kCaptchaTokenParam
[] = "CaptchaToken";
139 const char GaiaAuthFetcher::kCookiePersistence
[] = "true";
141 // TODO(johnnyg): When hosted accounts are supported by sync,
142 // we can always use "HOSTED_OR_GOOGLE"
143 const char GaiaAuthFetcher::kAccountTypeHostedOrGoogle
[] =
145 const char GaiaAuthFetcher::kAccountTypeGoogle
[] =
149 const char GaiaAuthFetcher::kSecondFactor
[] = "Info=InvalidSecondFactor";
152 const char GaiaAuthFetcher::kAuthHeaderFormat
[] =
153 "Authorization: GoogleLogin auth=%s";
155 const char GaiaAuthFetcher::kOAuthHeaderFormat
[] = "Authorization: OAuth %s";
157 const char GaiaAuthFetcher::kOAuth2BearerHeaderFormat
[] =
158 "Authorization: Bearer %s";
160 const char GaiaAuthFetcher::kDeviceIdHeaderFormat
[] = "X-Device-ID: %s";
162 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartSecure
[] = "secure";
164 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartHttpOnly
[] =
167 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefix
[] =
170 const int GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefixLength
=
171 arraysize(GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefix
) - 1;
173 GaiaAuthFetcher::GaiaAuthFetcher(GaiaAuthConsumer
* consumer
,
174 const std::string
& source
,
175 net::URLRequestContextGetter
* getter
)
176 : consumer_(consumer
),
179 client_login_gurl_(GaiaUrls::GetInstance()->client_login_url()),
180 issue_auth_token_gurl_(GaiaUrls::GetInstance()->issue_auth_token_url()),
181 oauth2_token_gurl_(GaiaUrls::GetInstance()->oauth2_token_url()),
182 oauth2_revoke_gurl_(GaiaUrls::GetInstance()->oauth2_revoke_url()),
183 get_user_info_gurl_(GaiaUrls::GetInstance()->get_user_info_url()),
184 merge_session_gurl_(GaiaUrls::GetInstance()->merge_session_url()),
185 uberauth_token_gurl_(GaiaUrls::GetInstance()->oauth1_login_url().Resolve(
186 base::StringPrintf(kUberAuthTokenURLFormat
, source
.c_str()))),
187 oauth_login_gurl_(GaiaUrls::GetInstance()->oauth1_login_url()),
189 GaiaUrls::GetInstance()->ListAccountsURLWithSource(source
)),
190 get_check_connection_info_url_(
191 GaiaUrls::GetInstance()->GetCheckConnectionInfoURLWithSource(source
)),
192 client_login_to_oauth2_gurl_(
193 GaiaUrls::GetInstance()->client_login_to_oauth2_url()),
194 fetch_pending_(false) {}
196 GaiaAuthFetcher::~GaiaAuthFetcher() {}
198 bool GaiaAuthFetcher::HasPendingFetch() {
199 return fetch_pending_
;
202 void GaiaAuthFetcher::CancelRequest() {
204 fetch_pending_
= false;
208 net::URLFetcher
* GaiaAuthFetcher::CreateGaiaFetcher(
209 net::URLRequestContextGetter
* getter
,
210 const std::string
& body
,
211 const std::string
& headers
,
212 const GURL
& gaia_gurl
,
214 net::URLFetcherDelegate
* delegate
) {
215 net::URLFetcher
* to_return
= net::URLFetcher::Create(
217 body
== "" ? net::URLFetcher::GET
: net::URLFetcher::POST
,
219 to_return
->SetRequestContext(getter
);
220 to_return
->SetUploadData("application/x-www-form-urlencoded", body
);
222 DVLOG(2) << "Gaia fetcher URL: " << gaia_gurl
.spec();
223 DVLOG(2) << "Gaia fetcher headers: " << headers
;
224 DVLOG(2) << "Gaia fetcher body: " << body
;
226 // The Gaia token exchange requests do not require any cookie-based
227 // identification as part of requests. We suppress sending any cookies to
228 // maintain a separation between the user's browsing and Chrome's internal
229 // services. Where such mixing is desired (MergeSession or OAuthLogin), it
230 // will be done explicitly.
231 to_return
->SetLoadFlags(load_flags
);
233 // Fetchers are sometimes cancelled because a network change was detected,
234 // especially at startup and after sign-in on ChromeOS. Retrying once should
235 // be enough in those cases; let the fetcher retry up to 3 times just in case.
236 // http://crbug.com/163710
237 to_return
->SetAutomaticallyRetryOnNetworkChanges(3);
239 if (!headers
.empty())
240 to_return
->SetExtraRequestHeaders(headers
);
246 std::string
GaiaAuthFetcher::MakeClientLoginBody(
247 const std::string
& username
,
248 const std::string
& password
,
249 const std::string
& source
,
251 const std::string
& login_token
,
252 const std::string
& login_captcha
,
253 HostedAccountsSetting allow_hosted_accounts
) {
254 std::string encoded_username
= net::EscapeUrlEncodedData(username
, true);
255 std::string encoded_password
= net::EscapeUrlEncodedData(password
, true);
256 std::string encoded_login_token
= net::EscapeUrlEncodedData(login_token
,
258 std::string encoded_login_captcha
= net::EscapeUrlEncodedData(login_captcha
,
261 const char* account_type
= allow_hosted_accounts
== HostedAccountsAllowed
?
262 kAccountTypeHostedOrGoogle
:
265 if (login_token
.empty() || login_captcha
.empty()) {
266 return base::StringPrintf(kClientLoginFormat
,
267 encoded_username
.c_str(),
268 encoded_password
.c_str(),
275 return base::StringPrintf(kClientLoginCaptchaFormat
,
276 encoded_username
.c_str(),
277 encoded_password
.c_str(),
282 encoded_login_token
.c_str(),
283 encoded_login_captcha
.c_str());
287 std::string
GaiaAuthFetcher::MakeIssueAuthTokenBody(
288 const std::string
& sid
,
289 const std::string
& lsid
,
290 const char* const service
) {
291 std::string encoded_sid
= net::EscapeUrlEncodedData(sid
, true);
292 std::string encoded_lsid
= net::EscapeUrlEncodedData(lsid
, true);
294 // All tokens should be session tokens except the gaia auth token.
296 if (!strcmp(service
, GaiaConstants::kGaiaService
))
299 return base::StringPrintf(kIssueAuthTokenFormat
,
301 encoded_lsid
.c_str(),
303 session
? "true" : "false");
307 std::string
GaiaAuthFetcher::MakeGetAuthCodeBody(bool include_device_type
) {
308 std::string encoded_scope
= net::EscapeUrlEncodedData(
309 GaiaConstants::kOAuth1LoginScope
, true);
310 std::string encoded_client_id
= net::EscapeUrlEncodedData(
311 GaiaUrls::GetInstance()->oauth2_chrome_client_id(), true);
312 if (include_device_type
) {
313 return base::StringPrintf(kClientLoginToOAuth2WithDeviceTypeBodyFormat
,
314 encoded_scope
.c_str(),
315 encoded_client_id
.c_str());
317 return base::StringPrintf(kClientLoginToOAuth2BodyFormat
,
318 encoded_scope
.c_str(),
319 encoded_client_id
.c_str());
324 std::string
GaiaAuthFetcher::MakeGetTokenPairBody(
325 const std::string
& auth_code
) {
326 std::string encoded_scope
= net::EscapeUrlEncodedData(
327 GaiaConstants::kOAuth1LoginScope
, true);
328 std::string encoded_client_id
= net::EscapeUrlEncodedData(
329 GaiaUrls::GetInstance()->oauth2_chrome_client_id(), true);
330 std::string encoded_client_secret
= net::EscapeUrlEncodedData(
331 GaiaUrls::GetInstance()->oauth2_chrome_client_secret(), true);
332 std::string encoded_auth_code
= net::EscapeUrlEncodedData(auth_code
, true);
333 return base::StringPrintf(kOAuth2CodeToTokenPairBodyFormat
,
334 encoded_scope
.c_str(),
335 encoded_client_id
.c_str(),
336 encoded_client_secret
.c_str(),
337 encoded_auth_code
.c_str());
341 std::string
GaiaAuthFetcher::MakeRevokeTokenBody(
342 const std::string
& auth_token
) {
343 return base::StringPrintf(kOAuth2RevokeTokenBodyFormat
, auth_token
.c_str());
347 std::string
GaiaAuthFetcher::MakeGetUserInfoBody(const std::string
& lsid
) {
348 std::string encoded_lsid
= net::EscapeUrlEncodedData(lsid
, true);
349 return base::StringPrintf(kGetUserInfoFormat
, encoded_lsid
.c_str());
353 std::string
GaiaAuthFetcher::MakeMergeSessionBody(
354 const std::string
& auth_token
,
355 const std::string
& external_cc_result
,
356 const std::string
& continue_url
,
357 const std::string
& source
) {
358 std::string encoded_auth_token
= net::EscapeUrlEncodedData(auth_token
, true);
359 std::string encoded_continue_url
= net::EscapeUrlEncodedData(continue_url
,
361 std::string encoded_source
= net::EscapeUrlEncodedData(source
, true);
362 std::string result
= base::StringPrintf(kMergeSessionFormat
,
363 encoded_auth_token
.c_str(),
364 encoded_continue_url
.c_str(),
365 encoded_source
.c_str());
366 if (!external_cc_result
.empty()) {
367 base::StringAppendF(&result
, "&externalCcResult=%s",
368 net::EscapeUrlEncodedData(
369 external_cc_result
, true).c_str());
376 std::string
GaiaAuthFetcher::MakeGetAuthCodeHeader(
377 const std::string
& auth_token
) {
378 return base::StringPrintf(kAuthHeaderFormat
, auth_token
.c_str());
381 // Helper method that extracts tokens from a successful reply.
383 void GaiaAuthFetcher::ParseClientLoginResponse(const std::string
& data
,
386 std::string
* token
) {
393 vector
<pair
<string
, string
> > tokens
;
394 base::SplitStringIntoKeyValuePairs(data
, '=', '\n', &tokens
);
395 for (vector
<pair
<string
, string
> >::iterator i
= tokens
.begin();
396 i
!= tokens
.end(); ++i
) {
397 if (i
->first
== "SID") {
398 sid
->assign(i
->second
);
399 } else if (i
->first
== "LSID") {
400 lsid
->assign(i
->second
);
401 } else if (i
->first
== "Auth") {
402 token
->assign(i
->second
);
405 // If this was a request for uberauth token, then that's all we've got in
407 if (sid
->empty() && lsid
->empty() && token
->empty())
412 std::string
GaiaAuthFetcher::MakeOAuthLoginBody(const std::string
& service
,
413 const std::string
& source
) {
414 std::string encoded_service
= net::EscapeUrlEncodedData(service
, true);
415 std::string encoded_source
= net::EscapeUrlEncodedData(source
, true);
416 return base::StringPrintf(kOAuthLoginFormat
,
417 encoded_service
.c_str(),
418 encoded_source
.c_str());
422 void GaiaAuthFetcher::ParseClientLoginFailure(const std::string
& data
,
424 std::string
* error_url
,
425 std::string
* captcha_url
,
426 std::string
* captcha_token
) {
431 vector
<pair
<string
, string
> > tokens
;
432 base::SplitStringIntoKeyValuePairs(data
, '=', '\n', &tokens
);
433 for (vector
<pair
<string
, string
> >::iterator i
= tokens
.begin();
434 i
!= tokens
.end(); ++i
) {
435 if (i
->first
== kErrorParam
) {
436 error
->assign(i
->second
);
437 } else if (i
->first
== kErrorUrlParam
) {
438 error_url
->assign(i
->second
);
439 } else if (i
->first
== kCaptchaUrlParam
) {
440 captcha_url
->assign(i
->second
);
441 } else if (i
->first
== kCaptchaTokenParam
) {
442 captcha_token
->assign(i
->second
);
448 bool GaiaAuthFetcher::ParseClientLoginToOAuth2Response(
449 const net::ResponseCookies
& cookies
,
450 std::string
* auth_code
) {
452 net::ResponseCookies::const_iterator iter
;
453 for (iter
= cookies
.begin(); iter
!= cookies
.end(); ++iter
) {
454 if (ParseClientLoginToOAuth2Cookie(*iter
, auth_code
))
461 bool GaiaAuthFetcher::ParseClientLoginToOAuth2Cookie(const std::string
& cookie
,
462 std::string
* auth_code
) {
463 std::vector
<std::string
> parts
;
464 base::SplitString(cookie
, ';', &parts
);
465 // Per documentation, the cookie should have Secure and HttpOnly.
466 if (!CookiePartsContains(parts
, kClientLoginToOAuth2CookiePartSecure
) ||
467 !CookiePartsContains(parts
, kClientLoginToOAuth2CookiePartHttpOnly
)) {
471 std::vector
<std::string
>::const_iterator iter
;
472 for (iter
= parts
.begin(); iter
!= parts
.end(); ++iter
) {
473 const std::string
& part
= *iter
;
475 part
, kClientLoginToOAuth2CookiePartCodePrefix
, false)) {
476 auth_code
->assign(part
.substr(
477 kClientLoginToOAuth2CookiePartCodePrefixLength
));
484 void GaiaAuthFetcher::StartClientLogin(
485 const std::string
& username
,
486 const std::string
& password
,
487 const char* const service
,
488 const std::string
& login_token
,
489 const std::string
& login_captcha
,
490 HostedAccountsSetting allow_hosted_accounts
) {
492 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
494 // This class is thread agnostic, so be sure to call this only on the
495 // same thread each time.
496 DVLOG(1) << "Starting new ClientLogin fetch for:" << username
;
498 // Must outlive fetcher_.
499 request_body_
= MakeClientLoginBody(username
,
505 allow_hosted_accounts
);
506 fetcher_
.reset(CreateGaiaFetcher(getter_
,
510 kLoadFlagsIgnoreCookies
,
512 fetch_pending_
= true;
516 void GaiaAuthFetcher::StartIssueAuthToken(const std::string
& sid
,
517 const std::string
& lsid
,
518 const char* const service
) {
519 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
521 DVLOG(1) << "Starting IssueAuthToken for: " << service
;
522 requested_service_
= service
;
523 request_body_
= MakeIssueAuthTokenBody(sid
, lsid
, service
);
524 fetcher_
.reset(CreateGaiaFetcher(getter_
,
527 issue_auth_token_gurl_
,
528 kLoadFlagsIgnoreCookies
,
530 fetch_pending_
= true;
534 void GaiaAuthFetcher::StartLsoForOAuthLoginTokenExchange(
535 const std::string
& auth_token
) {
536 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
538 DVLOG(1) << "Starting OAuth login token exchange with auth_token";
539 request_body_
= MakeGetAuthCodeBody(false);
540 client_login_to_oauth2_gurl_
=
541 GaiaUrls::GetInstance()->client_login_to_oauth2_url();
543 fetcher_
.reset(CreateGaiaFetcher(getter_
,
545 MakeGetAuthCodeHeader(auth_token
),
546 client_login_to_oauth2_gurl_
,
547 kLoadFlagsIgnoreCookies
,
549 fetch_pending_
= true;
553 void GaiaAuthFetcher::StartRevokeOAuth2Token(const std::string
& auth_token
) {
554 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
556 DVLOG(1) << "Starting OAuth2 token revocation";
557 request_body_
= MakeRevokeTokenBody(auth_token
);
558 fetcher_
.reset(CreateGaiaFetcher(getter_
,
562 kLoadFlagsIgnoreCookies
,
564 fetch_pending_
= true;
568 void GaiaAuthFetcher::StartCookieForOAuthLoginTokenExchange(
569 const std::string
& session_index
) {
570 StartCookieForOAuthLoginTokenExchangeWithDeviceId(session_index
,
574 void GaiaAuthFetcher::StartCookieForOAuthLoginTokenExchangeWithDeviceId(
575 const std::string
& session_index
,
576 const std::string
& device_id
) {
577 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
579 DVLOG(1) << "Starting OAuth login token fetch with cookie jar";
580 request_body_
= MakeGetAuthCodeBody(!device_id
.empty());
582 client_login_to_oauth2_gurl_
=
583 GaiaUrls::GetInstance()->client_login_to_oauth2_url();
584 if (!session_index
.empty()) {
585 client_login_to_oauth2_gurl_
=
586 client_login_to_oauth2_gurl_
.Resolve("?authuser=" + session_index
);
589 std::string device_id_header
;
590 if (!device_id
.empty()) {
592 base::StringPrintf(kDeviceIdHeaderFormat
, device_id
.c_str());
595 fetcher_
.reset(CreateGaiaFetcher(getter_
,
598 client_login_to_oauth2_gurl_
,
601 fetch_pending_
= true;
605 void GaiaAuthFetcher::StartAuthCodeForOAuth2TokenExchange(
606 const std::string
& auth_code
) {
607 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
609 DVLOG(1) << "Starting OAuth token pair fetch";
610 request_body_
= MakeGetTokenPairBody(auth_code
);
611 fetcher_
.reset(CreateGaiaFetcher(getter_
,
615 kLoadFlagsIgnoreCookies
,
617 fetch_pending_
= true;
621 void GaiaAuthFetcher::StartGetUserInfo(const std::string
& lsid
) {
622 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
624 DVLOG(1) << "Starting GetUserInfo for lsid=" << lsid
;
625 request_body_
= MakeGetUserInfoBody(lsid
);
626 fetcher_
.reset(CreateGaiaFetcher(getter_
,
630 kLoadFlagsIgnoreCookies
,
632 fetch_pending_
= true;
636 void GaiaAuthFetcher::StartMergeSession(const std::string
& uber_token
,
637 const std::string
& external_cc_result
) {
638 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
640 DVLOG(1) << "Starting MergeSession with uber_token=" << uber_token
;
642 // The continue URL is a required parameter of the MergeSession API, but in
643 // this case we don't actually need or want to navigate to it. Setting it to
644 // an arbitrary Google URL.
646 // In order for the new session to be merged correctly, the server needs to
647 // know what sessions already exist in the browser. The fetcher needs to be
648 // created such that it sends the cookies with the request, which is
649 // different from all other requests the fetcher can make.
650 std::string
continue_url("http://www.google.com");
651 request_body_
= MakeMergeSessionBody(uber_token
, external_cc_result
,
652 continue_url
, source_
);
653 fetcher_
.reset(CreateGaiaFetcher(getter_
,
659 fetch_pending_
= true;
663 void GaiaAuthFetcher::StartTokenFetchForUberAuthExchange(
664 const std::string
& access_token
) {
665 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
667 DVLOG(1) << "Starting StartTokenFetchForUberAuthExchange with access_token="
669 std::string authentication_header
=
670 base::StringPrintf(kOAuthHeaderFormat
, access_token
.c_str());
671 fetcher_
.reset(CreateGaiaFetcher(getter_
,
673 authentication_header
,
674 uberauth_token_gurl_
,
677 fetch_pending_
= true;
681 void GaiaAuthFetcher::StartOAuthLogin(const std::string
& access_token
,
682 const std::string
& service
) {
683 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
685 request_body_
= MakeOAuthLoginBody(service
, source_
);
686 std::string authentication_header
=
687 base::StringPrintf(kOAuth2BearerHeaderFormat
, access_token
.c_str());
688 fetcher_
.reset(CreateGaiaFetcher(getter_
,
690 authentication_header
,
694 fetch_pending_
= true;
698 void GaiaAuthFetcher::StartListAccounts() {
699 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
701 fetcher_
.reset(CreateGaiaFetcher(getter_
,
702 " ", // To force an HTTP POST.
703 "Origin: https://www.google.com",
707 fetch_pending_
= true;
711 void GaiaAuthFetcher::StartGetCheckConnectionInfo() {
712 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
714 fetcher_
.reset(CreateGaiaFetcher(getter_
,
717 get_check_connection_info_url_
,
718 kLoadFlagsIgnoreCookies
,
720 fetch_pending_
= true;
725 GoogleServiceAuthError
GaiaAuthFetcher::GenerateAuthError(
726 const std::string
& data
,
727 const net::URLRequestStatus
& status
) {
728 if (!status
.is_success()) {
729 if (status
.status() == net::URLRequestStatus::CANCELED
) {
730 return GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED
);
732 DLOG(WARNING
) << "Could not reach Google Accounts servers: errno "
734 return GoogleServiceAuthError::FromConnectionError(status
.error());
737 if (IsSecondFactorSuccess(data
))
738 return GoogleServiceAuthError(GoogleServiceAuthError::TWO_FACTOR
);
742 std::string captcha_url
;
743 std::string captcha_token
;
744 ParseClientLoginFailure(data
, &error
, &url
, &captcha_url
, &captcha_token
);
745 DLOG(WARNING
) << "ClientLogin failed with " << error
;
747 if (error
== kCaptchaError
) {
748 return GoogleServiceAuthError::FromClientLoginCaptchaChallenge(
750 GURL(GaiaUrls::GetInstance()->captcha_base_url().Resolve(captcha_url
)),
753 if (error
== kAccountDeletedError
)
754 return GoogleServiceAuthError(GoogleServiceAuthError::ACCOUNT_DELETED
);
755 if (error
== kAccountDisabledError
)
756 return GoogleServiceAuthError(GoogleServiceAuthError::ACCOUNT_DISABLED
);
757 if (error
== kBadAuthenticationError
) {
758 return GoogleServiceAuthError(
759 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS
);
761 if (error
== kServiceUnavailableError
) {
762 return GoogleServiceAuthError(
763 GoogleServiceAuthError::SERVICE_UNAVAILABLE
);
766 DLOG(WARNING
) << "Incomprehensible response from Google Accounts servers.";
767 return GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_UNAVAILABLE
);
770 void GaiaAuthFetcher::OnClientLoginFetched(const std::string
& data
,
771 const net::URLRequestStatus
& status
,
773 if (status
.is_success() && response_code
== net::HTTP_OK
) {
774 DVLOG(1) << "ClientLogin successful!";
778 ParseClientLoginResponse(data
, &sid
, &lsid
, &token
);
779 consumer_
->OnClientLoginSuccess(
780 GaiaAuthConsumer::ClientLoginResult(sid
, lsid
, token
, data
));
782 consumer_
->OnClientLoginFailure(GenerateAuthError(data
, status
));
786 void GaiaAuthFetcher::OnIssueAuthTokenFetched(
787 const std::string
& data
,
788 const net::URLRequestStatus
& status
,
790 if (status
.is_success() && response_code
== net::HTTP_OK
) {
791 // Only the bare token is returned in the body of this Gaia call
792 // without any padding.
793 consumer_
->OnIssueAuthTokenSuccess(requested_service_
, data
);
795 consumer_
->OnIssueAuthTokenFailure(requested_service_
,
796 GenerateAuthError(data
, status
));
800 void GaiaAuthFetcher::OnClientLoginToOAuth2Fetched(
801 const std::string
& data
,
802 const net::ResponseCookies
& cookies
,
803 const net::URLRequestStatus
& status
,
805 if (status
.is_success() && response_code
== net::HTTP_OK
) {
806 std::string auth_code
;
807 if (ParseClientLoginToOAuth2Response(cookies
, &auth_code
)) {
808 StartAuthCodeForOAuth2TokenExchange(auth_code
);
810 GoogleServiceAuthError
auth_error(
811 GoogleServiceAuthError::FromUnexpectedServiceResponse(
812 "ClientLogin response cookies didn't contain an auth code"));
813 consumer_
->OnClientOAuthFailure(auth_error
);
816 GoogleServiceAuthError
auth_error(GenerateAuthError(data
, status
));
817 consumer_
->OnClientOAuthFailure(auth_error
);
821 void GaiaAuthFetcher::OnOAuth2TokenPairFetched(
822 const std::string
& data
,
823 const net::URLRequestStatus
& status
,
825 std::string refresh_token
;
826 std::string access_token
;
827 int expires_in_secs
= 0;
829 bool success
= false;
830 if (status
.is_success() && response_code
== net::HTTP_OK
) {
831 scoped_ptr
<base::Value
> value(base::JSONReader::Read(data
));
832 if (value
.get() && value
->GetType() == base::Value::TYPE_DICTIONARY
) {
833 base::DictionaryValue
* dict
=
834 static_cast<base::DictionaryValue
*>(value
.get());
835 success
= ExtractOAuth2TokenPairResponse(dict
, &refresh_token
,
836 &access_token
, &expires_in_secs
);
841 consumer_
->OnClientOAuthSuccess(
842 GaiaAuthConsumer::ClientOAuthResult(refresh_token
, access_token
,
845 consumer_
->OnClientOAuthFailure(GenerateAuthError(data
, status
));
849 void GaiaAuthFetcher::OnOAuth2RevokeTokenFetched(
850 const std::string
& data
,
851 const net::URLRequestStatus
& status
,
853 consumer_
->OnOAuth2RevokeTokenCompleted();
856 void GaiaAuthFetcher::OnListAccountsFetched(const std::string
& data
,
857 const net::URLRequestStatus
& status
,
859 if (status
.is_success() && response_code
== net::HTTP_OK
) {
860 consumer_
->OnListAccountsSuccess(data
);
862 consumer_
->OnListAccountsFailure(GenerateAuthError(data
, status
));
866 void GaiaAuthFetcher::OnGetUserInfoFetched(
867 const std::string
& data
,
868 const net::URLRequestStatus
& status
,
870 if (status
.is_success() && response_code
== net::HTTP_OK
) {
871 base::StringPairs tokens
;
873 base::SplitStringIntoKeyValuePairs(data
, '=', '\n', &tokens
);
874 base::StringPairs::iterator i
;
875 for (i
= tokens
.begin(); i
!= tokens
.end(); ++i
) {
876 matches
[i
->first
] = i
->second
;
878 consumer_
->OnGetUserInfoSuccess(matches
);
880 consumer_
->OnGetUserInfoFailure(GenerateAuthError(data
, status
));
884 void GaiaAuthFetcher::OnMergeSessionFetched(const std::string
& data
,
885 const net::URLRequestStatus
& status
,
887 if (status
.is_success() && response_code
== net::HTTP_OK
) {
888 consumer_
->OnMergeSessionSuccess(data
);
890 consumer_
->OnMergeSessionFailure(GenerateAuthError(data
, status
));
894 void GaiaAuthFetcher::OnUberAuthTokenFetch(const std::string
& data
,
895 const net::URLRequestStatus
& status
,
897 if (status
.is_success() && response_code
== net::HTTP_OK
) {
898 consumer_
->OnUberAuthTokenSuccess(data
);
900 consumer_
->OnUberAuthTokenFailure(GenerateAuthError(data
, status
));
904 void GaiaAuthFetcher::OnOAuthLoginFetched(const std::string
& data
,
905 const net::URLRequestStatus
& status
,
907 if (status
.is_success() && response_code
== net::HTTP_OK
) {
908 DVLOG(1) << "ClientLogin successful!";
912 ParseClientLoginResponse(data
, &sid
, &lsid
, &token
);
913 consumer_
->OnClientLoginSuccess(
914 GaiaAuthConsumer::ClientLoginResult(sid
, lsid
, token
, data
));
916 consumer_
->OnClientLoginFailure(GenerateAuthError(data
, status
));
920 void GaiaAuthFetcher::OnGetCheckConnectionInfoFetched(
921 const std::string
& data
,
922 const net::URLRequestStatus
& status
,
924 if (status
.is_success() && response_code
== net::HTTP_OK
) {
925 consumer_
->OnGetCheckConnectionInfoSuccess(data
);
927 consumer_
->OnGetCheckConnectionInfoError(GenerateAuthError(data
, status
));
931 void GaiaAuthFetcher::OnURLFetchComplete(const net::URLFetcher
* source
) {
932 fetch_pending_
= false;
933 // Some of the GAIA requests perform redirects, which results in the final
934 // URL of the fetcher not being the original URL requested. Therefore use
935 // the original URL when determining which OnXXX function to call.
936 const GURL
& url
= source
->GetOriginalURL();
937 const net::URLRequestStatus
& status
= source
->GetStatus();
938 int response_code
= source
->GetResponseCode();
940 source
->GetResponseAsString(&data
);
943 if (source
->GetResponseHeaders())
944 source
->GetResponseHeaders()->GetNormalizedHeaders(&headers
);
945 DVLOG(2) << "Response " << url
.spec() << ", code = " << response_code
<< "\n"
947 DVLOG(2) << "data: " << data
<< "\n";
949 // Retrieve the response headers from the request. Must only be called after
950 // the OnURLFetchComplete callback has run.
951 if (url
== client_login_gurl_
) {
952 OnClientLoginFetched(data
, status
, response_code
);
953 } else if (url
== issue_auth_token_gurl_
) {
954 OnIssueAuthTokenFetched(data
, status
, response_code
);
955 } else if (url
== client_login_to_oauth2_gurl_
) {
956 OnClientLoginToOAuth2Fetched(
957 data
, source
->GetCookies(), status
, response_code
);
958 } else if (url
== oauth2_token_gurl_
) {
959 OnOAuth2TokenPairFetched(data
, status
, response_code
);
960 } else if (url
== get_user_info_gurl_
) {
961 OnGetUserInfoFetched(data
, status
, response_code
);
962 } else if (url
== merge_session_gurl_
) {
963 OnMergeSessionFetched(data
, status
, response_code
);
964 } else if (url
== uberauth_token_gurl_
) {
965 OnUberAuthTokenFetch(data
, status
, response_code
);
966 } else if (url
== oauth_login_gurl_
) {
967 OnOAuthLoginFetched(data
, status
, response_code
);
968 } else if (url
== oauth2_revoke_gurl_
) {
969 OnOAuth2RevokeTokenFetched(data
, status
, response_code
);
970 } else if (url
== list_accounts_gurl_
) {
971 OnListAccountsFetched(data
, status
, response_code
);
972 } else if (url
== get_check_connection_info_url_
) {
973 OnGetCheckConnectionInfoFetched(data
, status
, response_code
);
980 bool GaiaAuthFetcher::IsSecondFactorSuccess(
981 const std::string
& alleged_error
) {
982 return alleged_error
.find(kSecondFactor
) !=