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::kOAuth2CodeToTokenPairBodyFormat
[] =
93 "grant_type=authorization_code&"
98 const char GaiaAuthFetcher::kOAuth2RevokeTokenBodyFormat
[] =
101 const char GaiaAuthFetcher::kGetUserInfoFormat
[] =
104 const char GaiaAuthFetcher::kMergeSessionFormat
[] =
109 const char GaiaAuthFetcher::kUberAuthTokenURLFormat
[] =
113 const char GaiaAuthFetcher::kOAuthLoginFormat
[] = "service=%s&source=%s";
116 const char GaiaAuthFetcher::kAccountDeletedError
[] = "AccountDeleted";
118 const char GaiaAuthFetcher::kAccountDisabledError
[] = "AccountDisabled";
120 const char GaiaAuthFetcher::kBadAuthenticationError
[] = "BadAuthentication";
122 const char GaiaAuthFetcher::kCaptchaError
[] = "CaptchaRequired";
124 const char GaiaAuthFetcher::kServiceUnavailableError
[] =
125 "ServiceUnavailable";
127 const char GaiaAuthFetcher::kErrorParam
[] = "Error";
129 const char GaiaAuthFetcher::kErrorUrlParam
[] = "Url";
131 const char GaiaAuthFetcher::kCaptchaUrlParam
[] = "CaptchaUrl";
133 const char GaiaAuthFetcher::kCaptchaTokenParam
[] = "CaptchaToken";
136 const char GaiaAuthFetcher::kCookiePersistence
[] = "true";
138 // TODO(johnnyg): When hosted accounts are supported by sync,
139 // we can always use "HOSTED_OR_GOOGLE"
140 const char GaiaAuthFetcher::kAccountTypeHostedOrGoogle
[] =
142 const char GaiaAuthFetcher::kAccountTypeGoogle
[] =
146 const char GaiaAuthFetcher::kSecondFactor
[] = "Info=InvalidSecondFactor";
149 const char GaiaAuthFetcher::kAuthHeaderFormat
[] =
150 "Authorization: GoogleLogin auth=%s";
152 const char GaiaAuthFetcher::kOAuthHeaderFormat
[] = "Authorization: OAuth %s";
154 const char GaiaAuthFetcher::kOAuth2BearerHeaderFormat
[] =
155 "Authorization: Bearer %s";
157 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartSecure
[] = "secure";
159 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartHttpOnly
[] =
162 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefix
[] =
165 const int GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefixLength
=
166 arraysize(GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefix
) - 1;
168 GaiaAuthFetcher::GaiaAuthFetcher(GaiaAuthConsumer
* consumer
,
169 const std::string
& source
,
170 net::URLRequestContextGetter
* getter
)
171 : consumer_(consumer
),
174 client_login_gurl_(GaiaUrls::GetInstance()->client_login_url()),
175 issue_auth_token_gurl_(GaiaUrls::GetInstance()->issue_auth_token_url()),
176 oauth2_token_gurl_(GaiaUrls::GetInstance()->oauth2_token_url()),
177 oauth2_revoke_gurl_(GaiaUrls::GetInstance()->oauth2_revoke_url()),
178 get_user_info_gurl_(GaiaUrls::GetInstance()->get_user_info_url()),
179 merge_session_gurl_(GaiaUrls::GetInstance()->merge_session_url()),
180 uberauth_token_gurl_(GaiaUrls::GetInstance()->oauth1_login_url().Resolve(
181 base::StringPrintf(kUberAuthTokenURLFormat
, source
.c_str()))),
182 oauth_login_gurl_(GaiaUrls::GetInstance()->oauth1_login_url()),
183 list_accounts_gurl_(GaiaUrls::GetInstance()->list_accounts_url()),
184 client_login_to_oauth2_gurl_(
185 GaiaUrls::GetInstance()->client_login_to_oauth2_url()),
186 fetch_pending_(false),
187 fetch_code_only_(false) {}
189 GaiaAuthFetcher::~GaiaAuthFetcher() {}
191 bool GaiaAuthFetcher::HasPendingFetch() {
192 return fetch_pending_
;
195 void GaiaAuthFetcher::CancelRequest() {
197 fetch_pending_
= false;
201 net::URLFetcher
* GaiaAuthFetcher::CreateGaiaFetcher(
202 net::URLRequestContextGetter
* getter
,
203 const std::string
& body
,
204 const std::string
& headers
,
205 const GURL
& gaia_gurl
,
207 net::URLFetcherDelegate
* delegate
) {
208 net::URLFetcher
* to_return
= net::URLFetcher::Create(
210 body
== "" ? net::URLFetcher::GET
: net::URLFetcher::POST
,
212 to_return
->SetRequestContext(getter
);
213 to_return
->SetUploadData("application/x-www-form-urlencoded", body
);
215 DVLOG(2) << "Gaia fetcher URL: " << gaia_gurl
.spec();
216 DVLOG(2) << "Gaia fetcher headers: " << headers
;
217 DVLOG(2) << "Gaia fetcher body: " << body
;
219 // The Gaia token exchange requests do not require any cookie-based
220 // identification as part of requests. We suppress sending any cookies to
221 // maintain a separation between the user's browsing and Chrome's internal
222 // services. Where such mixing is desired (MergeSession or OAuthLogin), it
223 // will be done explicitly.
224 to_return
->SetLoadFlags(load_flags
);
226 // Fetchers are sometimes cancelled because a network change was detected,
227 // especially at startup and after sign-in on ChromeOS. Retrying once should
228 // be enough in those cases; let the fetcher retry up to 3 times just in case.
229 // http://crbug.com/163710
230 to_return
->SetAutomaticallyRetryOnNetworkChanges(3);
232 if (!headers
.empty())
233 to_return
->SetExtraRequestHeaders(headers
);
239 std::string
GaiaAuthFetcher::MakeClientLoginBody(
240 const std::string
& username
,
241 const std::string
& password
,
242 const std::string
& source
,
244 const std::string
& login_token
,
245 const std::string
& login_captcha
,
246 HostedAccountsSetting allow_hosted_accounts
) {
247 std::string encoded_username
= net::EscapeUrlEncodedData(username
, true);
248 std::string encoded_password
= net::EscapeUrlEncodedData(password
, true);
249 std::string encoded_login_token
= net::EscapeUrlEncodedData(login_token
,
251 std::string encoded_login_captcha
= net::EscapeUrlEncodedData(login_captcha
,
254 const char* account_type
= allow_hosted_accounts
== HostedAccountsAllowed
?
255 kAccountTypeHostedOrGoogle
:
258 if (login_token
.empty() || login_captcha
.empty()) {
259 return base::StringPrintf(kClientLoginFormat
,
260 encoded_username
.c_str(),
261 encoded_password
.c_str(),
268 return base::StringPrintf(kClientLoginCaptchaFormat
,
269 encoded_username
.c_str(),
270 encoded_password
.c_str(),
275 encoded_login_token
.c_str(),
276 encoded_login_captcha
.c_str());
280 std::string
GaiaAuthFetcher::MakeIssueAuthTokenBody(
281 const std::string
& sid
,
282 const std::string
& lsid
,
283 const char* const service
) {
284 std::string encoded_sid
= net::EscapeUrlEncodedData(sid
, true);
285 std::string encoded_lsid
= net::EscapeUrlEncodedData(lsid
, true);
287 // All tokens should be session tokens except the gaia auth token.
289 if (!strcmp(service
, GaiaConstants::kGaiaService
))
292 return base::StringPrintf(kIssueAuthTokenFormat
,
294 encoded_lsid
.c_str(),
296 session
? "true" : "false");
300 std::string
GaiaAuthFetcher::MakeGetAuthCodeBody() {
301 std::string encoded_scope
= net::EscapeUrlEncodedData(
302 GaiaConstants::kOAuth1LoginScope
, true);
303 std::string encoded_client_id
= net::EscapeUrlEncodedData(
304 GaiaUrls::GetInstance()->oauth2_chrome_client_id(), true);
305 return base::StringPrintf(kClientLoginToOAuth2BodyFormat
,
306 encoded_scope
.c_str(),
307 encoded_client_id
.c_str());
311 std::string
GaiaAuthFetcher::MakeGetTokenPairBody(
312 const std::string
& auth_code
) {
313 std::string encoded_scope
= net::EscapeUrlEncodedData(
314 GaiaConstants::kOAuth1LoginScope
, true);
315 std::string encoded_client_id
= net::EscapeUrlEncodedData(
316 GaiaUrls::GetInstance()->oauth2_chrome_client_id(), true);
317 std::string encoded_client_secret
= net::EscapeUrlEncodedData(
318 GaiaUrls::GetInstance()->oauth2_chrome_client_secret(), true);
319 std::string encoded_auth_code
= net::EscapeUrlEncodedData(auth_code
, true);
320 return base::StringPrintf(kOAuth2CodeToTokenPairBodyFormat
,
321 encoded_scope
.c_str(),
322 encoded_client_id
.c_str(),
323 encoded_client_secret
.c_str(),
324 encoded_auth_code
.c_str());
328 std::string
GaiaAuthFetcher::MakeRevokeTokenBody(
329 const std::string
& auth_token
) {
330 return base::StringPrintf(kOAuth2RevokeTokenBodyFormat
, auth_token
.c_str());
334 std::string
GaiaAuthFetcher::MakeGetUserInfoBody(const std::string
& lsid
) {
335 std::string encoded_lsid
= net::EscapeUrlEncodedData(lsid
, true);
336 return base::StringPrintf(kGetUserInfoFormat
, encoded_lsid
.c_str());
340 std::string
GaiaAuthFetcher::MakeMergeSessionBody(
341 const std::string
& auth_token
,
342 const std::string
& continue_url
,
343 const std::string
& source
) {
344 std::string encoded_auth_token
= net::EscapeUrlEncodedData(auth_token
, true);
345 std::string encoded_continue_url
= net::EscapeUrlEncodedData(continue_url
,
347 std::string encoded_source
= net::EscapeUrlEncodedData(source
, true);
348 return base::StringPrintf(kMergeSessionFormat
,
349 encoded_auth_token
.c_str(),
350 encoded_continue_url
.c_str(),
351 encoded_source
.c_str());
355 std::string
GaiaAuthFetcher::MakeGetAuthCodeHeader(
356 const std::string
& auth_token
) {
357 return base::StringPrintf(kAuthHeaderFormat
, auth_token
.c_str());
360 // Helper method that extracts tokens from a successful reply.
362 void GaiaAuthFetcher::ParseClientLoginResponse(const std::string
& data
,
365 std::string
* token
) {
372 vector
<pair
<string
, string
> > tokens
;
373 base::SplitStringIntoKeyValuePairs(data
, '=', '\n', &tokens
);
374 for (vector
<pair
<string
, string
> >::iterator i
= tokens
.begin();
375 i
!= tokens
.end(); ++i
) {
376 if (i
->first
== "SID") {
377 sid
->assign(i
->second
);
378 } else if (i
->first
== "LSID") {
379 lsid
->assign(i
->second
);
380 } else if (i
->first
== "Auth") {
381 token
->assign(i
->second
);
384 // If this was a request for uberauth token, then that's all we've got in
386 if (sid
->empty() && lsid
->empty() && token
->empty())
391 std::string
GaiaAuthFetcher::MakeOAuthLoginBody(const std::string
& service
,
392 const std::string
& source
) {
393 std::string encoded_service
= net::EscapeUrlEncodedData(service
, true);
394 std::string encoded_source
= net::EscapeUrlEncodedData(source
, true);
395 return base::StringPrintf(kOAuthLoginFormat
,
396 encoded_service
.c_str(),
397 encoded_source
.c_str());
401 void GaiaAuthFetcher::ParseClientLoginFailure(const std::string
& data
,
403 std::string
* error_url
,
404 std::string
* captcha_url
,
405 std::string
* captcha_token
) {
410 vector
<pair
<string
, string
> > tokens
;
411 base::SplitStringIntoKeyValuePairs(data
, '=', '\n', &tokens
);
412 for (vector
<pair
<string
, string
> >::iterator i
= tokens
.begin();
413 i
!= tokens
.end(); ++i
) {
414 if (i
->first
== kErrorParam
) {
415 error
->assign(i
->second
);
416 } else if (i
->first
== kErrorUrlParam
) {
417 error_url
->assign(i
->second
);
418 } else if (i
->first
== kCaptchaUrlParam
) {
419 captcha_url
->assign(i
->second
);
420 } else if (i
->first
== kCaptchaTokenParam
) {
421 captcha_token
->assign(i
->second
);
427 bool GaiaAuthFetcher::ParseClientLoginToOAuth2Response(
428 const net::ResponseCookies
& cookies
,
429 std::string
* auth_code
) {
431 net::ResponseCookies::const_iterator iter
;
432 for (iter
= cookies
.begin(); iter
!= cookies
.end(); ++iter
) {
433 if (ParseClientLoginToOAuth2Cookie(*iter
, auth_code
))
440 bool GaiaAuthFetcher::ParseClientLoginToOAuth2Cookie(const std::string
& cookie
,
441 std::string
* auth_code
) {
442 std::vector
<std::string
> parts
;
443 base::SplitString(cookie
, ';', &parts
);
444 // Per documentation, the cookie should have Secure and HttpOnly.
445 if (!CookiePartsContains(parts
, kClientLoginToOAuth2CookiePartSecure
) ||
446 !CookiePartsContains(parts
, kClientLoginToOAuth2CookiePartHttpOnly
)) {
450 std::vector
<std::string
>::const_iterator iter
;
451 for (iter
= parts
.begin(); iter
!= parts
.end(); ++iter
) {
452 const std::string
& part
= *iter
;
454 part
, kClientLoginToOAuth2CookiePartCodePrefix
, false)) {
455 auth_code
->assign(part
.substr(
456 kClientLoginToOAuth2CookiePartCodePrefixLength
));
463 void GaiaAuthFetcher::StartClientLogin(
464 const std::string
& username
,
465 const std::string
& password
,
466 const char* const service
,
467 const std::string
& login_token
,
468 const std::string
& login_captcha
,
469 HostedAccountsSetting allow_hosted_accounts
) {
471 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
473 // This class is thread agnostic, so be sure to call this only on the
474 // same thread each time.
475 DVLOG(1) << "Starting new ClientLogin fetch for:" << username
;
477 // Must outlive fetcher_.
478 request_body_
= MakeClientLoginBody(username
,
484 allow_hosted_accounts
);
485 fetcher_
.reset(CreateGaiaFetcher(getter_
,
489 kLoadFlagsIgnoreCookies
,
491 fetch_pending_
= true;
495 void GaiaAuthFetcher::StartIssueAuthToken(const std::string
& sid
,
496 const std::string
& lsid
,
497 const char* const service
) {
498 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
500 DVLOG(1) << "Starting IssueAuthToken for: " << service
;
501 requested_service_
= service
;
502 request_body_
= MakeIssueAuthTokenBody(sid
, lsid
, service
);
503 fetcher_
.reset(CreateGaiaFetcher(getter_
,
506 issue_auth_token_gurl_
,
507 kLoadFlagsIgnoreCookies
,
509 fetch_pending_
= true;
513 void GaiaAuthFetcher::StartLsoForOAuthLoginTokenExchange(
514 const std::string
& auth_token
) {
515 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
517 DVLOG(1) << "Starting OAuth login token exchange with auth_token";
518 request_body_
= MakeGetAuthCodeBody();
519 client_login_to_oauth2_gurl_
=
520 GaiaUrls::GetInstance()->client_login_to_oauth2_url();
522 fetcher_
.reset(CreateGaiaFetcher(getter_
,
524 MakeGetAuthCodeHeader(auth_token
),
525 client_login_to_oauth2_gurl_
,
526 kLoadFlagsIgnoreCookies
,
528 fetch_pending_
= true;
532 void GaiaAuthFetcher::StartRevokeOAuth2Token(const std::string
& auth_token
) {
533 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
535 DVLOG(1) << "Starting OAuth2 token revocation";
536 request_body_
= MakeRevokeTokenBody(auth_token
);
537 fetcher_
.reset(CreateGaiaFetcher(getter_
,
541 kLoadFlagsIgnoreCookies
,
543 fetch_pending_
= true;
547 void GaiaAuthFetcher::StartCookieForOAuthCodeExchange(
548 const std::string
& session_index
) {
549 // Same as the first step of StartCookieForOAuthLoginTokenExchange;
550 StartCookieForOAuthLoginTokenExchange(session_index
);
551 fetch_code_only_
= true;
554 void GaiaAuthFetcher::StartCookieForOAuthLoginTokenExchange(
555 const std::string
& session_index
) {
556 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
558 DVLOG(1) << "Starting OAuth login token fetch with cookie jar";
559 request_body_
= MakeGetAuthCodeBody();
561 client_login_to_oauth2_gurl_
=
562 GaiaUrls::GetInstance()->client_login_to_oauth2_url();
563 if (!session_index
.empty()) {
564 client_login_to_oauth2_gurl_
=
565 client_login_to_oauth2_gurl_
.Resolve("?authuser=" + session_index
);
568 fetcher_
.reset(CreateGaiaFetcher(getter_
,
571 client_login_to_oauth2_gurl_
,
574 fetch_pending_
= true;
575 fetch_code_only_
= false;
579 void GaiaAuthFetcher::StartAuthCodeForOAuth2TokenExchange(
580 const std::string
& auth_code
) {
581 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
583 DVLOG(1) << "Starting OAuth token pair fetch";
584 request_body_
= MakeGetTokenPairBody(auth_code
);
585 fetcher_
.reset(CreateGaiaFetcher(getter_
,
589 kLoadFlagsIgnoreCookies
,
591 fetch_pending_
= true;
595 void GaiaAuthFetcher::StartGetUserInfo(const std::string
& lsid
) {
596 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
598 DVLOG(1) << "Starting GetUserInfo for lsid=" << lsid
;
599 request_body_
= MakeGetUserInfoBody(lsid
);
600 fetcher_
.reset(CreateGaiaFetcher(getter_
,
604 kLoadFlagsIgnoreCookies
,
606 fetch_pending_
= true;
610 void GaiaAuthFetcher::StartMergeSession(const std::string
& uber_token
) {
611 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
613 DVLOG(1) << "Starting MergeSession with uber_token=" << uber_token
;
615 // The continue URL is a required parameter of the MergeSession API, but in
616 // this case we don't actually need or want to navigate to it. Setting it to
617 // an arbitrary Google URL.
619 // In order for the new session to be merged correctly, the server needs to
620 // know what sessions already exist in the browser. The fetcher needs to be
621 // created such that it sends the cookies with the request, which is
622 // different from all other requests the fetcher can make.
623 std::string
continue_url("http://www.google.com");
624 request_body_
= MakeMergeSessionBody(uber_token
, continue_url
, source_
);
625 fetcher_
.reset(CreateGaiaFetcher(getter_
,
631 fetch_pending_
= true;
635 void GaiaAuthFetcher::StartTokenFetchForUberAuthExchange(
636 const std::string
& access_token
) {
637 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
639 DVLOG(1) << "Starting StartTokenFetchForUberAuthExchange with access_token="
641 std::string authentication_header
=
642 base::StringPrintf(kOAuthHeaderFormat
, access_token
.c_str());
643 fetcher_
.reset(CreateGaiaFetcher(getter_
,
645 authentication_header
,
646 uberauth_token_gurl_
,
649 fetch_pending_
= true;
653 void GaiaAuthFetcher::StartOAuthLogin(const std::string
& access_token
,
654 const std::string
& service
) {
655 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
657 request_body_
= MakeOAuthLoginBody(service
, source_
);
658 std::string authentication_header
=
659 base::StringPrintf(kOAuth2BearerHeaderFormat
, access_token
.c_str());
660 fetcher_
.reset(CreateGaiaFetcher(getter_
,
662 authentication_header
,
666 fetch_pending_
= true;
670 void GaiaAuthFetcher::StartListAccounts() {
671 DCHECK(!fetch_pending_
) << "Tried to fetch two things at once!";
673 fetcher_
.reset(CreateGaiaFetcher(getter_
,
674 " ", // To force an HTTP POST.
675 "Origin: https://www.google.com",
679 fetch_pending_
= true;
684 GoogleServiceAuthError
GaiaAuthFetcher::GenerateAuthError(
685 const std::string
& data
,
686 const net::URLRequestStatus
& status
) {
687 if (!status
.is_success()) {
688 if (status
.status() == net::URLRequestStatus::CANCELED
) {
689 return GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED
);
691 DLOG(WARNING
) << "Could not reach Google Accounts servers: errno "
693 return GoogleServiceAuthError::FromConnectionError(status
.error());
696 if (IsSecondFactorSuccess(data
))
697 return GoogleServiceAuthError(GoogleServiceAuthError::TWO_FACTOR
);
701 std::string captcha_url
;
702 std::string captcha_token
;
703 ParseClientLoginFailure(data
, &error
, &url
, &captcha_url
, &captcha_token
);
704 DLOG(WARNING
) << "ClientLogin failed with " << error
;
706 if (error
== kCaptchaError
) {
707 return GoogleServiceAuthError::FromClientLoginCaptchaChallenge(
709 GURL(GaiaUrls::GetInstance()->captcha_base_url().Resolve(captcha_url
)),
712 if (error
== kAccountDeletedError
)
713 return GoogleServiceAuthError(GoogleServiceAuthError::ACCOUNT_DELETED
);
714 if (error
== kAccountDisabledError
)
715 return GoogleServiceAuthError(GoogleServiceAuthError::ACCOUNT_DISABLED
);
716 if (error
== kBadAuthenticationError
) {
717 return GoogleServiceAuthError(
718 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS
);
720 if (error
== kServiceUnavailableError
) {
721 return GoogleServiceAuthError(
722 GoogleServiceAuthError::SERVICE_UNAVAILABLE
);
725 DLOG(WARNING
) << "Incomprehensible response from Google Accounts servers.";
726 return GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_UNAVAILABLE
);
729 void GaiaAuthFetcher::OnClientLoginFetched(const std::string
& data
,
730 const net::URLRequestStatus
& status
,
732 if (status
.is_success() && response_code
== net::HTTP_OK
) {
733 DVLOG(1) << "ClientLogin successful!";
737 ParseClientLoginResponse(data
, &sid
, &lsid
, &token
);
738 consumer_
->OnClientLoginSuccess(
739 GaiaAuthConsumer::ClientLoginResult(sid
, lsid
, token
, data
));
741 consumer_
->OnClientLoginFailure(GenerateAuthError(data
, status
));
745 void GaiaAuthFetcher::OnIssueAuthTokenFetched(
746 const std::string
& data
,
747 const net::URLRequestStatus
& status
,
749 if (status
.is_success() && response_code
== net::HTTP_OK
) {
750 // Only the bare token is returned in the body of this Gaia call
751 // without any padding.
752 consumer_
->OnIssueAuthTokenSuccess(requested_service_
, data
);
754 consumer_
->OnIssueAuthTokenFailure(requested_service_
,
755 GenerateAuthError(data
, status
));
759 void GaiaAuthFetcher::OnClientLoginToOAuth2Fetched(
760 const std::string
& data
,
761 const net::ResponseCookies
& cookies
,
762 const net::URLRequestStatus
& status
,
764 if (status
.is_success() && response_code
== net::HTTP_OK
) {
765 std::string auth_code
;
766 ParseClientLoginToOAuth2Response(cookies
, &auth_code
);
767 if (fetch_code_only_
)
768 consumer_
->OnClientOAuthCodeSuccess(auth_code
);
770 StartAuthCodeForOAuth2TokenExchange(auth_code
);
772 GoogleServiceAuthError
auth_error(GenerateAuthError(data
, status
));
773 if (fetch_code_only_
)
774 consumer_
->OnClientOAuthCodeFailure(auth_error
);
776 consumer_
->OnClientOAuthFailure(auth_error
);
780 void GaiaAuthFetcher::OnOAuth2TokenPairFetched(
781 const std::string
& data
,
782 const net::URLRequestStatus
& status
,
784 std::string refresh_token
;
785 std::string access_token
;
786 int expires_in_secs
= 0;
788 bool success
= false;
789 if (status
.is_success() && response_code
== net::HTTP_OK
) {
790 scoped_ptr
<base::Value
> value(base::JSONReader::Read(data
));
791 if (value
.get() && value
->GetType() == base::Value::TYPE_DICTIONARY
) {
792 base::DictionaryValue
* dict
=
793 static_cast<base::DictionaryValue
*>(value
.get());
794 success
= ExtractOAuth2TokenPairResponse(dict
, &refresh_token
,
795 &access_token
, &expires_in_secs
);
800 consumer_
->OnClientOAuthSuccess(
801 GaiaAuthConsumer::ClientOAuthResult(refresh_token
, access_token
,
804 consumer_
->OnClientOAuthFailure(GenerateAuthError(data
, status
));
808 void GaiaAuthFetcher::OnOAuth2RevokeTokenFetched(
809 const std::string
& data
,
810 const net::URLRequestStatus
& status
,
812 consumer_
->OnOAuth2RevokeTokenCompleted();
815 void GaiaAuthFetcher::OnListAccountsFetched(const std::string
& data
,
816 const net::URLRequestStatus
& status
,
818 if (status
.is_success() && response_code
== net::HTTP_OK
) {
819 consumer_
->OnListAccountsSuccess(data
);
821 consumer_
->OnListAccountsFailure(GenerateAuthError(data
, status
));
825 void GaiaAuthFetcher::OnGetUserInfoFetched(
826 const std::string
& data
,
827 const net::URLRequestStatus
& status
,
829 if (status
.is_success() && response_code
== net::HTTP_OK
) {
830 std::vector
<std::pair
<std::string
, std::string
> > tokens
;
832 base::SplitStringIntoKeyValuePairs(data
, '=', '\n', &tokens
);
833 std::vector
<std::pair
<std::string
, std::string
> >::iterator i
;
834 for (i
= tokens
.begin(); i
!= tokens
.end(); ++i
) {
835 matches
[i
->first
] = i
->second
;
837 consumer_
->OnGetUserInfoSuccess(matches
);
839 consumer_
->OnGetUserInfoFailure(GenerateAuthError(data
, status
));
843 void GaiaAuthFetcher::OnMergeSessionFetched(const std::string
& data
,
844 const net::URLRequestStatus
& status
,
846 if (status
.is_success() && response_code
== net::HTTP_OK
) {
847 consumer_
->OnMergeSessionSuccess(data
);
849 consumer_
->OnMergeSessionFailure(GenerateAuthError(data
, status
));
853 void GaiaAuthFetcher::OnUberAuthTokenFetch(const std::string
& data
,
854 const net::URLRequestStatus
& status
,
856 if (status
.is_success() && response_code
== net::HTTP_OK
) {
857 consumer_
->OnUberAuthTokenSuccess(data
);
859 consumer_
->OnUberAuthTokenFailure(GenerateAuthError(data
, status
));
863 void GaiaAuthFetcher::OnOAuthLoginFetched(const std::string
& data
,
864 const net::URLRequestStatus
& status
,
866 if (status
.is_success() && response_code
== net::HTTP_OK
) {
867 DVLOG(1) << "ClientLogin successful!";
871 ParseClientLoginResponse(data
, &sid
, &lsid
, &token
);
872 consumer_
->OnClientLoginSuccess(
873 GaiaAuthConsumer::ClientLoginResult(sid
, lsid
, token
, data
));
875 consumer_
->OnClientLoginFailure(GenerateAuthError(data
, status
));
879 void GaiaAuthFetcher::OnURLFetchComplete(const net::URLFetcher
* source
) {
880 fetch_pending_
= false;
881 // Some of the GAIA requests perform redirects, which results in the final
882 // URL of the fetcher not being the original URL requested. Therefore use
883 // the original URL when determining which OnXXX function to call.
884 const GURL
& url
= source
->GetOriginalURL();
885 const net::URLRequestStatus
& status
= source
->GetStatus();
886 int response_code
= source
->GetResponseCode();
888 source
->GetResponseAsString(&data
);
891 if (source
->GetResponseHeaders())
892 source
->GetResponseHeaders()->GetNormalizedHeaders(&headers
);
893 DVLOG(2) << "Response " << url
.spec() << ", code = " << response_code
<< "\n"
895 DVLOG(2) << "data: " << data
<< "\n";
897 // Retrieve the response headers from the request. Must only be called after
898 // the OnURLFetchComplete callback has run.
899 if (url
== client_login_gurl_
) {
900 OnClientLoginFetched(data
, status
, response_code
);
901 } else if (url
== issue_auth_token_gurl_
) {
902 OnIssueAuthTokenFetched(data
, status
, response_code
);
903 } else if (url
== client_login_to_oauth2_gurl_
) {
904 OnClientLoginToOAuth2Fetched(
905 data
, source
->GetCookies(), status
, response_code
);
906 } else if (url
== oauth2_token_gurl_
) {
907 OnOAuth2TokenPairFetched(data
, status
, response_code
);
908 } else if (url
== get_user_info_gurl_
) {
909 OnGetUserInfoFetched(data
, status
, response_code
);
910 } else if (url
== merge_session_gurl_
) {
911 OnMergeSessionFetched(data
, status
, response_code
);
912 } else if (url
== uberauth_token_gurl_
) {
913 OnUberAuthTokenFetch(data
, status
, response_code
);
914 } else if (url
== oauth_login_gurl_
) {
915 OnOAuthLoginFetched(data
, status
, response_code
);
916 } else if (url
== oauth2_revoke_gurl_
) {
917 OnOAuth2RevokeTokenFetched(data
, status
, response_code
);
918 } else if (url
== list_accounts_gurl_
) {
919 OnListAccountsFetched(data
, status
, response_code
);
926 bool GaiaAuthFetcher::IsSecondFactorSuccess(
927 const std::string
& alleged_error
) {
928 return alleged_error
.find(kSecondFactor
) !=