Fix hittest not working correctly on non client mouse messages on high DPI Windows.
[chromium-blink-merge.git] / google_apis / gaia / gaia_auth_fetcher.cc
blob4e21fd7e59153405107015031e1b07df4289a172
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::kOAuth2CodeToTokenPairBodyFormat[] =
92 "scope=%s&"
93 "grant_type=authorization_code&"
94 "client_id=%s&"
95 "client_secret=%s&"
96 "code=%s";
97 // static
98 const char GaiaAuthFetcher::kOAuth2RevokeTokenBodyFormat[] =
99 "token=%s";
100 // static
101 const char GaiaAuthFetcher::kGetUserInfoFormat[] =
102 "LSID=%s";
103 // static
104 const char GaiaAuthFetcher::kMergeSessionFormat[] =
105 "uberauth=%s&"
106 "continue=%s&"
107 "source=%s";
108 // static
109 const char GaiaAuthFetcher::kUberAuthTokenURLFormat[] =
110 "?source=%s&"
111 "issueuberauth=1";
113 const char GaiaAuthFetcher::kOAuthLoginFormat[] = "service=%s&source=%s";
115 // static
116 const char GaiaAuthFetcher::kAccountDeletedError[] = "AccountDeleted";
117 // static
118 const char GaiaAuthFetcher::kAccountDisabledError[] = "AccountDisabled";
119 // static
120 const char GaiaAuthFetcher::kBadAuthenticationError[] = "BadAuthentication";
121 // static
122 const char GaiaAuthFetcher::kCaptchaError[] = "CaptchaRequired";
123 // static
124 const char GaiaAuthFetcher::kServiceUnavailableError[] =
125 "ServiceUnavailable";
126 // static
127 const char GaiaAuthFetcher::kErrorParam[] = "Error";
128 // static
129 const char GaiaAuthFetcher::kErrorUrlParam[] = "Url";
130 // static
131 const char GaiaAuthFetcher::kCaptchaUrlParam[] = "CaptchaUrl";
132 // static
133 const char GaiaAuthFetcher::kCaptchaTokenParam[] = "CaptchaToken";
135 // static
136 const char GaiaAuthFetcher::kCookiePersistence[] = "true";
137 // static
138 // TODO(johnnyg): When hosted accounts are supported by sync,
139 // we can always use "HOSTED_OR_GOOGLE"
140 const char GaiaAuthFetcher::kAccountTypeHostedOrGoogle[] =
141 "HOSTED_OR_GOOGLE";
142 const char GaiaAuthFetcher::kAccountTypeGoogle[] =
143 "GOOGLE";
145 // static
146 const char GaiaAuthFetcher::kSecondFactor[] = "Info=InvalidSecondFactor";
148 // static
149 const char GaiaAuthFetcher::kAuthHeaderFormat[] =
150 "Authorization: GoogleLogin auth=%s";
151 // static
152 const char GaiaAuthFetcher::kOAuthHeaderFormat[] = "Authorization: OAuth %s";
153 // static
154 const char GaiaAuthFetcher::kOAuth2BearerHeaderFormat[] =
155 "Authorization: Bearer %s";
156 // static
157 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartSecure[] = "secure";
158 // static
159 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartHttpOnly[] =
160 "httponly";
161 // static
162 const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefix[] =
163 "oauth_code=";
164 // static
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),
172 getter_(getter),
173 source_(source),
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() {
196 fetcher_.reset();
197 fetch_pending_ = false;
200 // static
201 net::URLFetcher* GaiaAuthFetcher::CreateGaiaFetcher(
202 net::URLRequestContextGetter* getter,
203 const std::string& body,
204 const std::string& headers,
205 const GURL& gaia_gurl,
206 int load_flags,
207 net::URLFetcherDelegate* delegate) {
208 net::URLFetcher* to_return = net::URLFetcher::Create(
209 0, gaia_gurl,
210 body == "" ? net::URLFetcher::GET : net::URLFetcher::POST,
211 delegate);
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);
235 return to_return;
238 // static
239 std::string GaiaAuthFetcher::MakeClientLoginBody(
240 const std::string& username,
241 const std::string& password,
242 const std::string& source,
243 const char* service,
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,
250 true);
251 std::string encoded_login_captcha = net::EscapeUrlEncodedData(login_captcha,
252 true);
254 const char* account_type = allow_hosted_accounts == HostedAccountsAllowed ?
255 kAccountTypeHostedOrGoogle :
256 kAccountTypeGoogle;
258 if (login_token.empty() || login_captcha.empty()) {
259 return base::StringPrintf(kClientLoginFormat,
260 encoded_username.c_str(),
261 encoded_password.c_str(),
262 kCookiePersistence,
263 account_type,
264 source.c_str(),
265 service);
268 return base::StringPrintf(kClientLoginCaptchaFormat,
269 encoded_username.c_str(),
270 encoded_password.c_str(),
271 kCookiePersistence,
272 account_type,
273 source.c_str(),
274 service,
275 encoded_login_token.c_str(),
276 encoded_login_captcha.c_str());
279 // static
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.
288 bool session = true;
289 if (!strcmp(service, GaiaConstants::kGaiaService))
290 session = false;
292 return base::StringPrintf(kIssueAuthTokenFormat,
293 encoded_sid.c_str(),
294 encoded_lsid.c_str(),
295 service,
296 session ? "true" : "false");
299 // static
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());
310 // static
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());
327 // static
328 std::string GaiaAuthFetcher::MakeRevokeTokenBody(
329 const std::string& auth_token) {
330 return base::StringPrintf(kOAuth2RevokeTokenBodyFormat, auth_token.c_str());
333 // static
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());
339 // static
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,
346 true);
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());
354 // static
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.
361 // static
362 void GaiaAuthFetcher::ParseClientLoginResponse(const std::string& data,
363 std::string* sid,
364 std::string* lsid,
365 std::string* token) {
366 using std::vector;
367 using std::pair;
368 using std::string;
369 sid->clear();
370 lsid->clear();
371 token->clear();
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
385 // data.
386 if (sid->empty() && lsid->empty() && token->empty())
387 token->assign(data);
390 // static
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());
400 // static
401 void GaiaAuthFetcher::ParseClientLoginFailure(const std::string& data,
402 std::string* error,
403 std::string* error_url,
404 std::string* captcha_url,
405 std::string* captcha_token) {
406 using std::vector;
407 using std::pair;
408 using std::string;
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);
426 // static
427 bool GaiaAuthFetcher::ParseClientLoginToOAuth2Response(
428 const net::ResponseCookies& cookies,
429 std::string* auth_code) {
430 DCHECK(auth_code);
431 net::ResponseCookies::const_iterator iter;
432 for (iter = cookies.begin(); iter != cookies.end(); ++iter) {
433 if (ParseClientLoginToOAuth2Cookie(*iter, auth_code))
434 return true;
436 return false;
439 // static
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)) {
447 return false;
450 std::vector<std::string>::const_iterator iter;
451 for (iter = parts.begin(); iter != parts.end(); ++iter) {
452 const std::string& part = *iter;
453 if (StartsWithASCII(
454 part, kClientLoginToOAuth2CookiePartCodePrefix, false)) {
455 auth_code->assign(part.substr(
456 kClientLoginToOAuth2CookiePartCodePrefixLength));
457 return true;
460 return false;
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,
479 password,
480 source_,
481 service,
482 login_token,
483 login_captcha,
484 allow_hosted_accounts);
485 fetcher_.reset(CreateGaiaFetcher(getter_,
486 request_body_,
487 std::string(),
488 client_login_gurl_,
489 kLoadFlagsIgnoreCookies,
490 this));
491 fetch_pending_ = true;
492 fetcher_->Start();
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_,
504 request_body_,
505 std::string(),
506 issue_auth_token_gurl_,
507 kLoadFlagsIgnoreCookies,
508 this));
509 fetch_pending_ = true;
510 fetcher_->Start();
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_,
523 request_body_,
524 MakeGetAuthCodeHeader(auth_token),
525 client_login_to_oauth2_gurl_,
526 kLoadFlagsIgnoreCookies,
527 this));
528 fetch_pending_ = true;
529 fetcher_->Start();
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_,
538 request_body_,
539 std::string(),
540 oauth2_revoke_gurl_,
541 kLoadFlagsIgnoreCookies,
542 this));
543 fetch_pending_ = true;
544 fetcher_->Start();
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_,
569 request_body_,
570 std::string(),
571 client_login_to_oauth2_gurl_,
572 net::LOAD_NORMAL,
573 this));
574 fetch_pending_ = true;
575 fetch_code_only_ = false;
576 fetcher_->Start();
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_,
586 request_body_,
587 std::string(),
588 oauth2_token_gurl_,
589 kLoadFlagsIgnoreCookies,
590 this));
591 fetch_pending_ = true;
592 fetcher_->Start();
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_,
601 request_body_,
602 std::string(),
603 get_user_info_gurl_,
604 kLoadFlagsIgnoreCookies,
605 this));
606 fetch_pending_ = true;
607 fetcher_->Start();
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_,
626 request_body_,
627 std::string(),
628 merge_session_gurl_,
629 net::LOAD_NORMAL,
630 this));
631 fetch_pending_ = true;
632 fetcher_->Start();
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="
640 << access_token;
641 std::string authentication_header =
642 base::StringPrintf(kOAuthHeaderFormat, access_token.c_str());
643 fetcher_.reset(CreateGaiaFetcher(getter_,
644 std::string(),
645 authentication_header,
646 uberauth_token_gurl_,
647 net::LOAD_NORMAL,
648 this));
649 fetch_pending_ = true;
650 fetcher_->Start();
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_,
661 request_body_,
662 authentication_header,
663 oauth_login_gurl_,
664 net::LOAD_NORMAL,
665 this));
666 fetch_pending_ = true;
667 fetcher_->Start();
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",
676 list_accounts_gurl_,
677 net::LOAD_NORMAL,
678 this));
679 fetch_pending_ = true;
680 fetcher_->Start();
683 // static
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 "
692 << status.error();
693 return GoogleServiceAuthError::FromConnectionError(status.error());
696 if (IsSecondFactorSuccess(data))
697 return GoogleServiceAuthError(GoogleServiceAuthError::TWO_FACTOR);
699 std::string error;
700 std::string url;
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(
708 captcha_token,
709 GURL(GaiaUrls::GetInstance()->captcha_base_url().Resolve(captcha_url)),
710 GURL(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,
731 int response_code) {
732 if (status.is_success() && response_code == net::HTTP_OK) {
733 DVLOG(1) << "ClientLogin successful!";
734 std::string sid;
735 std::string lsid;
736 std::string token;
737 ParseClientLoginResponse(data, &sid, &lsid, &token);
738 consumer_->OnClientLoginSuccess(
739 GaiaAuthConsumer::ClientLoginResult(sid, lsid, token, data));
740 } else {
741 consumer_->OnClientLoginFailure(GenerateAuthError(data, status));
745 void GaiaAuthFetcher::OnIssueAuthTokenFetched(
746 const std::string& data,
747 const net::URLRequestStatus& status,
748 int response_code) {
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);
753 } else {
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,
763 int response_code) {
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);
769 else
770 StartAuthCodeForOAuth2TokenExchange(auth_code);
771 } else {
772 GoogleServiceAuthError auth_error(GenerateAuthError(data, status));
773 if (fetch_code_only_)
774 consumer_->OnClientOAuthCodeFailure(auth_error);
775 else
776 consumer_->OnClientOAuthFailure(auth_error);
780 void GaiaAuthFetcher::OnOAuth2TokenPairFetched(
781 const std::string& data,
782 const net::URLRequestStatus& status,
783 int response_code) {
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);
799 if (success) {
800 consumer_->OnClientOAuthSuccess(
801 GaiaAuthConsumer::ClientOAuthResult(refresh_token, access_token,
802 expires_in_secs));
803 } else {
804 consumer_->OnClientOAuthFailure(GenerateAuthError(data, status));
808 void GaiaAuthFetcher::OnOAuth2RevokeTokenFetched(
809 const std::string& data,
810 const net::URLRequestStatus& status,
811 int response_code) {
812 consumer_->OnOAuth2RevokeTokenCompleted();
815 void GaiaAuthFetcher::OnListAccountsFetched(const std::string& data,
816 const net::URLRequestStatus& status,
817 int response_code) {
818 if (status.is_success() && response_code == net::HTTP_OK) {
819 consumer_->OnListAccountsSuccess(data);
820 } else {
821 consumer_->OnListAccountsFailure(GenerateAuthError(data, status));
825 void GaiaAuthFetcher::OnGetUserInfoFetched(
826 const std::string& data,
827 const net::URLRequestStatus& status,
828 int response_code) {
829 if (status.is_success() && response_code == net::HTTP_OK) {
830 std::vector<std::pair<std::string, std::string> > tokens;
831 UserInfoMap matches;
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);
838 } else {
839 consumer_->OnGetUserInfoFailure(GenerateAuthError(data, status));
843 void GaiaAuthFetcher::OnMergeSessionFetched(const std::string& data,
844 const net::URLRequestStatus& status,
845 int response_code) {
846 if (status.is_success() && response_code == net::HTTP_OK) {
847 consumer_->OnMergeSessionSuccess(data);
848 } else {
849 consumer_->OnMergeSessionFailure(GenerateAuthError(data, status));
853 void GaiaAuthFetcher::OnUberAuthTokenFetch(const std::string& data,
854 const net::URLRequestStatus& status,
855 int response_code) {
856 if (status.is_success() && response_code == net::HTTP_OK) {
857 consumer_->OnUberAuthTokenSuccess(data);
858 } else {
859 consumer_->OnUberAuthTokenFailure(GenerateAuthError(data, status));
863 void GaiaAuthFetcher::OnOAuthLoginFetched(const std::string& data,
864 const net::URLRequestStatus& status,
865 int response_code) {
866 if (status.is_success() && response_code == net::HTTP_OK) {
867 DVLOG(1) << "ClientLogin successful!";
868 std::string sid;
869 std::string lsid;
870 std::string token;
871 ParseClientLoginResponse(data, &sid, &lsid, &token);
872 consumer_->OnClientLoginSuccess(
873 GaiaAuthConsumer::ClientLoginResult(sid, lsid, token, data));
874 } else {
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();
887 std::string data;
888 source->GetResponseAsString(&data);
889 #ifndef NDEBUG
890 std::string headers;
891 if (source->GetResponseHeaders())
892 source->GetResponseHeaders()->GetNormalizedHeaders(&headers);
893 DVLOG(2) << "Response " << url.spec() << ", code = " << response_code << "\n"
894 << headers << "\n";
895 DVLOG(2) << "data: " << data << "\n";
896 #endif
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);
920 } else {
921 NOTREACHED();
925 // static
926 bool GaiaAuthFetcher::IsSecondFactorSuccess(
927 const std::string& alleged_error) {
928 return alleged_error.find(kSecondFactor) !=
929 std::string::npos;