fileapi: Use standard task-runner to run the fileapi callbacks.
[chromium-blink-merge.git] / google_apis / gaia / gaia_auth_fetcher.cc
blob3b3c1902540489725987f862119e7e63f3a98f6a
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"
7 #include <string>
8 #include <utility>
9 #include <vector>
11 #include "base/json/json_reader.h"
12 #include "base/json/json_writer.h"
13 #include "base/profiler/scoped_tracker.h"
14 #include "base/strings/string_split.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/values.h"
18 #include "google_apis/gaia/gaia_auth_consumer.h"
19 #include "google_apis/gaia/gaia_constants.h"
20 #include "google_apis/gaia/gaia_urls.h"
21 #include "google_apis/gaia/google_service_auth_error.h"
22 #include "net/base/escape.h"
23 #include "net/base/load_flags.h"
24 #include "net/http/http_response_headers.h"
25 #include "net/http/http_status_code.h"
26 #include "net/url_request/url_fetcher.h"
27 #include "net/url_request/url_request_context_getter.h"
28 #include "net/url_request/url_request_status.h"
30 namespace {
31 const int kLoadFlagsIgnoreCookies = net::LOAD_DO_NOT_SEND_COOKIES |
32 net::LOAD_DO_NOT_SAVE_COOKIES;
34 static bool CookiePartsContains(const std::vector<std::string>& parts,
35 const char* part) {
36 for (std::vector<std::string>::const_iterator it = parts.begin();
37 it != parts.end(); ++it) {
38 if (LowerCaseEqualsASCII(*it, part))
39 return true;
41 return false;
44 bool ExtractOAuth2TokenPairResponse(base::DictionaryValue* dict,
45 std::string* refresh_token,
46 std::string* access_token,
47 int* expires_in_secs) {
48 DCHECK(refresh_token);
49 DCHECK(access_token);
50 DCHECK(expires_in_secs);
52 if (!dict->GetStringWithoutPathExpansion("refresh_token", refresh_token) ||
53 !dict->GetStringWithoutPathExpansion("access_token", access_token) ||
54 !dict->GetIntegerWithoutPathExpansion("expires_in", expires_in_secs)) {
55 return false;
58 return true;
61 } // namespace
63 // TODO(chron): Add sourceless version of this formatter.
64 // static
65 const char GaiaAuthFetcher::kClientLoginFormat[] =
66 "Email=%s&"
67 "Passwd=%s&"
68 "PersistentCookie=%s&"
69 "accountType=%s&"
70 "source=%s&"
71 "service=%s";
72 // static
73 const char GaiaAuthFetcher::kClientLoginCaptchaFormat[] =
74 "Email=%s&"
75 "Passwd=%s&"
76 "PersistentCookie=%s&"
77 "accountType=%s&"
78 "source=%s&"
79 "service=%s&"
80 "logintoken=%s&"
81 "logincaptcha=%s";
82 // static
83 const char GaiaAuthFetcher::kIssueAuthTokenFormat[] =
84 "SID=%s&"
85 "LSID=%s&"
86 "service=%s&"
87 "Session=%s";
88 // static
89 const char GaiaAuthFetcher::kClientLoginToOAuth2BodyFormat[] =
90 "scope=%s&client_id=%s";
91 // static
92 const char GaiaAuthFetcher::kClientLoginToOAuth2WithDeviceTypeBodyFormat[] =
93 "scope=%s&client_id=%s&device_type=chrome";
94 // static
95 const char GaiaAuthFetcher::kOAuth2CodeToTokenPairBodyFormat[] =
96 "scope=%s&"
97 "grant_type=authorization_code&"
98 "client_id=%s&"
99 "client_secret=%s&"
100 "code=%s";
101 // static
102 const char GaiaAuthFetcher::kOAuth2RevokeTokenBodyFormat[] =
103 "token=%s";
104 // static
105 const char GaiaAuthFetcher::kGetUserInfoFormat[] =
106 "LSID=%s";
107 // static
108 const char GaiaAuthFetcher::kMergeSessionFormat[] =
109 "uberauth=%s&"
110 "continue=%s&"
111 "source=%s";
112 // static
113 const char GaiaAuthFetcher::kUberAuthTokenURLFormat[] =
114 "?source=%s&"
115 "issueuberauth=1";
117 const char GaiaAuthFetcher::kOAuthLoginFormat[] = "service=%s&source=%s";
119 // static
120 const char GaiaAuthFetcher::kAccountDeletedError[] = "AccountDeleted";
121 // static
122 const char GaiaAuthFetcher::kAccountDisabledError[] = "AccountDisabled";
123 // static
124 const char GaiaAuthFetcher::kBadAuthenticationError[] = "BadAuthentication";
125 // static
126 const char GaiaAuthFetcher::kCaptchaError[] = "CaptchaRequired";
127 // static
128 const char GaiaAuthFetcher::kServiceUnavailableError[] =
129 "ServiceUnavailable";
130 // static
131 const char GaiaAuthFetcher::kErrorParam[] = "Error";
132 // static
133 const char GaiaAuthFetcher::kErrorUrlParam[] = "Url";
134 // static
135 const char GaiaAuthFetcher::kCaptchaUrlParam[] = "CaptchaUrl";
136 // static
137 const char GaiaAuthFetcher::kCaptchaTokenParam[] = "CaptchaToken";
139 // static
140 const char GaiaAuthFetcher::kCookiePersistence[] = "true";
141 // static
142 // TODO(johnnyg): When hosted accounts are supported by sync,
143 // we can always use "HOSTED_OR_GOOGLE"
144 const char GaiaAuthFetcher::kAccountTypeHostedOrGoogle[] =
145 "HOSTED_OR_GOOGLE";
146 const char GaiaAuthFetcher::kAccountTypeGoogle[] =
147 "GOOGLE";
149 // static
150 const char GaiaAuthFetcher::kSecondFactor[] = "Info=InvalidSecondFactor";
151 // static
152 const char GaiaAuthFetcher::kWebLoginRequired[] = "Info=WebLoginRequired";
154 // static
155 const char GaiaAuthFetcher::kAuthHeaderFormat[] =
156 "Authorization: GoogleLogin auth=%s";
157 // static
158 const char GaiaAuthFetcher::kOAuthHeaderFormat[] = "Authorization: OAuth %s";
159 // static
160 const char GaiaAuthFetcher::kOAuth2BearerHeaderFormat[] =
161 "Authorization: Bearer %s";
162 // static
163 const char GaiaAuthFetcher::kDeviceIdHeaderFormat[] = "X-Device-ID: %s";
164 // static
165 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartSecure[] = "secure";
166 // static
167 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartHttpOnly[] =
168 "httponly";
169 // static
170 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefix[] =
171 "oauth_code=";
172 // static
173 const int GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefixLength =
174 arraysize(GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefix) - 1;
176 GaiaAuthFetcher::GaiaAuthFetcher(GaiaAuthConsumer* consumer,
177 const std::string& source,
178 net::URLRequestContextGetter* getter)
179 : consumer_(consumer),
180 getter_(getter),
181 source_(source),
182 client_login_gurl_(GaiaUrls::GetInstance()->client_login_url()),
183 issue_auth_token_gurl_(GaiaUrls::GetInstance()->issue_auth_token_url()),
184 oauth2_token_gurl_(GaiaUrls::GetInstance()->oauth2_token_url()),
185 oauth2_revoke_gurl_(GaiaUrls::GetInstance()->oauth2_revoke_url()),
186 get_user_info_gurl_(GaiaUrls::GetInstance()->get_user_info_url()),
187 merge_session_gurl_(GaiaUrls::GetInstance()->merge_session_url()),
188 uberauth_token_gurl_(GaiaUrls::GetInstance()->oauth1_login_url().Resolve(
189 base::StringPrintf(kUberAuthTokenURLFormat, source.c_str()))),
190 oauth_login_gurl_(GaiaUrls::GetInstance()->oauth1_login_url()),
191 list_accounts_gurl_(
192 GaiaUrls::GetInstance()->ListAccountsURLWithSource(source)),
193 get_check_connection_info_url_(
194 GaiaUrls::GetInstance()->GetCheckConnectionInfoURLWithSource(source)),
195 client_login_to_oauth2_gurl_(
196 GaiaUrls::GetInstance()->client_login_to_oauth2_url()),
197 fetch_pending_(false) {}
199 GaiaAuthFetcher::~GaiaAuthFetcher() {}
201 bool GaiaAuthFetcher::HasPendingFetch() {
202 return fetch_pending_;
205 void GaiaAuthFetcher::CancelRequest() {
206 fetcher_.reset();
207 fetch_pending_ = false;
210 // static
211 net::URLFetcher* GaiaAuthFetcher::CreateGaiaFetcher(
212 net::URLRequestContextGetter* getter,
213 const std::string& body,
214 const std::string& headers,
215 const GURL& gaia_gurl,
216 int load_flags,
217 net::URLFetcherDelegate* delegate) {
218 net::URLFetcher* to_return = net::URLFetcher::Create(
219 0, gaia_gurl,
220 body.empty() ? net::URLFetcher::GET : net::URLFetcher::POST,
221 delegate);
222 to_return->SetRequestContext(getter);
223 to_return->SetUploadData("application/x-www-form-urlencoded", body);
225 DVLOG(2) << "Gaia fetcher URL: " << gaia_gurl.spec();
226 DVLOG(2) << "Gaia fetcher headers: " << headers;
227 DVLOG(2) << "Gaia fetcher body: " << body;
229 // The Gaia token exchange requests do not require any cookie-based
230 // identification as part of requests. We suppress sending any cookies to
231 // maintain a separation between the user's browsing and Chrome's internal
232 // services. Where such mixing is desired (MergeSession or OAuthLogin), it
233 // will be done explicitly.
234 to_return->SetLoadFlags(load_flags);
236 // Fetchers are sometimes cancelled because a network change was detected,
237 // especially at startup and after sign-in on ChromeOS. Retrying once should
238 // be enough in those cases; let the fetcher retry up to 3 times just in case.
239 // http://crbug.com/163710
240 to_return->SetAutomaticallyRetryOnNetworkChanges(3);
242 if (!headers.empty())
243 to_return->SetExtraRequestHeaders(headers);
245 return to_return;
248 // static
249 std::string GaiaAuthFetcher::MakeClientLoginBody(
250 const std::string& username,
251 const std::string& password,
252 const std::string& source,
253 const char* service,
254 const std::string& login_token,
255 const std::string& login_captcha,
256 HostedAccountsSetting allow_hosted_accounts) {
257 std::string encoded_username = net::EscapeUrlEncodedData(username, true);
258 std::string encoded_password = net::EscapeUrlEncodedData(password, true);
259 std::string encoded_login_token = net::EscapeUrlEncodedData(login_token,
260 true);
261 std::string encoded_login_captcha = net::EscapeUrlEncodedData(login_captcha,
262 true);
264 const char* account_type = allow_hosted_accounts == HostedAccountsAllowed ?
265 kAccountTypeHostedOrGoogle :
266 kAccountTypeGoogle;
268 if (login_token.empty() || login_captcha.empty()) {
269 return base::StringPrintf(kClientLoginFormat,
270 encoded_username.c_str(),
271 encoded_password.c_str(),
272 kCookiePersistence,
273 account_type,
274 source.c_str(),
275 service);
278 return base::StringPrintf(kClientLoginCaptchaFormat,
279 encoded_username.c_str(),
280 encoded_password.c_str(),
281 kCookiePersistence,
282 account_type,
283 source.c_str(),
284 service,
285 encoded_login_token.c_str(),
286 encoded_login_captcha.c_str());
289 // static
290 std::string GaiaAuthFetcher::MakeIssueAuthTokenBody(
291 const std::string& sid,
292 const std::string& lsid,
293 const char* const service) {
294 std::string encoded_sid = net::EscapeUrlEncodedData(sid, true);
295 std::string encoded_lsid = net::EscapeUrlEncodedData(lsid, true);
297 // All tokens should be session tokens except the gaia auth token.
298 bool session = true;
299 if (!strcmp(service, GaiaConstants::kGaiaService))
300 session = false;
302 return base::StringPrintf(kIssueAuthTokenFormat,
303 encoded_sid.c_str(),
304 encoded_lsid.c_str(),
305 service,
306 session ? "true" : "false");
309 // static
310 std::string GaiaAuthFetcher::MakeGetAuthCodeBody(bool include_device_type) {
311 std::string encoded_scope = net::EscapeUrlEncodedData(
312 GaiaConstants::kOAuth1LoginScope, true);
313 std::string encoded_client_id = net::EscapeUrlEncodedData(
314 GaiaUrls::GetInstance()->oauth2_chrome_client_id(), true);
315 if (include_device_type) {
316 return base::StringPrintf(kClientLoginToOAuth2WithDeviceTypeBodyFormat,
317 encoded_scope.c_str(),
318 encoded_client_id.c_str());
319 } else {
320 return base::StringPrintf(kClientLoginToOAuth2BodyFormat,
321 encoded_scope.c_str(),
322 encoded_client_id.c_str());
326 // static
327 std::string GaiaAuthFetcher::MakeGetTokenPairBody(
328 const std::string& auth_code) {
329 std::string encoded_scope = net::EscapeUrlEncodedData(
330 GaiaConstants::kOAuth1LoginScope, true);
331 std::string encoded_client_id = net::EscapeUrlEncodedData(
332 GaiaUrls::GetInstance()->oauth2_chrome_client_id(), true);
333 std::string encoded_client_secret = net::EscapeUrlEncodedData(
334 GaiaUrls::GetInstance()->oauth2_chrome_client_secret(), true);
335 std::string encoded_auth_code = net::EscapeUrlEncodedData(auth_code, true);
336 return base::StringPrintf(kOAuth2CodeToTokenPairBodyFormat,
337 encoded_scope.c_str(),
338 encoded_client_id.c_str(),
339 encoded_client_secret.c_str(),
340 encoded_auth_code.c_str());
343 // static
344 std::string GaiaAuthFetcher::MakeRevokeTokenBody(
345 const std::string& auth_token) {
346 return base::StringPrintf(kOAuth2RevokeTokenBodyFormat, auth_token.c_str());
349 // static
350 std::string GaiaAuthFetcher::MakeGetUserInfoBody(const std::string& lsid) {
351 std::string encoded_lsid = net::EscapeUrlEncodedData(lsid, true);
352 return base::StringPrintf(kGetUserInfoFormat, encoded_lsid.c_str());
355 // static
356 std::string GaiaAuthFetcher::MakeMergeSessionBody(
357 const std::string& auth_token,
358 const std::string& external_cc_result,
359 const std::string& continue_url,
360 const std::string& source) {
361 std::string encoded_auth_token = net::EscapeUrlEncodedData(auth_token, true);
362 std::string encoded_continue_url = net::EscapeUrlEncodedData(continue_url,
363 true);
364 std::string encoded_source = net::EscapeUrlEncodedData(source, true);
365 std::string result = base::StringPrintf(kMergeSessionFormat,
366 encoded_auth_token.c_str(),
367 encoded_continue_url.c_str(),
368 encoded_source.c_str());
369 if (!external_cc_result.empty()) {
370 base::StringAppendF(&result, "&externalCcResult=%s",
371 net::EscapeUrlEncodedData(
372 external_cc_result, true).c_str());
375 return result;
378 // static
379 std::string GaiaAuthFetcher::MakeGetAuthCodeHeader(
380 const std::string& auth_token) {
381 return base::StringPrintf(kAuthHeaderFormat, auth_token.c_str());
384 // Helper method that extracts tokens from a successful reply.
385 // static
386 void GaiaAuthFetcher::ParseClientLoginResponse(const std::string& data,
387 std::string* sid,
388 std::string* lsid,
389 std::string* token) {
390 using std::vector;
391 using std::pair;
392 using std::string;
393 sid->clear();
394 lsid->clear();
395 token->clear();
396 vector<pair<string, string> > tokens;
397 base::SplitStringIntoKeyValuePairs(data, '=', '\n', &tokens);
398 for (vector<pair<string, string> >::iterator i = tokens.begin();
399 i != tokens.end(); ++i) {
400 if (i->first == "SID") {
401 sid->assign(i->second);
402 } else if (i->first == "LSID") {
403 lsid->assign(i->second);
404 } else if (i->first == "Auth") {
405 token->assign(i->second);
408 // If this was a request for uberauth token, then that's all we've got in
409 // data.
410 if (sid->empty() && lsid->empty() && token->empty())
411 token->assign(data);
414 // static
415 std::string GaiaAuthFetcher::MakeOAuthLoginBody(const std::string& service,
416 const std::string& source) {
417 std::string encoded_service = net::EscapeUrlEncodedData(service, true);
418 std::string encoded_source = net::EscapeUrlEncodedData(source, true);
419 return base::StringPrintf(kOAuthLoginFormat,
420 encoded_service.c_str(),
421 encoded_source.c_str());
424 // static
425 void GaiaAuthFetcher::ParseClientLoginFailure(const std::string& data,
426 std::string* error,
427 std::string* error_url,
428 std::string* captcha_url,
429 std::string* captcha_token) {
430 using std::vector;
431 using std::pair;
432 using std::string;
434 vector<pair<string, string> > tokens;
435 base::SplitStringIntoKeyValuePairs(data, '=', '\n', &tokens);
436 for (vector<pair<string, string> >::iterator i = tokens.begin();
437 i != tokens.end(); ++i) {
438 if (i->first == kErrorParam) {
439 error->assign(i->second);
440 } else if (i->first == kErrorUrlParam) {
441 error_url->assign(i->second);
442 } else if (i->first == kCaptchaUrlParam) {
443 captcha_url->assign(i->second);
444 } else if (i->first == kCaptchaTokenParam) {
445 captcha_token->assign(i->second);
450 // static
451 bool GaiaAuthFetcher::ParseClientLoginToOAuth2Response(
452 const net::ResponseCookies& cookies,
453 std::string* auth_code) {
454 DCHECK(auth_code);
455 net::ResponseCookies::const_iterator iter;
456 for (iter = cookies.begin(); iter != cookies.end(); ++iter) {
457 if (ParseClientLoginToOAuth2Cookie(*iter, auth_code))
458 return true;
460 return false;
463 // static
464 bool GaiaAuthFetcher::ParseClientLoginToOAuth2Cookie(const std::string& cookie,
465 std::string* auth_code) {
466 std::vector<std::string> parts;
467 base::SplitString(cookie, ';', &parts);
468 // Per documentation, the cookie should have Secure and HttpOnly.
469 if (!CookiePartsContains(parts, kClientLoginToOAuth2CookiePartSecure) ||
470 !CookiePartsContains(parts, kClientLoginToOAuth2CookiePartHttpOnly)) {
471 return false;
474 std::vector<std::string>::const_iterator iter;
475 for (iter = parts.begin(); iter != parts.end(); ++iter) {
476 const std::string& part = *iter;
477 if (StartsWithASCII(
478 part, kClientLoginToOAuth2CookiePartCodePrefix, false)) {
479 auth_code->assign(part.substr(
480 kClientLoginToOAuth2CookiePartCodePrefixLength));
481 return true;
484 return false;
487 void GaiaAuthFetcher::StartClientLogin(
488 const std::string& username,
489 const std::string& password,
490 const char* const service,
491 const std::string& login_token,
492 const std::string& login_captcha,
493 HostedAccountsSetting allow_hosted_accounts) {
495 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
497 // This class is thread agnostic, so be sure to call this only on the
498 // same thread each time.
499 DVLOG(1) << "Starting new ClientLogin fetch for:" << username;
501 // Must outlive fetcher_.
502 request_body_ = MakeClientLoginBody(username,
503 password,
504 source_,
505 service,
506 login_token,
507 login_captcha,
508 allow_hosted_accounts);
509 fetcher_.reset(CreateGaiaFetcher(getter_,
510 request_body_,
511 std::string(),
512 client_login_gurl_,
513 kLoadFlagsIgnoreCookies,
514 this));
515 fetch_pending_ = true;
516 fetcher_->Start();
519 void GaiaAuthFetcher::StartIssueAuthToken(const std::string& sid,
520 const std::string& lsid,
521 const char* const service) {
522 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
524 DVLOG(1) << "Starting IssueAuthToken for: " << service;
525 requested_service_ = service;
526 request_body_ = MakeIssueAuthTokenBody(sid, lsid, service);
527 fetcher_.reset(CreateGaiaFetcher(getter_,
528 request_body_,
529 std::string(),
530 issue_auth_token_gurl_,
531 kLoadFlagsIgnoreCookies,
532 this));
533 fetch_pending_ = true;
534 fetcher_->Start();
537 void GaiaAuthFetcher::StartLsoForOAuthLoginTokenExchange(
538 const std::string& auth_token) {
539 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
541 DVLOG(1) << "Starting OAuth login token exchange with auth_token";
542 request_body_ = MakeGetAuthCodeBody(false);
543 client_login_to_oauth2_gurl_ =
544 GaiaUrls::GetInstance()->client_login_to_oauth2_url();
546 fetcher_.reset(CreateGaiaFetcher(getter_,
547 request_body_,
548 MakeGetAuthCodeHeader(auth_token),
549 client_login_to_oauth2_gurl_,
550 kLoadFlagsIgnoreCookies,
551 this));
552 fetch_pending_ = true;
553 fetcher_->Start();
556 void GaiaAuthFetcher::StartRevokeOAuth2Token(const std::string& auth_token) {
557 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
559 DVLOG(1) << "Starting OAuth2 token revocation";
560 request_body_ = MakeRevokeTokenBody(auth_token);
561 fetcher_.reset(CreateGaiaFetcher(getter_,
562 request_body_,
563 std::string(),
564 oauth2_revoke_gurl_,
565 kLoadFlagsIgnoreCookies,
566 this));
567 fetch_pending_ = true;
568 fetcher_->Start();
571 void GaiaAuthFetcher::StartCookieForOAuthLoginTokenExchange(
572 const std::string& session_index) {
573 StartCookieForOAuthLoginTokenExchangeWithDeviceId(session_index,
574 std::string());
577 void GaiaAuthFetcher::StartCookieForOAuthLoginTokenExchangeWithDeviceId(
578 const std::string& session_index,
579 const std::string& device_id) {
580 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
582 DVLOG(1) << "Starting OAuth login token fetch with cookie jar";
583 request_body_ = MakeGetAuthCodeBody(!device_id.empty());
585 client_login_to_oauth2_gurl_ =
586 GaiaUrls::GetInstance()->client_login_to_oauth2_url();
587 if (!session_index.empty()) {
588 client_login_to_oauth2_gurl_ =
589 client_login_to_oauth2_gurl_.Resolve("?authuser=" + session_index);
592 std::string device_id_header;
593 if (!device_id.empty()) {
594 device_id_header =
595 base::StringPrintf(kDeviceIdHeaderFormat, device_id.c_str());
598 fetcher_.reset(CreateGaiaFetcher(getter_,
599 request_body_,
600 device_id_header,
601 client_login_to_oauth2_gurl_,
602 net::LOAD_NORMAL,
603 this));
604 fetch_pending_ = true;
605 fetcher_->Start();
608 void GaiaAuthFetcher::StartAuthCodeForOAuth2TokenExchange(
609 const std::string& auth_code) {
610 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
612 DVLOG(1) << "Starting OAuth token pair fetch";
613 request_body_ = MakeGetTokenPairBody(auth_code);
614 fetcher_.reset(CreateGaiaFetcher(getter_,
615 request_body_,
616 std::string(),
617 oauth2_token_gurl_,
618 kLoadFlagsIgnoreCookies,
619 this));
620 fetch_pending_ = true;
621 fetcher_->Start();
624 void GaiaAuthFetcher::StartGetUserInfo(const std::string& lsid) {
625 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
627 DVLOG(1) << "Starting GetUserInfo for lsid=" << lsid;
628 request_body_ = MakeGetUserInfoBody(lsid);
629 fetcher_.reset(CreateGaiaFetcher(getter_,
630 request_body_,
631 std::string(),
632 get_user_info_gurl_,
633 kLoadFlagsIgnoreCookies,
634 this));
635 fetch_pending_ = true;
636 fetcher_->Start();
639 void GaiaAuthFetcher::StartMergeSession(const std::string& uber_token,
640 const std::string& external_cc_result) {
641 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
643 DVLOG(1) << "Starting MergeSession with uber_token=" << uber_token;
645 // The continue URL is a required parameter of the MergeSession API, but in
646 // this case we don't actually need or want to navigate to it. Setting it to
647 // an arbitrary Google URL.
649 // In order for the new session to be merged correctly, the server needs to
650 // know what sessions already exist in the browser. The fetcher needs to be
651 // created such that it sends the cookies with the request, which is
652 // different from all other requests the fetcher can make.
653 std::string continue_url("http://www.google.com");
654 request_body_ = MakeMergeSessionBody(uber_token, external_cc_result,
655 continue_url, source_);
656 fetcher_.reset(CreateGaiaFetcher(getter_,
657 request_body_,
658 std::string(),
659 merge_session_gurl_,
660 net::LOAD_NORMAL,
661 this));
662 fetch_pending_ = true;
663 fetcher_->Start();
666 void GaiaAuthFetcher::StartTokenFetchForUberAuthExchange(
667 const std::string& access_token) {
668 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
670 DVLOG(1) << "Starting StartTokenFetchForUberAuthExchange with access_token="
671 << access_token;
672 std::string authentication_header =
673 base::StringPrintf(kOAuthHeaderFormat, access_token.c_str());
674 fetcher_.reset(CreateGaiaFetcher(getter_,
675 std::string(),
676 authentication_header,
677 uberauth_token_gurl_,
678 net::LOAD_NORMAL,
679 this));
680 fetch_pending_ = true;
681 fetcher_->Start();
684 void GaiaAuthFetcher::StartOAuthLogin(const std::string& access_token,
685 const std::string& service) {
686 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
688 request_body_ = MakeOAuthLoginBody(service, source_);
689 std::string authentication_header =
690 base::StringPrintf(kOAuth2BearerHeaderFormat, access_token.c_str());
691 fetcher_.reset(CreateGaiaFetcher(getter_,
692 request_body_,
693 authentication_header,
694 oauth_login_gurl_,
695 net::LOAD_NORMAL,
696 this));
697 fetch_pending_ = true;
698 fetcher_->Start();
701 void GaiaAuthFetcher::StartListAccounts() {
702 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
704 fetcher_.reset(CreateGaiaFetcher(getter_,
705 " ", // To force an HTTP POST.
706 "Origin: https://www.google.com",
707 list_accounts_gurl_,
708 net::LOAD_NORMAL,
709 this));
710 fetch_pending_ = true;
711 fetcher_->Start();
714 void GaiaAuthFetcher::StartGetCheckConnectionInfo() {
715 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
717 fetcher_.reset(CreateGaiaFetcher(getter_,
718 std::string(),
719 std::string(),
720 get_check_connection_info_url_,
721 kLoadFlagsIgnoreCookies,
722 this));
723 fetch_pending_ = true;
724 fetcher_->Start();
727 // static
728 GoogleServiceAuthError GaiaAuthFetcher::GenerateAuthError(
729 const std::string& data,
730 const net::URLRequestStatus& status) {
731 if (!status.is_success()) {
732 if (status.status() == net::URLRequestStatus::CANCELED) {
733 return GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED);
735 DLOG(WARNING) << "Could not reach Google Accounts servers: errno "
736 << status.error();
737 return GoogleServiceAuthError::FromConnectionError(status.error());
740 if (IsSecondFactorSuccess(data))
741 return GoogleServiceAuthError(GoogleServiceAuthError::TWO_FACTOR);
743 if (IsWebLoginRequiredSuccess(data))
744 return GoogleServiceAuthError(GoogleServiceAuthError::WEB_LOGIN_REQUIRED);
746 std::string error;
747 std::string url;
748 std::string captcha_url;
749 std::string captcha_token;
750 ParseClientLoginFailure(data, &error, &url, &captcha_url, &captcha_token);
751 DLOG(WARNING) << "ClientLogin failed with " << error;
753 if (error == kCaptchaError) {
754 return GoogleServiceAuthError::FromClientLoginCaptchaChallenge(
755 captcha_token,
756 GURL(GaiaUrls::GetInstance()->captcha_base_url().Resolve(captcha_url)),
757 GURL(url));
759 if (error == kAccountDeletedError)
760 return GoogleServiceAuthError(GoogleServiceAuthError::ACCOUNT_DELETED);
761 if (error == kAccountDisabledError)
762 return GoogleServiceAuthError(GoogleServiceAuthError::ACCOUNT_DISABLED);
763 if (error == kBadAuthenticationError) {
764 return GoogleServiceAuthError(
765 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
767 if (error == kServiceUnavailableError) {
768 return GoogleServiceAuthError(
769 GoogleServiceAuthError::SERVICE_UNAVAILABLE);
772 DLOG(WARNING) << "Incomprehensible response from Google Accounts servers.";
773 return GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_UNAVAILABLE);
776 void GaiaAuthFetcher::OnClientLoginFetched(const std::string& data,
777 const net::URLRequestStatus& status,
778 int response_code) {
779 if (status.is_success() && response_code == net::HTTP_OK) {
780 DVLOG(1) << "ClientLogin successful!";
781 std::string sid;
782 std::string lsid;
783 std::string token;
784 ParseClientLoginResponse(data, &sid, &lsid, &token);
785 consumer_->OnClientLoginSuccess(
786 GaiaAuthConsumer::ClientLoginResult(sid, lsid, token, data));
787 } else {
788 consumer_->OnClientLoginFailure(GenerateAuthError(data, status));
792 void GaiaAuthFetcher::OnIssueAuthTokenFetched(
793 const std::string& data,
794 const net::URLRequestStatus& status,
795 int response_code) {
796 if (status.is_success() && response_code == net::HTTP_OK) {
797 // Only the bare token is returned in the body of this Gaia call
798 // without any padding.
799 consumer_->OnIssueAuthTokenSuccess(requested_service_, data);
800 } else {
801 consumer_->OnIssueAuthTokenFailure(requested_service_,
802 GenerateAuthError(data, status));
806 void GaiaAuthFetcher::OnClientLoginToOAuth2Fetched(
807 const std::string& data,
808 const net::ResponseCookies& cookies,
809 const net::URLRequestStatus& status,
810 int response_code) {
811 if (status.is_success() && response_code == net::HTTP_OK) {
812 std::string auth_code;
813 if (ParseClientLoginToOAuth2Response(cookies, &auth_code)) {
814 StartAuthCodeForOAuth2TokenExchange(auth_code);
815 } else {
816 GoogleServiceAuthError auth_error(
817 GoogleServiceAuthError::FromUnexpectedServiceResponse(
818 "ClientLogin response cookies didn't contain an auth code"));
819 consumer_->OnClientOAuthFailure(auth_error);
821 } else {
822 GoogleServiceAuthError auth_error(GenerateAuthError(data, status));
823 consumer_->OnClientOAuthFailure(auth_error);
827 void GaiaAuthFetcher::OnOAuth2TokenPairFetched(
828 const std::string& data,
829 const net::URLRequestStatus& status,
830 int response_code) {
831 std::string refresh_token;
832 std::string access_token;
833 int expires_in_secs = 0;
835 bool success = false;
836 if (status.is_success() && response_code == net::HTTP_OK) {
837 scoped_ptr<base::Value> value(base::JSONReader::Read(data));
838 if (value.get() && value->GetType() == base::Value::TYPE_DICTIONARY) {
839 base::DictionaryValue* dict =
840 static_cast<base::DictionaryValue*>(value.get());
841 success = ExtractOAuth2TokenPairResponse(dict, &refresh_token,
842 &access_token, &expires_in_secs);
846 if (success) {
847 consumer_->OnClientOAuthSuccess(
848 GaiaAuthConsumer::ClientOAuthResult(refresh_token, access_token,
849 expires_in_secs));
850 } else {
851 consumer_->OnClientOAuthFailure(GenerateAuthError(data, status));
855 void GaiaAuthFetcher::OnOAuth2RevokeTokenFetched(
856 const std::string& data,
857 const net::URLRequestStatus& status,
858 int response_code) {
859 consumer_->OnOAuth2RevokeTokenCompleted();
862 void GaiaAuthFetcher::OnListAccountsFetched(const std::string& data,
863 const net::URLRequestStatus& status,
864 int response_code) {
865 if (status.is_success() && response_code == net::HTTP_OK) {
866 consumer_->OnListAccountsSuccess(data);
867 } else {
868 consumer_->OnListAccountsFailure(GenerateAuthError(data, status));
872 void GaiaAuthFetcher::OnGetUserInfoFetched(
873 const std::string& data,
874 const net::URLRequestStatus& status,
875 int response_code) {
876 if (status.is_success() && response_code == net::HTTP_OK) {
877 base::StringPairs tokens;
878 UserInfoMap matches;
879 base::SplitStringIntoKeyValuePairs(data, '=', '\n', &tokens);
880 base::StringPairs::iterator i;
881 for (i = tokens.begin(); i != tokens.end(); ++i) {
882 matches[i->first] = i->second;
884 consumer_->OnGetUserInfoSuccess(matches);
885 } else {
886 consumer_->OnGetUserInfoFailure(GenerateAuthError(data, status));
890 void GaiaAuthFetcher::OnMergeSessionFetched(const std::string& data,
891 const net::URLRequestStatus& status,
892 int response_code) {
893 if (status.is_success() && response_code == net::HTTP_OK) {
894 consumer_->OnMergeSessionSuccess(data);
895 } else {
896 consumer_->OnMergeSessionFailure(GenerateAuthError(data, status));
900 void GaiaAuthFetcher::OnUberAuthTokenFetch(const std::string& data,
901 const net::URLRequestStatus& status,
902 int response_code) {
903 if (status.is_success() && response_code == net::HTTP_OK) {
904 consumer_->OnUberAuthTokenSuccess(data);
905 } else {
906 consumer_->OnUberAuthTokenFailure(GenerateAuthError(data, status));
910 void GaiaAuthFetcher::OnOAuthLoginFetched(const std::string& data,
911 const net::URLRequestStatus& status,
912 int response_code) {
913 if (status.is_success() && response_code == net::HTTP_OK) {
914 DVLOG(1) << "ClientLogin successful!";
915 std::string sid;
916 std::string lsid;
917 std::string token;
918 ParseClientLoginResponse(data, &sid, &lsid, &token);
919 consumer_->OnClientLoginSuccess(
920 GaiaAuthConsumer::ClientLoginResult(sid, lsid, token, data));
921 } else {
922 consumer_->OnClientLoginFailure(GenerateAuthError(data, status));
926 void GaiaAuthFetcher::OnGetCheckConnectionInfoFetched(
927 const std::string& data,
928 const net::URLRequestStatus& status,
929 int response_code) {
930 if (status.is_success() && response_code == net::HTTP_OK) {
931 consumer_->OnGetCheckConnectionInfoSuccess(data);
932 } else {
933 consumer_->OnGetCheckConnectionInfoError(GenerateAuthError(data, status));
937 void GaiaAuthFetcher::OnURLFetchComplete(const net::URLFetcher* source) {
938 fetch_pending_ = false;
939 // Some of the GAIA requests perform redirects, which results in the final
940 // URL of the fetcher not being the original URL requested. Therefore use
941 // the original URL when determining which OnXXX function to call.
942 const GURL& url = source->GetOriginalURL();
943 const net::URLRequestStatus& status = source->GetStatus();
944 int response_code = source->GetResponseCode();
945 std::string data;
946 source->GetResponseAsString(&data);
947 #ifndef NDEBUG
948 std::string headers;
949 if (source->GetResponseHeaders())
950 source->GetResponseHeaders()->GetNormalizedHeaders(&headers);
951 DVLOG(2) << "Response " << url.spec() << ", code = " << response_code << "\n"
952 << headers << "\n";
953 DVLOG(2) << "data: " << data << "\n";
954 #endif
955 // Retrieve the response headers from the request. Must only be called after
956 // the OnURLFetchComplete callback has run.
957 if (url == client_login_gurl_) {
958 OnClientLoginFetched(data, status, response_code);
959 } else if (url == issue_auth_token_gurl_) {
960 OnIssueAuthTokenFetched(data, status, response_code);
961 } else if (url == client_login_to_oauth2_gurl_) {
962 OnClientLoginToOAuth2Fetched(
963 data, source->GetCookies(), status, response_code);
964 } else if (url == oauth2_token_gurl_) {
965 OnOAuth2TokenPairFetched(data, status, response_code);
966 } else if (url == get_user_info_gurl_) {
967 OnGetUserInfoFetched(data, status, response_code);
968 } else if (url == merge_session_gurl_) {
969 OnMergeSessionFetched(data, status, response_code);
970 } else if (url == uberauth_token_gurl_) {
971 OnUberAuthTokenFetch(data, status, response_code);
972 } else if (url == oauth_login_gurl_) {
973 OnOAuthLoginFetched(data, status, response_code);
974 } else if (url == oauth2_revoke_gurl_) {
975 OnOAuth2RevokeTokenFetched(data, status, response_code);
976 } else if (url == list_accounts_gurl_) {
977 OnListAccountsFetched(data, status, response_code);
978 } else if (url == get_check_connection_info_url_) {
979 OnGetCheckConnectionInfoFetched(data, status, response_code);
980 } else {
981 NOTREACHED();
985 // static
986 bool GaiaAuthFetcher::IsSecondFactorSuccess(
987 const std::string& alleged_error) {
988 return alleged_error.find(kSecondFactor) !=
989 std::string::npos;
992 // static
993 bool GaiaAuthFetcher::IsWebLoginRequiredSuccess(
994 const std::string& alleged_error) {
995 return alleged_error.find(kWebLoginRequired) !=
996 std::string::npos;