If a RemoteFrame asks to navigate, send an OpenURL IPC
[chromium-blink-merge.git] / google_apis / gaia / gaia_auth_fetcher.cc
blob194f591d5467080b945d1bdf130eb1401ca49061
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/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"
29 namespace {
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,
34 const char* part) {
35 for (std::vector<std::string>::const_iterator it = parts.begin();
36 it != parts.end(); ++it) {
37 if (LowerCaseEqualsASCII(*it, part))
38 return true;
40 return false;
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);
48 DCHECK(access_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)) {
54 return false;
57 return true;
60 } // namespace
62 // TODO(chron): Add sourceless version of this formatter.
63 // static
64 const char GaiaAuthFetcher::kClientLoginFormat[] =
65 "Email=%s&"
66 "Passwd=%s&"
67 "PersistentCookie=%s&"
68 "accountType=%s&"
69 "source=%s&"
70 "service=%s";
71 // static
72 const char GaiaAuthFetcher::kClientLoginCaptchaFormat[] =
73 "Email=%s&"
74 "Passwd=%s&"
75 "PersistentCookie=%s&"
76 "accountType=%s&"
77 "source=%s&"
78 "service=%s&"
79 "logintoken=%s&"
80 "logincaptcha=%s";
81 // static
82 const char GaiaAuthFetcher::kIssueAuthTokenFormat[] =
83 "SID=%s&"
84 "LSID=%s&"
85 "service=%s&"
86 "Session=%s";
87 // static
88 const char GaiaAuthFetcher::kClientLoginToOAuth2BodyFormat[] =
89 "scope=%s&client_id=%s";
90 // static
91 const char GaiaAuthFetcher::kClientLoginToOAuth2WithDeviceTypeBodyFormat[] =
92 "scope=%s&client_id=%s&device_type=chrome";
93 // static
94 const char GaiaAuthFetcher::kOAuth2CodeToTokenPairBodyFormat[] =
95 "scope=%s&"
96 "grant_type=authorization_code&"
97 "client_id=%s&"
98 "client_secret=%s&"
99 "code=%s";
100 // static
101 const char GaiaAuthFetcher::kOAuth2RevokeTokenBodyFormat[] =
102 "token=%s";
103 // static
104 const char GaiaAuthFetcher::kGetUserInfoFormat[] =
105 "LSID=%s";
106 // static
107 const char GaiaAuthFetcher::kMergeSessionFormat[] =
108 "uberauth=%s&"
109 "continue=%s&"
110 "source=%s";
111 // static
112 const char GaiaAuthFetcher::kUberAuthTokenURLFormat[] =
113 "?source=%s&"
114 "issueuberauth=1";
116 const char GaiaAuthFetcher::kOAuthLoginFormat[] = "service=%s&source=%s";
118 // static
119 const char GaiaAuthFetcher::kAccountDeletedError[] = "AccountDeleted";
120 // static
121 const char GaiaAuthFetcher::kAccountDisabledError[] = "AccountDisabled";
122 // static
123 const char GaiaAuthFetcher::kBadAuthenticationError[] = "BadAuthentication";
124 // static
125 const char GaiaAuthFetcher::kCaptchaError[] = "CaptchaRequired";
126 // static
127 const char GaiaAuthFetcher::kServiceUnavailableError[] =
128 "ServiceUnavailable";
129 // static
130 const char GaiaAuthFetcher::kErrorParam[] = "Error";
131 // static
132 const char GaiaAuthFetcher::kErrorUrlParam[] = "Url";
133 // static
134 const char GaiaAuthFetcher::kCaptchaUrlParam[] = "CaptchaUrl";
135 // static
136 const char GaiaAuthFetcher::kCaptchaTokenParam[] = "CaptchaToken";
138 // static
139 const char GaiaAuthFetcher::kCookiePersistence[] = "true";
140 // static
141 // TODO(johnnyg): When hosted accounts are supported by sync,
142 // we can always use "HOSTED_OR_GOOGLE"
143 const char GaiaAuthFetcher::kAccountTypeHostedOrGoogle[] =
144 "HOSTED_OR_GOOGLE";
145 const char GaiaAuthFetcher::kAccountTypeGoogle[] =
146 "GOOGLE";
148 // static
149 const char GaiaAuthFetcher::kSecondFactor[] = "Info=InvalidSecondFactor";
151 // static
152 const char GaiaAuthFetcher::kAuthHeaderFormat[] =
153 "Authorization: GoogleLogin auth=%s";
154 // static
155 const char GaiaAuthFetcher::kOAuthHeaderFormat[] = "Authorization: OAuth %s";
156 // static
157 const char GaiaAuthFetcher::kOAuth2BearerHeaderFormat[] =
158 "Authorization: Bearer %s";
159 // static
160 const char GaiaAuthFetcher::kDeviceIdHeaderFormat[] = "X-Device-ID: %s";
161 // static
162 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartSecure[] = "secure";
163 // static
164 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartHttpOnly[] =
165 "httponly";
166 // static
167 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefix[] =
168 "oauth_code=";
169 // static
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),
177 getter_(getter),
178 source_(source),
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()),
188 list_accounts_gurl_(
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() {
203 fetcher_.reset();
204 fetch_pending_ = false;
207 // static
208 net::URLFetcher* GaiaAuthFetcher::CreateGaiaFetcher(
209 net::URLRequestContextGetter* getter,
210 const std::string& body,
211 const std::string& headers,
212 const GURL& gaia_gurl,
213 int load_flags,
214 net::URLFetcherDelegate* delegate) {
215 net::URLFetcher* to_return = net::URLFetcher::Create(
216 0, gaia_gurl,
217 body == "" ? net::URLFetcher::GET : net::URLFetcher::POST,
218 delegate);
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);
242 return to_return;
245 // static
246 std::string GaiaAuthFetcher::MakeClientLoginBody(
247 const std::string& username,
248 const std::string& password,
249 const std::string& source,
250 const char* service,
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,
257 true);
258 std::string encoded_login_captcha = net::EscapeUrlEncodedData(login_captcha,
259 true);
261 const char* account_type = allow_hosted_accounts == HostedAccountsAllowed ?
262 kAccountTypeHostedOrGoogle :
263 kAccountTypeGoogle;
265 if (login_token.empty() || login_captcha.empty()) {
266 return base::StringPrintf(kClientLoginFormat,
267 encoded_username.c_str(),
268 encoded_password.c_str(),
269 kCookiePersistence,
270 account_type,
271 source.c_str(),
272 service);
275 return base::StringPrintf(kClientLoginCaptchaFormat,
276 encoded_username.c_str(),
277 encoded_password.c_str(),
278 kCookiePersistence,
279 account_type,
280 source.c_str(),
281 service,
282 encoded_login_token.c_str(),
283 encoded_login_captcha.c_str());
286 // static
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.
295 bool session = true;
296 if (!strcmp(service, GaiaConstants::kGaiaService))
297 session = false;
299 return base::StringPrintf(kIssueAuthTokenFormat,
300 encoded_sid.c_str(),
301 encoded_lsid.c_str(),
302 service,
303 session ? "true" : "false");
306 // static
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());
316 } else {
317 return base::StringPrintf(kClientLoginToOAuth2BodyFormat,
318 encoded_scope.c_str(),
319 encoded_client_id.c_str());
323 // static
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());
340 // static
341 std::string GaiaAuthFetcher::MakeRevokeTokenBody(
342 const std::string& auth_token) {
343 return base::StringPrintf(kOAuth2RevokeTokenBodyFormat, auth_token.c_str());
346 // static
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());
352 // static
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,
360 true);
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());
372 return result;
375 // static
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.
382 // static
383 void GaiaAuthFetcher::ParseClientLoginResponse(const std::string& data,
384 std::string* sid,
385 std::string* lsid,
386 std::string* token) {
387 using std::vector;
388 using std::pair;
389 using std::string;
390 sid->clear();
391 lsid->clear();
392 token->clear();
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
406 // data.
407 if (sid->empty() && lsid->empty() && token->empty())
408 token->assign(data);
411 // static
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());
421 // static
422 void GaiaAuthFetcher::ParseClientLoginFailure(const std::string& data,
423 std::string* error,
424 std::string* error_url,
425 std::string* captcha_url,
426 std::string* captcha_token) {
427 using std::vector;
428 using std::pair;
429 using std::string;
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);
447 // static
448 bool GaiaAuthFetcher::ParseClientLoginToOAuth2Response(
449 const net::ResponseCookies& cookies,
450 std::string* auth_code) {
451 DCHECK(auth_code);
452 net::ResponseCookies::const_iterator iter;
453 for (iter = cookies.begin(); iter != cookies.end(); ++iter) {
454 if (ParseClientLoginToOAuth2Cookie(*iter, auth_code))
455 return true;
457 return false;
460 // static
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)) {
468 return false;
471 std::vector<std::string>::const_iterator iter;
472 for (iter = parts.begin(); iter != parts.end(); ++iter) {
473 const std::string& part = *iter;
474 if (StartsWithASCII(
475 part, kClientLoginToOAuth2CookiePartCodePrefix, false)) {
476 auth_code->assign(part.substr(
477 kClientLoginToOAuth2CookiePartCodePrefixLength));
478 return true;
481 return false;
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,
500 password,
501 source_,
502 service,
503 login_token,
504 login_captcha,
505 allow_hosted_accounts);
506 fetcher_.reset(CreateGaiaFetcher(getter_,
507 request_body_,
508 std::string(),
509 client_login_gurl_,
510 kLoadFlagsIgnoreCookies,
511 this));
512 fetch_pending_ = true;
513 fetcher_->Start();
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_,
525 request_body_,
526 std::string(),
527 issue_auth_token_gurl_,
528 kLoadFlagsIgnoreCookies,
529 this));
530 fetch_pending_ = true;
531 fetcher_->Start();
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_,
544 request_body_,
545 MakeGetAuthCodeHeader(auth_token),
546 client_login_to_oauth2_gurl_,
547 kLoadFlagsIgnoreCookies,
548 this));
549 fetch_pending_ = true;
550 fetcher_->Start();
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_,
559 request_body_,
560 std::string(),
561 oauth2_revoke_gurl_,
562 kLoadFlagsIgnoreCookies,
563 this));
564 fetch_pending_ = true;
565 fetcher_->Start();
568 void GaiaAuthFetcher::StartCookieForOAuthLoginTokenExchange(
569 const std::string& session_index) {
570 StartCookieForOAuthLoginTokenExchangeWithDeviceId(session_index,
571 std::string());
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()) {
591 device_id_header =
592 base::StringPrintf(kDeviceIdHeaderFormat, device_id.c_str());
595 fetcher_.reset(CreateGaiaFetcher(getter_,
596 request_body_,
597 device_id_header,
598 client_login_to_oauth2_gurl_,
599 net::LOAD_NORMAL,
600 this));
601 fetch_pending_ = true;
602 fetcher_->Start();
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_,
612 request_body_,
613 std::string(),
614 oauth2_token_gurl_,
615 kLoadFlagsIgnoreCookies,
616 this));
617 fetch_pending_ = true;
618 fetcher_->Start();
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_,
627 request_body_,
628 std::string(),
629 get_user_info_gurl_,
630 kLoadFlagsIgnoreCookies,
631 this));
632 fetch_pending_ = true;
633 fetcher_->Start();
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_,
654 request_body_,
655 std::string(),
656 merge_session_gurl_,
657 net::LOAD_NORMAL,
658 this));
659 fetch_pending_ = true;
660 fetcher_->Start();
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="
668 << access_token;
669 std::string authentication_header =
670 base::StringPrintf(kOAuthHeaderFormat, access_token.c_str());
671 fetcher_.reset(CreateGaiaFetcher(getter_,
672 std::string(),
673 authentication_header,
674 uberauth_token_gurl_,
675 net::LOAD_NORMAL,
676 this));
677 fetch_pending_ = true;
678 fetcher_->Start();
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_,
689 request_body_,
690 authentication_header,
691 oauth_login_gurl_,
692 net::LOAD_NORMAL,
693 this));
694 fetch_pending_ = true;
695 fetcher_->Start();
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",
704 list_accounts_gurl_,
705 net::LOAD_NORMAL,
706 this));
707 fetch_pending_ = true;
708 fetcher_->Start();
711 void GaiaAuthFetcher::StartGetCheckConnectionInfo() {
712 DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";
714 fetcher_.reset(CreateGaiaFetcher(getter_,
715 std::string(),
716 std::string(),
717 get_check_connection_info_url_,
718 kLoadFlagsIgnoreCookies,
719 this));
720 fetch_pending_ = true;
721 fetcher_->Start();
724 // static
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 "
733 << status.error();
734 return GoogleServiceAuthError::FromConnectionError(status.error());
737 if (IsSecondFactorSuccess(data))
738 return GoogleServiceAuthError(GoogleServiceAuthError::TWO_FACTOR);
740 std::string error;
741 std::string url;
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(
749 captcha_token,
750 GURL(GaiaUrls::GetInstance()->captcha_base_url().Resolve(captcha_url)),
751 GURL(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,
772 int response_code) {
773 if (status.is_success() && response_code == net::HTTP_OK) {
774 DVLOG(1) << "ClientLogin successful!";
775 std::string sid;
776 std::string lsid;
777 std::string token;
778 ParseClientLoginResponse(data, &sid, &lsid, &token);
779 consumer_->OnClientLoginSuccess(
780 GaiaAuthConsumer::ClientLoginResult(sid, lsid, token, data));
781 } else {
782 consumer_->OnClientLoginFailure(GenerateAuthError(data, status));
786 void GaiaAuthFetcher::OnIssueAuthTokenFetched(
787 const std::string& data,
788 const net::URLRequestStatus& status,
789 int response_code) {
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);
794 } else {
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,
804 int response_code) {
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);
809 } else {
810 GoogleServiceAuthError auth_error(
811 GoogleServiceAuthError::FromUnexpectedServiceResponse(
812 "ClientLogin response cookies didn't contain an auth code"));
813 consumer_->OnClientOAuthFailure(auth_error);
815 } else {
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,
824 int response_code) {
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);
840 if (success) {
841 consumer_->OnClientOAuthSuccess(
842 GaiaAuthConsumer::ClientOAuthResult(refresh_token, access_token,
843 expires_in_secs));
844 } else {
845 consumer_->OnClientOAuthFailure(GenerateAuthError(data, status));
849 void GaiaAuthFetcher::OnOAuth2RevokeTokenFetched(
850 const std::string& data,
851 const net::URLRequestStatus& status,
852 int response_code) {
853 consumer_->OnOAuth2RevokeTokenCompleted();
856 void GaiaAuthFetcher::OnListAccountsFetched(const std::string& data,
857 const net::URLRequestStatus& status,
858 int response_code) {
859 if (status.is_success() && response_code == net::HTTP_OK) {
860 consumer_->OnListAccountsSuccess(data);
861 } else {
862 consumer_->OnListAccountsFailure(GenerateAuthError(data, status));
866 void GaiaAuthFetcher::OnGetUserInfoFetched(
867 const std::string& data,
868 const net::URLRequestStatus& status,
869 int response_code) {
870 if (status.is_success() && response_code == net::HTTP_OK) {
871 base::StringPairs tokens;
872 UserInfoMap matches;
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);
879 } else {
880 consumer_->OnGetUserInfoFailure(GenerateAuthError(data, status));
884 void GaiaAuthFetcher::OnMergeSessionFetched(const std::string& data,
885 const net::URLRequestStatus& status,
886 int response_code) {
887 if (status.is_success() && response_code == net::HTTP_OK) {
888 consumer_->OnMergeSessionSuccess(data);
889 } else {
890 consumer_->OnMergeSessionFailure(GenerateAuthError(data, status));
894 void GaiaAuthFetcher::OnUberAuthTokenFetch(const std::string& data,
895 const net::URLRequestStatus& status,
896 int response_code) {
897 if (status.is_success() && response_code == net::HTTP_OK) {
898 consumer_->OnUberAuthTokenSuccess(data);
899 } else {
900 consumer_->OnUberAuthTokenFailure(GenerateAuthError(data, status));
904 void GaiaAuthFetcher::OnOAuthLoginFetched(const std::string& data,
905 const net::URLRequestStatus& status,
906 int response_code) {
907 if (status.is_success() && response_code == net::HTTP_OK) {
908 DVLOG(1) << "ClientLogin successful!";
909 std::string sid;
910 std::string lsid;
911 std::string token;
912 ParseClientLoginResponse(data, &sid, &lsid, &token);
913 consumer_->OnClientLoginSuccess(
914 GaiaAuthConsumer::ClientLoginResult(sid, lsid, token, data));
915 } else {
916 consumer_->OnClientLoginFailure(GenerateAuthError(data, status));
920 void GaiaAuthFetcher::OnGetCheckConnectionInfoFetched(
921 const std::string& data,
922 const net::URLRequestStatus& status,
923 int response_code) {
924 if (status.is_success() && response_code == net::HTTP_OK) {
925 consumer_->OnGetCheckConnectionInfoSuccess(data);
926 } else {
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();
939 std::string data;
940 source->GetResponseAsString(&data);
941 #ifndef NDEBUG
942 std::string headers;
943 if (source->GetResponseHeaders())
944 source->GetResponseHeaders()->GetNormalizedHeaders(&headers);
945 DVLOG(2) << "Response " << url.spec() << ", code = " << response_code << "\n"
946 << headers << "\n";
947 DVLOG(2) << "data: " << data << "\n";
948 #endif
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);
974 } else {
975 NOTREACHED();
979 // static
980 bool GaiaAuthFetcher::IsSecondFactorSuccess(
981 const std::string& alleged_error) {
982 return alleged_error.find(kSecondFactor) !=
983 std::string::npos;