summaryrefslogtreecommitdiffstats
path: root/chrome/common/net/gaia/gaia_auth_fetcher.cc
blob: f3f86d3c11579f4f57f87a54efdaa816a28e54a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/net/gaia/gaia_auth_fetcher.h"

#include <algorithm>
#include <string>
#include <utility>
#include <vector>

#include "base/json/json_reader.h"
#include "base/string_split.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/values.h"
#include "chrome/common/net/gaia/gaia_auth_consumer.h"
#include "chrome/common/net/gaia/gaia_constants.h"
#include "chrome/common/net/gaia/gaia_urls.h"
#include "chrome/common/net/gaia/google_service_auth_error.h"
#include "chrome/common/net/http_return.h"
#include "content/public/common/url_fetcher.h"
#include "net/base/escape.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_status.h"

namespace {
static bool CookiePartsContains(const std::vector<std::string>& parts,
                                const char* part) {
  return std::find(parts.begin(), parts.end(), part) != parts.end();
}
}  // namespace

// TODO(chron): Add sourceless version of this formatter.
// static
const char GaiaAuthFetcher::kClientLoginFormat[] =
    "Email=%s&"
    "Passwd=%s&"
    "PersistentCookie=%s&"
    "accountType=%s&"
    "source=%s&"
    "service=%s";
// static
const char GaiaAuthFetcher::kClientLoginCaptchaFormat[] =
    "Email=%s&"
    "Passwd=%s&"
    "PersistentCookie=%s&"
    "accountType=%s&"
    "source=%s&"
    "service=%s&"
    "logintoken=%s&"
    "logincaptcha=%s";
// static
const char GaiaAuthFetcher::kIssueAuthTokenFormat[] =
    "SID=%s&"
    "LSID=%s&"
    "service=%s&"
    "Session=%s";
// static
const char GaiaAuthFetcher::kClientLoginToOAuth2BodyFormat[] =
    "scope=%s&client_id=%s";
// static
const char GaiaAuthFetcher::kOAuth2CodeToTokenPairBodyFormat[] =
    "scope=%s&"
    "grant_type=authorization_code&"
    "client_id=%s&"
    "client_secret=%s&"
    "code=%s";
// static
const char GaiaAuthFetcher::kGetUserInfoFormat[] =
    "LSID=%s";
// static
const char GaiaAuthFetcher::kTokenAuthFormat[] =
    "auth=%s&"
    "continue=%s&"
    "source=%s";
// static
const char GaiaAuthFetcher::kMergeSessionFormat[] =
    "uberauth=%s&"
    "continue=%s&"
    "source=%s";

// static
const char GaiaAuthFetcher::kAccountDeletedError[] = "AccountDeleted";
const char GaiaAuthFetcher::kAccountDeletedErrorCode[] = "adel";
// static
const char GaiaAuthFetcher::kAccountDisabledError[] = "AccountDisabled";
const char GaiaAuthFetcher::kAccountDisabledErrorCode[] = "adis";
// static
const char GaiaAuthFetcher::kBadAuthenticationError[] = "BadAuthentication";
const char GaiaAuthFetcher::kBadAuthenticationErrorCode[] = "badauth";
// static
const char GaiaAuthFetcher::kCaptchaError[] = "CaptchaRequired";
const char GaiaAuthFetcher::kCaptchaErrorCode[] = "cr";
// static
const char GaiaAuthFetcher::kServiceUnavailableError[] =
    "ServiceUnavailable";
const char GaiaAuthFetcher::kServiceUnavailableErrorCode[] =
    "ire";
// static
const char GaiaAuthFetcher::kErrorParam[] = "Error";
// static
const char GaiaAuthFetcher::kErrorUrlParam[] = "Url";
// static
const char GaiaAuthFetcher::kCaptchaUrlParam[] = "CaptchaUrl";
// static
const char GaiaAuthFetcher::kCaptchaTokenParam[] = "CaptchaToken";

// static
const char GaiaAuthFetcher::kCookiePersistence[] = "true";
// static
// TODO(johnnyg): When hosted accounts are supported by sync,
// we can always use "HOSTED_OR_GOOGLE"
const char GaiaAuthFetcher::kAccountTypeHostedOrGoogle[] =
    "HOSTED_OR_GOOGLE";
const char GaiaAuthFetcher::kAccountTypeGoogle[] =
    "GOOGLE";

// static
const char GaiaAuthFetcher::kSecondFactor[] = "Info=InvalidSecondFactor";

// static
const char GaiaAuthFetcher::kAuthHeaderFormat[] =
    "Authorization: GoogleLogin auth=%s";
// static
const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartSecure[] = "Secure";
// static
const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartHttpOnly[] =
    "HttpOnly";
// static
const char GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefix[] =
    "oauth_code=";
// static
const int GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefixLength =
    arraysize(GaiaAuthFetcher::kClientLoginToOAuth2CookiePartCodePrefix) - 1;
// static
const char GaiaAuthFetcher::kOAuth2RefreshTokenKey[] = "refresh_token";
// static
const char GaiaAuthFetcher::kOAuth2AccessTokenKey[] = "access_token";
// static
const char GaiaAuthFetcher::kOAuth2ExpiresInKey[] = "expires_in";

GaiaAuthFetcher::GaiaAuthFetcher(GaiaAuthConsumer* consumer,
                                       const std::string& source,
                                       net::URLRequestContextGetter* getter)
    : consumer_(consumer),
      getter_(getter),
      source_(source),
      client_login_gurl_(GaiaUrls::GetInstance()->client_login_url()),
      issue_auth_token_gurl_(GaiaUrls::GetInstance()->issue_auth_token_url()),
      client_login_to_oauth2_gurl_(
          GaiaUrls::GetInstance()->client_login_to_oauth2_url()),
      oauth2_token_gurl_(GaiaUrls::GetInstance()->oauth2_token_url()),
      get_user_info_gurl_(GaiaUrls::GetInstance()->get_user_info_url()),
      token_auth_gurl_(GaiaUrls::GetInstance()->token_auth_url()),
      merge_session_gurl_(GaiaUrls::GetInstance()->merge_session_url()),
      fetch_pending_(false) {}

GaiaAuthFetcher::~GaiaAuthFetcher() {}

bool GaiaAuthFetcher::HasPendingFetch() {
  return fetch_pending_;
}

void GaiaAuthFetcher::CancelRequest() {
  fetcher_.reset();
  fetch_pending_ = false;
}

// static
content::URLFetcher* GaiaAuthFetcher::CreateGaiaFetcher(
    net::URLRequestContextGetter* getter,
    const std::string& body,
    const std::string& headers,
    const GURL& gaia_gurl,
    bool use_cookies,
    content::URLFetcherDelegate* delegate) {
  content::URLFetcher* to_return = content::URLFetcher::Create(
      0, gaia_gurl, content::URLFetcher::POST, delegate);
  to_return->SetRequestContext(getter);
  to_return->SetUploadData("application/x-www-form-urlencoded", body);

  // The Gaia token exchange requests do not require any cookie-based
  // identification as part of requests.  We suppress sending any cookies to
  // maintain a separation between the user's browsing and Chrome's internal
  // services.  Where such mixing is desired (MergeSession), it will be done
  // explicitly.
  if (!use_cookies) {
    to_return->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
                            net::LOAD_DO_NOT_SAVE_COOKIES);
  }
  if (!headers.empty())
    to_return->SetExtraRequestHeaders(headers);

  return to_return;
}

// static
std::string GaiaAuthFetcher::MakeClientLoginBody(
    const std::string& username,
    const std::string& password,
    const std::string& source,
    const char* service,
    const std::string& login_token,
    const std::string& login_captcha,
    HostedAccountsSetting allow_hosted_accounts) {
  std::string encoded_username = net::EscapeUrlEncodedData(username, true);
  std::string encoded_password = net::EscapeUrlEncodedData(password, true);
  std::string encoded_login_token = net::EscapeUrlEncodedData(login_token,
                                                              true);
  std::string encoded_login_captcha = net::EscapeUrlEncodedData(login_captcha,
                                                                true);

  const char* account_type = allow_hosted_accounts == HostedAccountsAllowed ?
      kAccountTypeHostedOrGoogle :
      kAccountTypeGoogle;

  if (login_token.empty() || login_captcha.empty()) {
    return base::StringPrintf(kClientLoginFormat,
                              encoded_username.c_str(),
                              encoded_password.c_str(),
                              kCookiePersistence,
                              account_type,
                              source.c_str(),
                              service);
  }

  return base::StringPrintf(kClientLoginCaptchaFormat,
                            encoded_username.c_str(),
                            encoded_password.c_str(),
                            kCookiePersistence,
                            account_type,
                            source.c_str(),
                            service,
                            encoded_login_token.c_str(),
                            encoded_login_captcha.c_str());
}

// static
std::string GaiaAuthFetcher::MakeIssueAuthTokenBody(
    const std::string& sid,
    const std::string& lsid,
    const char* const service) {
  std::string encoded_sid = net::EscapeUrlEncodedData(sid, true);
  std::string encoded_lsid = net::EscapeUrlEncodedData(lsid, true);

  // All tokens should be session tokens except the gaia auth token.
  bool session = true;
  if (!strcmp(service, GaiaConstants::kGaiaService))
    session = false;

  return base::StringPrintf(kIssueAuthTokenFormat,
                            encoded_sid.c_str(),
                            encoded_lsid.c_str(),
                            service,
                            session ? "true" : "false");
}

// static
std::string GaiaAuthFetcher::MakeGetAuthCodeBody() {
  std::string encoded_scope = net::EscapeUrlEncodedData(
      GaiaUrls::GetInstance()->oauth1_login_scope(), true);
  std::string encoded_client_id = net::EscapeUrlEncodedData(
      GaiaUrls::GetInstance()->oauth2_chrome_client_id(), true);
  return StringPrintf(kClientLoginToOAuth2BodyFormat,
                      encoded_scope.c_str(),
                      encoded_client_id.c_str());
}

// static
std::string GaiaAuthFetcher::MakeGetTokenPairBody(
    const std::string& auth_code) {
  std::string encoded_scope = net::EscapeUrlEncodedData(
      GaiaUrls::GetInstance()->oauth1_login_scope(), true);
  std::string encoded_client_id = net::EscapeUrlEncodedData(
      GaiaUrls::GetInstance()->oauth2_chrome_client_id(), true);
  std::string encoded_client_secret = net::EscapeUrlEncodedData(
      GaiaUrls::GetInstance()->oauth2_chrome_client_secret(), true);
  std::string encoded_auth_code = net::EscapeUrlEncodedData(auth_code, true);
  return StringPrintf(kOAuth2CodeToTokenPairBodyFormat,
                      encoded_scope.c_str(),
                      encoded_client_id.c_str(),
                      encoded_client_secret.c_str(),
                      encoded_auth_code.c_str());
}

// static
std::string GaiaAuthFetcher::MakeGetUserInfoBody(const std::string& lsid) {
  std::string encoded_lsid = net::EscapeUrlEncodedData(lsid, true);
  return base::StringPrintf(kGetUserInfoFormat, encoded_lsid.c_str());
}

// static
std::string GaiaAuthFetcher::MakeTokenAuthBody(const std::string& auth_token,
                                               const std::string& continue_url,
                                               const std::string& source) {
  std::string encoded_auth_token = net::EscapeUrlEncodedData(auth_token, true);
  std::string encoded_continue_url = net::EscapeUrlEncodedData(continue_url,
                                                               true);
  std::string encoded_source = net::EscapeUrlEncodedData(source, true);
  return base::StringPrintf(kTokenAuthFormat,
                            encoded_auth_token.c_str(),
                            encoded_continue_url.c_str(),
                            encoded_source.c_str());
}

// static
std::string GaiaAuthFetcher::MakeMergeSessionBody(
    const std::string& auth_token,
    const std::string& continue_url,
    const std::string& source) {
  std::string encoded_auth_token = net::EscapeUrlEncodedData(auth_token, true);
  std::string encoded_continue_url = net::EscapeUrlEncodedData(continue_url,
                                                               true);
  std::string encoded_source = net::EscapeUrlEncodedData(source, true);
  return base::StringPrintf(kMergeSessionFormat,
                            encoded_auth_token.c_str(),
                            encoded_continue_url.c_str(),
                            encoded_source.c_str());
}

// static
std::string GaiaAuthFetcher::MakeGetAuthCodeHeader(
    const std::string& auth_token) {
  return StringPrintf(kAuthHeaderFormat, auth_token.c_str());
}

// Helper method that extracts tokens from a successful reply.
// static
void GaiaAuthFetcher::ParseClientLoginResponse(const std::string& data,
                                                  std::string* sid,
                                                  std::string* lsid,
                                                  std::string* token) {
  using std::vector;
  using std::pair;
  using std::string;

  vector<pair<string, string> > tokens;
  base::SplitStringIntoKeyValuePairs(data, '=', '\n', &tokens);
  for (vector<pair<string, string> >::iterator i = tokens.begin();
      i != tokens.end(); ++i) {
    if (i->first == "SID") {
      sid->assign(i->second);
    } else if (i->first == "LSID") {
      lsid->assign(i->second);
    } else if (i->first == "Auth") {
      token->assign(i->second);
    }
  }
}

// static
void GaiaAuthFetcher::ParseClientLoginFailure(const std::string& data,
                                              std::string* error,
                                              std::string* error_url,
                                              std::string* captcha_url,
                                              std::string* captcha_token) {
  using std::vector;
  using std::pair;
  using std::string;

  vector<pair<string, string> > tokens;
  base::SplitStringIntoKeyValuePairs(data, '=', '\n', &tokens);
  for (vector<pair<string, string> >::iterator i = tokens.begin();
       i != tokens.end(); ++i) {
    if (i->first == kErrorParam) {
      error->assign(i->second);
    } else if (i->first == kErrorUrlParam) {
      error_url->assign(i->second);
    } else if (i->first == kCaptchaUrlParam) {
      captcha_url->assign(i->second);
    } else if (i->first == kCaptchaTokenParam) {
      captcha_token->assign(i->second);
    }
  }
}

// static
bool GaiaAuthFetcher::ParseClientLoginToOAuth2Response(
    const net::ResponseCookies& cookies,
    std::string* auth_code) {
  DCHECK(auth_code);
  net::ResponseCookies::const_iterator iter;
  for (iter = cookies.begin(); iter != cookies.end(); ++iter) {
    if (ParseClientLoginToOAuth2Cookie(*iter, auth_code))
      return true;
  }
  return false;
}

// static
bool GaiaAuthFetcher::ParseOAuth2TokenPairResponse(const std::string& data,
                                                   std::string* refresh_token,
                                                   std::string* access_token,
                                                   int* expires_in_secs) {
  DCHECK(refresh_token);
  DCHECK(access_token);
  base::JSONReader reader;
  scoped_ptr<base::Value> value(reader.Read(data, false));
  if (!value.get() || value->GetType() != base::Value::TYPE_DICTIONARY)
    return false;

  DictionaryValue* dict = static_cast<DictionaryValue*>(value.get());
  std::string rt;
  std::string at;
  int exp;

  if (!dict->GetStringWithoutPathExpansion(kOAuth2RefreshTokenKey, &rt) ||
      !dict->GetStringWithoutPathExpansion(kOAuth2AccessTokenKey, &at) ||
      !dict->GetIntegerWithoutPathExpansion(kOAuth2ExpiresInKey, &exp)) {
    return false;
  }

  refresh_token->assign(rt);
  access_token->assign(at);
  *expires_in_secs = exp;
  return true;
}

// static
bool GaiaAuthFetcher::ParseClientLoginToOAuth2Cookie(const std::string& cookie,
                                                     std::string* auth_code) {
  std::vector<std::string> parts;
  base::SplitString(cookie, ';', &parts);
  // Per documentation, the cookie should have Secure and HttpOnly.
  if (!CookiePartsContains(parts, kClientLoginToOAuth2CookiePartSecure) ||
      !CookiePartsContains(parts, kClientLoginToOAuth2CookiePartHttpOnly)) {
    return false;
  }

  std::vector<std::string>::const_iterator iter;
  for (iter = parts.begin(); iter != parts.end(); ++iter) {
    const std::string& part = *iter;
    if (StartsWithASCII(
        part, kClientLoginToOAuth2CookiePartCodePrefix, false)) {
      auth_code->assign(part.substr(
          kClientLoginToOAuth2CookiePartCodePrefixLength));
      return true;
    }
  }
  return false;
}

void GaiaAuthFetcher::StartClientLogin(
    const std::string& username,
    const std::string& password,
    const char* const service,
    const std::string& login_token,
    const std::string& login_captcha,
    HostedAccountsSetting allow_hosted_accounts) {

  DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";

  // This class is thread agnostic, so be sure to call this only on the
  // same thread each time.
  DVLOG(1) << "Starting new ClientLogin fetch for:" << username;

  // Must outlive fetcher_.
  request_body_ = MakeClientLoginBody(username,
                                      password,
                                      source_,
                                      service,
                                      login_token,
                                      login_captcha,
                                      allow_hosted_accounts);
  fetcher_.reset(CreateGaiaFetcher(getter_,
                                   request_body_,
                                   "",
                                   client_login_gurl_,
                                   false,
                                   this));
  fetch_pending_ = true;
  fetcher_->Start();
}

void GaiaAuthFetcher::StartIssueAuthToken(const std::string& sid,
                                          const std::string& lsid,
                                          const char* const service) {
  DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";

  DVLOG(1) << "Starting IssueAuthToken for: " << service;
  requested_service_ = service;
  request_body_ = MakeIssueAuthTokenBody(sid, lsid, service);
  fetcher_.reset(CreateGaiaFetcher(getter_,
                                   request_body_,
                                   "",
                                   issue_auth_token_gurl_,
                                   false,
                                   this));
  fetch_pending_ = true;
  fetcher_->Start();
}

void GaiaAuthFetcher::StartOAuthLoginTokenFetch(
    const std::string& auth_token) {
  DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";

  DVLOG(1) << "Starting OAuth login token fetch";
  request_body_ = MakeGetAuthCodeBody();
  fetcher_.reset(CreateGaiaFetcher(getter_,
                                   request_body_,
                                   MakeGetAuthCodeHeader(auth_token),
                                   client_login_to_oauth2_gurl_,
                                   false,
                                   this));
  fetch_pending_ = true;
  fetcher_->Start();
}

void GaiaAuthFetcher::StartGetUserInfo(const std::string& lsid,
                                       const std::string& info_key) {
  DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";

  DVLOG(1) << "Starting GetUserInfo for lsid=" << lsid;
  request_body_ = MakeGetUserInfoBody(lsid);
  fetcher_.reset(CreateGaiaFetcher(getter_,
                                   request_body_,
                                   "",
                                   get_user_info_gurl_,
                                   false,
                                   this));
  fetch_pending_ = true;
  requested_info_key_ = info_key;
  fetcher_->Start();
}

void GaiaAuthFetcher::StartTokenAuth(const std::string& auth_token) {
  DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";

  DVLOG(1) << "Starting TokenAuth with auth_token=" << auth_token;

  // The continue URL is a required parameter of the TokenAuth API, but in this
  // case we don't actually need or want to navigate to it.  Setting it to
  // an arbitrary Google URL.
  std::string continue_url("http://www.google.com");
  request_body_ = MakeTokenAuthBody(auth_token, continue_url, source_);
  fetcher_.reset(CreateGaiaFetcher(getter_,
                                   request_body_,
                                   "",
                                   token_auth_gurl_,
                                   false,
                                   this));
  fetch_pending_ = true;
  fetcher_->Start();
}

void GaiaAuthFetcher::StartMergeSession(const std::string& auth_token) {
  DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";

  DVLOG(1) << "Starting MergeSession with auth_token=" << auth_token;

  // The continue URL is a required parameter of the MergeSession API, but in
  // this case we don't actually need or want to navigate to it.  Setting it to
  // an arbitrary Google URL.
  //
  // In order for the new session to be merged correctly, the server needs to
  // know what sessions already exist in the browser.  The fetcher needs to be
  // created such that it sends the cookies with the request, which is
  // different from all other requests the fetcher can make.
  std::string continue_url("http://www.google.com");
  request_body_ = MakeMergeSessionBody(auth_token, continue_url, source_);
  fetcher_.reset(CreateGaiaFetcher(getter_,
                                   request_body_,
                                   "",
                                   merge_session_gurl_,
                                   true,
                                   this));
  fetch_pending_ = true;
  fetcher_->Start();
}

// static
GoogleServiceAuthError GaiaAuthFetcher::GenerateAuthError(
    const std::string& data,
    const net::URLRequestStatus& status) {
  if (!status.is_success()) {
    if (status.status() == net::URLRequestStatus::CANCELED) {
      return GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED);
    } else {
      DLOG(WARNING) << "Could not reach Google Accounts servers: errno "
          << status.error();
      return GoogleServiceAuthError::FromConnectionError(status.error());
    }
  } else {
    if (IsSecondFactorSuccess(data)) {
      return GoogleServiceAuthError(GoogleServiceAuthError::TWO_FACTOR);
    }

    std::string error;
    std::string url;
    std::string captcha_url;
    std::string captcha_token;
    ParseClientLoginFailure(data, &error, &url, &captcha_url, &captcha_token);
    DLOG(WARNING) << "ClientLogin failed with " << error;

    if (error == kCaptchaError) {
      GURL image_url(
          GaiaUrls::GetInstance()->captcha_url_prefix() + captcha_url);
      GURL unlock_url(url);
      return GoogleServiceAuthError::FromCaptchaChallenge(
          captcha_token, image_url, unlock_url);
    }
    if (error == kAccountDeletedError)
      return GoogleServiceAuthError(GoogleServiceAuthError::ACCOUNT_DELETED);
    if (error == kAccountDisabledError)
      return GoogleServiceAuthError(GoogleServiceAuthError::ACCOUNT_DISABLED);
    if (error == kBadAuthenticationError) {
      return GoogleServiceAuthError(
          GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
    }
    if (error == kServiceUnavailableError) {
      return GoogleServiceAuthError(
          GoogleServiceAuthError::SERVICE_UNAVAILABLE);
    }

    DLOG(WARNING) << "Incomprehensible response from Google Accounts servers.";
    return GoogleServiceAuthError(
        GoogleServiceAuthError::SERVICE_UNAVAILABLE);
  }

  NOTREACHED();
  return GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_UNAVAILABLE);
}

// static
GoogleServiceAuthError GaiaAuthFetcher::GenerateOAuthLoginError(
    const std::string& data,
    const net::URLRequestStatus& status) {
  if (!status.is_success()) {
    if (status.status() == net::URLRequestStatus::CANCELED) {
      return GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED);
    } else {
      DLOG(WARNING) << "Could not reach Google Accounts servers: errno "
          << status.error();
      return GoogleServiceAuthError::FromConnectionError(status.error());
    }
  } else {
    if (IsSecondFactorSuccess(data)) {
      return GoogleServiceAuthError(GoogleServiceAuthError::TWO_FACTOR);
    }

    std::string error;
    std::string url;
    std::string captcha_url;
    std::string captcha_token;
    ParseClientLoginFailure(data, &error, &url, &captcha_url, &captcha_token);
    LOG(WARNING) << "OAuthLogin failed with " << error;

    if (error == kCaptchaErrorCode) {
      GURL image_url(
          GaiaUrls::GetInstance()->captcha_url_prefix() + captcha_url);
      GURL unlock_url(url);
      return GoogleServiceAuthError::FromCaptchaChallenge(
          captcha_token, image_url, unlock_url);
    }
    if (error == kAccountDeletedErrorCode)
      return GoogleServiceAuthError(GoogleServiceAuthError::ACCOUNT_DELETED);
    if (error == kAccountDisabledErrorCode)
      return GoogleServiceAuthError(GoogleServiceAuthError::ACCOUNT_DISABLED);
    if (error == kBadAuthenticationErrorCode) {
      return GoogleServiceAuthError(
          GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
    }
    if (error == kServiceUnavailableErrorCode) {
      return GoogleServiceAuthError(
          GoogleServiceAuthError::SERVICE_UNAVAILABLE);
    }

    DLOG(WARNING) << "Incomprehensible response from Google Accounts servers.";
    return GoogleServiceAuthError(
        GoogleServiceAuthError::SERVICE_UNAVAILABLE);
  }

  NOTREACHED();
  return GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_UNAVAILABLE);
}

void GaiaAuthFetcher::OnClientLoginFetched(const std::string& data,
                                           const net::URLRequestStatus& status,
                                           int response_code) {
  if (status.is_success() && response_code == RC_REQUEST_OK) {
    DVLOG(1) << "ClientLogin successful!";
    std::string sid;
    std::string lsid;
    std::string token;
    ParseClientLoginResponse(data, &sid, &lsid, &token);
    consumer_->OnClientLoginSuccess(
        GaiaAuthConsumer::ClientLoginResult(sid, lsid, token, data));
  } else {
    consumer_->OnClientLoginFailure(GenerateAuthError(data, status));
  }
}

void GaiaAuthFetcher::OnIssueAuthTokenFetched(
    const std::string& data,
    const net::URLRequestStatus& status,
    int response_code) {
  if (status.is_success() && response_code == RC_REQUEST_OK) {
    // Only the bare token is returned in the body of this Gaia call
    // without any padding.
    consumer_->OnIssueAuthTokenSuccess(requested_service_, data);
  } else {
    consumer_->OnIssueAuthTokenFailure(requested_service_,
        GenerateAuthError(data, status));
  }
}

void GaiaAuthFetcher::OnClientLoginToOAuth2Fetched(
    const std::string& data,
    const net::ResponseCookies& cookies,
    const net::URLRequestStatus& status,
    int response_code) {
  if (status.is_success() && response_code == RC_REQUEST_OK) {
    std::string auth_code;
    ParseClientLoginToOAuth2Response(cookies, &auth_code);
    StartOAuth2TokenPairFetch(auth_code);
  } else {
    consumer_->OnOAuthLoginTokenFailure(GenerateAuthError(data, status));
  }
}

void GaiaAuthFetcher::StartOAuth2TokenPairFetch(const std::string& auth_code) {
  DCHECK(!fetch_pending_) << "Tried to fetch two things at once!";

  DVLOG(1) << "Starting OAuth token pair fetch";
  request_body_ = MakeGetTokenPairBody(auth_code);
  fetcher_.reset(CreateGaiaFetcher(getter_,
                                   request_body_,
                                   "",
                                   oauth2_token_gurl_,
                                   false,
                                   this));
  fetch_pending_ = true;
  fetcher_->Start();
}

void GaiaAuthFetcher::OnOAuth2TokenPairFetched(
    const std::string& data,
    const net::URLRequestStatus& status,
    int response_code) {
  if (status.is_success() && response_code == RC_REQUEST_OK) {
    std::string refresh_token;
    std::string access_token;
    int expires_in_secs;
    ParseOAuth2TokenPairResponse(
        data, &refresh_token, &access_token, &expires_in_secs);
    consumer_->OnOAuthLoginTokenSuccess(
          refresh_token, access_token, expires_in_secs);
  } else {
    consumer_->OnOAuthLoginTokenFailure(GenerateAuthError(data, status));
  }
}

void GaiaAuthFetcher::OnGetUserInfoFetched(
    const std::string& data,
    const net::URLRequestStatus& status,
    int response_code) {
  using std::vector;
  using std::string;
  using std::pair;

  if (status.is_success() && response_code == RC_REQUEST_OK) {
    vector<pair<string, string> > tokens;
    base::SplitStringIntoKeyValuePairs(data, '=', '\n', &tokens);
    for (vector<pair<string, string> >::iterator i = tokens.begin();
         i != tokens.end(); ++i) {
      if (i->first == requested_info_key_) {
        consumer_->OnGetUserInfoSuccess(i->first, i->second);
        return;
      }
    }
    consumer_->OnGetUserInfoKeyNotFound(requested_info_key_);
  } else {
    consumer_->OnGetUserInfoFailure(GenerateAuthError(data, status));
  }
}

void GaiaAuthFetcher::OnTokenAuthFetched(const std::string& data,
                                         const net::URLRequestStatus& status,
                                         int response_code) {
  if (status.is_success() && response_code == RC_REQUEST_OK) {
    consumer_->OnTokenAuthSuccess(data);
  } else {
    consumer_->OnTokenAuthFailure(GenerateAuthError(data, status));
  }
}

void GaiaAuthFetcher::OnMergeSessionFetched(const std::string& data,
                                            const net::URLRequestStatus& status,
                                            int response_code) {
  if (status.is_success() && response_code == RC_REQUEST_OK) {
    consumer_->OnMergeSessionSuccess(data);
  } else {
    consumer_->OnMergeSessionFailure(GenerateAuthError(data, status));
  }
}

void GaiaAuthFetcher::OnURLFetchComplete(const content::URLFetcher* source) {
  fetch_pending_ = false;
  const GURL& url = source->GetURL();
  const net::URLRequestStatus& status = source->GetStatus();
  int response_code = source->GetResponseCode();
  std::string data;
  source->GetResponseAsString(&data);
  if (url == client_login_gurl_) {
    OnClientLoginFetched(data, status, response_code);
  } else if (url == issue_auth_token_gurl_) {
    OnIssueAuthTokenFetched(data, status, response_code);
  } else if (url == client_login_to_oauth2_gurl_) {
    OnClientLoginToOAuth2Fetched(
        data, source->GetCookies(), status, response_code);
  } else if (url == oauth2_token_gurl_) {
    OnOAuth2TokenPairFetched(data, status, response_code);
  } else if (url == get_user_info_gurl_) {
    OnGetUserInfoFetched(data, status, response_code);
  } else if (url == token_auth_gurl_) {
    OnTokenAuthFetched(data, status, response_code);
  } else if (url == merge_session_gurl_ ||
      (source && source->GetOriginalURL() == merge_session_gurl_)) {
    // MergeSession may redirect, so check the original URL of the fetcher.
    OnMergeSessionFetched(data, status, response_code);
  } else {
    NOTREACHED();
  }
}

// static
bool GaiaAuthFetcher::IsSecondFactorSuccess(
    const std::string& alleged_error) {
  return alleged_error.find(kSecondFactor) !=
      std::string::npos;
}