gaia_oauth_client.cc 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  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.
  4. #include "google_apis/gaia/gaia_oauth_client.h"
  5. #include <memory>
  6. #include <utility>
  7. #include "base/bind.h"
  8. #include "base/check.h"
  9. #include "base/check_op.h"
  10. #include "base/json/json_reader.h"
  11. #include "base/memory/raw_ptr.h"
  12. #include "base/memory/weak_ptr.h"
  13. #include "base/notreached.h"
  14. #include "base/strings/escape.h"
  15. #include "base/strings/strcat.h"
  16. #include "base/strings/string_util.h"
  17. #include "base/threading/thread_task_runner_handle.h"
  18. #include "base/values.h"
  19. #include "google_apis/gaia/gaia_auth_util.h"
  20. #include "google_apis/gaia/gaia_urls.h"
  21. #include "net/base/backoff_entry.h"
  22. #include "net/base/load_flags.h"
  23. #include "net/http/http_status_code.h"
  24. #include "net/traffic_annotation/network_traffic_annotation.h"
  25. #include "net/url_request/url_request_throttler_entry.h"
  26. #include "services/network/public/cpp/resource_request.h"
  27. #include "services/network/public/cpp/shared_url_loader_factory.h"
  28. #include "services/network/public/cpp/simple_url_loader.h"
  29. #include "services/network/public/mojom/url_response_head.mojom.h"
  30. #include "url/gurl.h"
  31. namespace {
  32. const char kAccessTokenValue[] = "access_token";
  33. const char kRefreshTokenValue[] = "refresh_token";
  34. const char kExpiresInValue[] = "expires_in";
  35. }
  36. namespace gaia {
  37. class GaiaOAuthClient::Core
  38. : public base::RefCountedThreadSafe<GaiaOAuthClient::Core> {
  39. public:
  40. Core(scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory)
  41. : backoff_entry_(&backoff_policy_),
  42. num_retries_(0),
  43. max_retries_(0),
  44. url_loader_factory_(url_loader_factory),
  45. delegate_(nullptr),
  46. request_type_(NO_PENDING_REQUEST) {
  47. backoff_policy_.num_errors_to_ignore =
  48. net::URLRequestThrottlerEntry::kDefaultNumErrorsToIgnore;
  49. backoff_policy_.initial_delay_ms =
  50. net::URLRequestThrottlerEntry::kDefaultInitialDelayMs;
  51. backoff_policy_.multiply_factor =
  52. net::URLRequestThrottlerEntry::kDefaultMultiplyFactor;
  53. backoff_policy_.jitter_factor =
  54. net::URLRequestThrottlerEntry::kDefaultJitterFactor;
  55. backoff_policy_.maximum_backoff_ms =
  56. net::URLRequestThrottlerEntry::kDefaultMaximumBackoffMs;
  57. backoff_policy_.entry_lifetime_ms =
  58. net::URLRequestThrottlerEntry::kDefaultEntryLifetimeMs;
  59. backoff_policy_.always_use_initial_delay = false;
  60. }
  61. void GetTokensFromAuthCode(const OAuthClientInfo& oauth_client_info,
  62. const std::string& auth_code,
  63. int max_retries,
  64. GaiaOAuthClient::Delegate* delegate);
  65. void RefreshToken(const OAuthClientInfo& oauth_client_info,
  66. const std::string& refresh_token,
  67. const std::vector<std::string>& scopes,
  68. int max_retries,
  69. GaiaOAuthClient::Delegate* delegate);
  70. void GetUserEmail(const std::string& oauth_access_token,
  71. int max_retries,
  72. Delegate* delegate);
  73. void GetUserId(const std::string& oauth_access_token,
  74. int max_retries,
  75. Delegate* delegate);
  76. void GetUserInfo(const std::string& oauth_access_token,
  77. int max_retries,
  78. Delegate* delegate);
  79. void GetAccountCapabilities(
  80. const std::string& oauth_access_token,
  81. const std::vector<std::string>& capabilities_names,
  82. int max_retries,
  83. Delegate* delegate);
  84. void GetTokenInfo(const std::string& qualifier,
  85. const std::string& query,
  86. int max_retries,
  87. Delegate* delegate);
  88. // Called as a SimpleURLLoader callback
  89. void OnURLLoadComplete(std::unique_ptr<std::string> body);
  90. private:
  91. friend class base::RefCountedThreadSafe<Core>;
  92. enum RequestType {
  93. NO_PENDING_REQUEST,
  94. TOKENS_FROM_AUTH_CODE,
  95. REFRESH_TOKEN,
  96. TOKEN_INFO,
  97. USER_EMAIL,
  98. USER_ID,
  99. USER_INFO,
  100. ACCOUNT_CAPABILITIES,
  101. };
  102. ~Core() {}
  103. void GetUserInfoImpl(RequestType type,
  104. const std::string& oauth_access_token,
  105. int max_retries,
  106. Delegate* delegate);
  107. // Stores request settings into |this| and calls SendRequest().
  108. void MakeRequest(
  109. RequestType type,
  110. const GURL& url,
  111. std::string post_body /* may be empty if not needed*/,
  112. std::string authorization_header /* empty if not needed */,
  113. std::string http_method_override_header /* empty if not needed */,
  114. int max_retries,
  115. GaiaOAuthClient::Delegate* delegate,
  116. const net::MutableNetworkTrafficAnnotationTag& traffic_annotation);
  117. // Sends out a request based on things MakeRequest() stored...
  118. // once |backoff_entry_| says it's OK. Can be called many times to retry,
  119. // assuming |request_| is destroyed first.
  120. void SendRequest();
  121. // Actually sends the request.
  122. void SendRequestImpl();
  123. void HandleResponse(std::unique_ptr<std::string> body,
  124. bool* should_retry_request);
  125. net::BackoffEntry::Policy backoff_policy_;
  126. net::BackoffEntry backoff_entry_;
  127. int num_retries_;
  128. int max_retries_;
  129. GURL url_;
  130. net::MutableNetworkTrafficAnnotationTag traffic_annotation_;
  131. std::string post_body_;
  132. std::string authorization_header_;
  133. std::string http_method_override_header_;
  134. scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
  135. raw_ptr<GaiaOAuthClient::Delegate> delegate_;
  136. std::unique_ptr<network::SimpleURLLoader> request_;
  137. RequestType request_type_;
  138. base::WeakPtrFactory<Core> weak_ptr_factory_{this};
  139. };
  140. void GaiaOAuthClient::Core::GetTokensFromAuthCode(
  141. const OAuthClientInfo& oauth_client_info,
  142. const std::string& auth_code,
  143. int max_retries,
  144. GaiaOAuthClient::Delegate* delegate) {
  145. std::string post_body =
  146. "code=" + base::EscapeUrlEncodedData(auth_code, true) + "&client_id=" +
  147. base::EscapeUrlEncodedData(oauth_client_info.client_id, true) +
  148. "&client_secret=" +
  149. base::EscapeUrlEncodedData(oauth_client_info.client_secret, true) +
  150. "&redirect_uri=" +
  151. base::EscapeUrlEncodedData(oauth_client_info.redirect_uri, true) +
  152. "&grant_type=authorization_code";
  153. net::MutableNetworkTrafficAnnotationTag traffic_annotation(
  154. net::DefineNetworkTrafficAnnotation("gaia_oauth_client_get_tokens", R"(
  155. semantics {
  156. sender: "OAuth 2.0 calls"
  157. description:
  158. "This request exchanges an authorization code for an OAuth 2.0 "
  159. "refresh token and an OAuth 2.0 access token."
  160. trigger:
  161. "This request is triggered when a Chrome service requires an "
  162. "access token and a refresh token (e.g. Cloud Print, Chrome Remote "
  163. "Desktop etc.) See https://developers.google.com/identity/protocols"
  164. "/OAuth2 for more information about the Google implementation of "
  165. "the OAuth 2.0 protocol."
  166. data:
  167. "The Google console client ID and client secret of the caller, the "
  168. "OAuth authorization code and the redirect URI."
  169. destination: GOOGLE_OWNED_SERVICE
  170. }
  171. policy {
  172. cookies_allowed: NO
  173. setting:
  174. "This feature cannot be disabled in settings, but if the user "
  175. "signs out of Chrome, this request would not be made."
  176. chrome_policy {
  177. SigninAllowed {
  178. policy_options {mode: MANDATORY}
  179. SigninAllowed: false
  180. }
  181. }
  182. })"));
  183. MakeRequest(TOKENS_FROM_AUTH_CODE,
  184. GURL(GaiaUrls::GetInstance()->oauth2_token_url()), post_body,
  185. /* authorization_header = */ std::string(),
  186. /* http_method_override_header = */ std::string(), max_retries,
  187. delegate, traffic_annotation);
  188. }
  189. void GaiaOAuthClient::Core::RefreshToken(
  190. const OAuthClientInfo& oauth_client_info,
  191. const std::string& refresh_token,
  192. const std::vector<std::string>& scopes,
  193. int max_retries,
  194. GaiaOAuthClient::Delegate* delegate) {
  195. std::string post_body =
  196. "refresh_token=" + base::EscapeUrlEncodedData(refresh_token, true) +
  197. "&client_id=" +
  198. base::EscapeUrlEncodedData(oauth_client_info.client_id, true) +
  199. "&client_secret=" +
  200. base::EscapeUrlEncodedData(oauth_client_info.client_secret, true) +
  201. "&grant_type=refresh_token";
  202. if (!scopes.empty()) {
  203. std::string scopes_string = base::JoinString(scopes, " ");
  204. post_body += "&scope=" + base::EscapeUrlEncodedData(scopes_string, true);
  205. }
  206. net::MutableNetworkTrafficAnnotationTag traffic_annotation(
  207. net::DefineNetworkTrafficAnnotation("gaia_oauth_client_refresh_token", R"(
  208. semantics {
  209. sender: "OAuth 2.0 calls"
  210. description:
  211. "This request fetches a fresh access token that can be used to "
  212. "authenticate an API call to a Google web endpoint."
  213. trigger:
  214. "This is called whenever the caller needs a fresh OAuth 2.0 access "
  215. "token."
  216. data:
  217. "The OAuth 2.0 refresh token, the Google console client ID and "
  218. "client secret of the caller, and optionally the scopes of the API "
  219. "for which the access token should be authorized."
  220. destination: GOOGLE_OWNED_SERVICE
  221. }
  222. policy {
  223. cookies_allowed: NO
  224. setting:
  225. "This feature cannot be disabled in settings, but if the user "
  226. "signs out of Chrome, this request would not be made."
  227. chrome_policy {
  228. SigninAllowed {
  229. policy_options {mode: MANDATORY}
  230. SigninAllowed: false
  231. }
  232. }
  233. })"));
  234. MakeRequest(REFRESH_TOKEN, GURL(GaiaUrls::GetInstance()->oauth2_token_url()),
  235. post_body,
  236. /* authorization_header = */ std::string(),
  237. /* http_method_override_header = */ std::string(), max_retries,
  238. delegate, traffic_annotation);
  239. }
  240. void GaiaOAuthClient::Core::GetUserEmail(const std::string& oauth_access_token,
  241. int max_retries,
  242. Delegate* delegate) {
  243. GetUserInfoImpl(USER_EMAIL, oauth_access_token, max_retries, delegate);
  244. }
  245. void GaiaOAuthClient::Core::GetUserId(const std::string& oauth_access_token,
  246. int max_retries,
  247. Delegate* delegate) {
  248. GetUserInfoImpl(USER_ID, oauth_access_token, max_retries, delegate);
  249. }
  250. void GaiaOAuthClient::Core::GetUserInfo(const std::string& oauth_access_token,
  251. int max_retries,
  252. Delegate* delegate) {
  253. GetUserInfoImpl(USER_INFO, oauth_access_token, max_retries, delegate);
  254. }
  255. void GaiaOAuthClient::Core::GetUserInfoImpl(
  256. RequestType type,
  257. const std::string& oauth_access_token,
  258. int max_retries,
  259. Delegate* delegate) {
  260. net::MutableNetworkTrafficAnnotationTag traffic_annotation(
  261. net::DefineNetworkTrafficAnnotation("gaia_oauth_client_get_user_info", R"(
  262. semantics {
  263. sender: "OAuth 2.0 calls"
  264. description:
  265. "This request is used to fetch profile information about the user, "
  266. "like the email, the ID of the account, the full name, and the "
  267. "profile picture."
  268. trigger:
  269. "The main trigger for this request is in the AccountTrackerService "
  270. "that fetches the user info soon after the user signs in."
  271. data:
  272. "The OAuth 2.0 access token of the account."
  273. destination: GOOGLE_OWNED_SERVICE
  274. }
  275. policy {
  276. cookies_allowed: NO
  277. setting:
  278. "This feature cannot be disabled in settings, but if the user "
  279. "signs out of Chrome, this request would not be made."
  280. chrome_policy {
  281. SigninAllowed {
  282. policy_options {mode: MANDATORY}
  283. SigninAllowed: false
  284. }
  285. }
  286. })"));
  287. std::string auth = "OAuth " + oauth_access_token;
  288. MakeRequest(type, GaiaUrls::GetInstance()->oauth_user_info_url(),
  289. /* post_body = */ std::string(), auth,
  290. /* http_method_override_header = */ std::string(), max_retries,
  291. delegate, traffic_annotation);
  292. }
  293. void GaiaOAuthClient::Core::GetTokenInfo(const std::string& qualifier,
  294. const std::string& query,
  295. int max_retries,
  296. Delegate* delegate) {
  297. std::string post_body =
  298. qualifier + "=" + base::EscapeUrlEncodedData(query, true);
  299. net::MutableNetworkTrafficAnnotationTag traffic_annotation(
  300. net::DefineNetworkTrafficAnnotation("gaia_oauth_client_get_token_info",
  301. R"(
  302. semantics {
  303. sender: "OAuth 2.0 calls"
  304. description:
  305. "This request fetches information about an OAuth 2.0 access token. "
  306. "The response is a dictionary of response values. The provided "
  307. "access token may have any scope, and basic results will be "
  308. "returned: issued_to, audience, scope, expires_in, access_type. In "
  309. "addition, if the https://www.googleapis.com/auth/userinfo.email "
  310. "scope is present, the email and verified_email fields will be "
  311. "returned. If the https://www.googleapis.com/auth/userinfo.profile "
  312. "scope is present, the user_id field will be returned."
  313. trigger:
  314. "This is triggered after a Google account is added to the browser. "
  315. "It it also triggered after each successful fetch of an OAuth 2.0 "
  316. "access token."
  317. data: "The OAuth 2.0 access token."
  318. destination: GOOGLE_OWNED_SERVICE
  319. }
  320. policy {
  321. cookies_allowed: NO
  322. setting:
  323. "This feature cannot be disabled in settings, but if the user "
  324. "signs out of Chrome, this request would not be made."
  325. chrome_policy {
  326. SigninAllowed {
  327. policy_options {mode: MANDATORY}
  328. SigninAllowed: false
  329. }
  330. }
  331. })"));
  332. MakeRequest(TOKEN_INFO,
  333. GURL(GaiaUrls::GetInstance()->oauth2_token_info_url()), post_body,
  334. /* authorization_header = */ std::string(),
  335. /* http_method_override_header = */ std::string(), max_retries,
  336. delegate, traffic_annotation);
  337. }
  338. void GaiaOAuthClient::Core::GetAccountCapabilities(
  339. const std::string& oauth_access_token,
  340. const std::vector<std::string>& capabilities_names,
  341. int max_retries,
  342. Delegate* delegate) {
  343. DCHECK(!capabilities_names.empty());
  344. std::string post_body =
  345. base::StrCat({"names=", base::EscapeUrlEncodedData(
  346. *capabilities_names.begin(), true)});
  347. for (auto it = capabilities_names.begin() + 1; it != capabilities_names.end();
  348. ++it) {
  349. base::StrAppend(&post_body,
  350. {"&names=", base::EscapeUrlEncodedData(*it, true)});
  351. }
  352. std::string auth = base::StrCat({"Bearer ", oauth_access_token});
  353. net::MutableNetworkTrafficAnnotationTag traffic_annotation(
  354. net::DefineNetworkTrafficAnnotation(
  355. "gaia_oauth_client_get_account_capabilities",
  356. R"(
  357. semantics {
  358. sender: "OAuth 2.0 calls"
  359. description:
  360. "This request is used to fetch account capabilities. Capabilities "
  361. "provide information about state and features of Gaia accounts."
  362. trigger:
  363. "AccountTrackerService fetches account capabilities soon after the "
  364. "user signs in. Afterwards, AccountTrackerService periodically "
  365. "triggers this request to keep account capabilities up to date for "
  366. "existing accounts."
  367. data:
  368. "The OAuth 2.0 access token of the account and a predefined list "
  369. "of capabilities to fetch."
  370. destination: GOOGLE_OWNED_SERVICE
  371. }
  372. policy {
  373. cookies_allowed: NO
  374. setting:
  375. "This feature cannot be disabled in settings, but if the user "
  376. "signs out of Chrome, this request would not be made."
  377. chrome_policy {
  378. SigninAllowed {
  379. SigninAllowed: false
  380. }
  381. }
  382. })"));
  383. MakeRequest(ACCOUNT_CAPABILITIES,
  384. GURL(GaiaUrls::GetInstance()->account_capabilities_url()),
  385. post_body, auth, /*http_method_override_header=*/"GET",
  386. max_retries, delegate, traffic_annotation);
  387. }
  388. void GaiaOAuthClient::Core::MakeRequest(
  389. RequestType type,
  390. const GURL& url,
  391. std::string post_body,
  392. std::string authorization_header,
  393. std::string http_method_override_header,
  394. int max_retries,
  395. GaiaOAuthClient::Delegate* delegate,
  396. const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) {
  397. DCHECK_EQ(request_type_, NO_PENDING_REQUEST);
  398. request_type_ = type;
  399. delegate_ = delegate;
  400. num_retries_ = 0;
  401. max_retries_ = max_retries;
  402. url_ = url;
  403. traffic_annotation_ = traffic_annotation;
  404. post_body_ = std::move(post_body);
  405. authorization_header_ = std::move(authorization_header);
  406. http_method_override_header_ = std::move(http_method_override_header);
  407. SendRequest();
  408. }
  409. void GaiaOAuthClient::Core::SendRequest() {
  410. if (backoff_entry_.ShouldRejectRequest()) {
  411. base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
  412. FROM_HERE,
  413. base::BindOnce(&GaiaOAuthClient::Core::SendRequestImpl,
  414. weak_ptr_factory_.GetWeakPtr()),
  415. backoff_entry_.GetTimeUntilRelease());
  416. } else {
  417. SendRequestImpl();
  418. }
  419. }
  420. void GaiaOAuthClient::Core::SendRequestImpl() {
  421. DCHECK(!request_.get()) << "Tried to fetch two things at once!";
  422. auto resource_request = std::make_unique<network::ResourceRequest>();
  423. resource_request->url = url_;
  424. resource_request->method = post_body_.empty() ? "GET" : "POST";
  425. resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit;
  426. if (!authorization_header_.empty())
  427. resource_request->headers.SetHeader("Authorization", authorization_header_);
  428. if (!http_method_override_header_.empty()) {
  429. resource_request->headers.SetHeader("X-HTTP-Method-Override",
  430. http_method_override_header_);
  431. }
  432. request_ = network::SimpleURLLoader::Create(
  433. std::move(resource_request),
  434. static_cast<net::NetworkTrafficAnnotationTag>(traffic_annotation_));
  435. if (!post_body_.empty()) {
  436. request_->AttachStringForUpload(post_body_,
  437. "application/x-www-form-urlencoded");
  438. }
  439. // Retry is implemented internally.
  440. request_->SetRetryOptions(0, network::SimpleURLLoader::RETRY_NEVER);
  441. request_->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
  442. url_loader_factory_.get(),
  443. // Unretained(this) is safe since |this| owns |request_|, and its deletion
  444. // will cancel the callback.
  445. base::BindOnce(&GaiaOAuthClient::Core::OnURLLoadComplete,
  446. base::Unretained(this)));
  447. }
  448. void GaiaOAuthClient::Core::OnURLLoadComplete(
  449. std::unique_ptr<std::string> body) {
  450. bool should_retry = false;
  451. base::WeakPtr<GaiaOAuthClient::Core> weak_this =
  452. weak_ptr_factory_.GetWeakPtr();
  453. // HandleResponse() may delete |this| if it assigns |should_retry| == false.
  454. HandleResponse(std::move(body), &should_retry);
  455. if (should_retry) {
  456. num_retries_++;
  457. backoff_entry_.InformOfRequest(false);
  458. SendRequest();
  459. } else {
  460. if (weak_this)
  461. backoff_entry_.InformOfRequest(true);
  462. }
  463. }
  464. void GaiaOAuthClient::Core::HandleResponse(std::unique_ptr<std::string> body,
  465. bool* should_retry_request) {
  466. *should_retry_request = false;
  467. // Move ownership of the request fetcher into a local scoped_ptr which
  468. // will be nuked when we're done handling the request.
  469. std::unique_ptr<network::SimpleURLLoader> source = std::move(request_);
  470. int response_code = -1;
  471. if (source->ResponseInfo() && source->ResponseInfo()->headers)
  472. response_code = source->ResponseInfo()->headers->response_code();
  473. // HTTP_BAD_REQUEST means the arguments are invalid. HTTP_UNAUTHORIZED means
  474. // the access or refresh token is invalid. No point retrying. We are
  475. // done here.
  476. if (response_code == net::HTTP_BAD_REQUEST ||
  477. response_code == net::HTTP_UNAUTHORIZED) {
  478. delegate_->OnOAuthError();
  479. return;
  480. }
  481. std::unique_ptr<base::DictionaryValue> response_dict;
  482. if (response_code == net::HTTP_OK && body) {
  483. std::string data = std::move(*body);
  484. std::unique_ptr<base::Value> message_value =
  485. base::JSONReader::ReadDeprecated(data);
  486. if (message_value.get() && message_value->is_dict()) {
  487. response_dict.reset(
  488. static_cast<base::DictionaryValue*>(message_value.release()));
  489. }
  490. }
  491. if (!response_dict.get()) {
  492. // If we don't have an access token yet and the the error was not
  493. // RC_BAD_REQUEST, we may need to retry.
  494. if ((max_retries_ != -1) && (num_retries_ >= max_retries_)) {
  495. // Retry limit reached. Give up.
  496. request_type_ = NO_PENDING_REQUEST;
  497. delegate_->OnNetworkError(response_code);
  498. } else {
  499. *should_retry_request = true;
  500. }
  501. return;
  502. }
  503. RequestType type = request_type_;
  504. request_type_ = NO_PENDING_REQUEST;
  505. switch (type) {
  506. case USER_EMAIL: {
  507. std::string email;
  508. response_dict->GetString("email", &email);
  509. delegate_->OnGetUserEmailResponse(email);
  510. break;
  511. }
  512. case USER_ID: {
  513. std::string id;
  514. response_dict->GetString("id", &id);
  515. delegate_->OnGetUserIdResponse(id);
  516. break;
  517. }
  518. case USER_INFO: {
  519. delegate_->OnGetUserInfoResponse(std::move(response_dict));
  520. break;
  521. }
  522. case TOKEN_INFO: {
  523. delegate_->OnGetTokenInfoResponse(std::move(response_dict));
  524. break;
  525. }
  526. case TOKENS_FROM_AUTH_CODE:
  527. case REFRESH_TOKEN: {
  528. std::string access_token;
  529. std::string refresh_token;
  530. int expires_in_seconds = 0;
  531. response_dict->GetString(kAccessTokenValue, &access_token);
  532. response_dict->GetString(kRefreshTokenValue, &refresh_token);
  533. response_dict->GetInteger(kExpiresInValue, &expires_in_seconds);
  534. if (access_token.empty()) {
  535. delegate_->OnOAuthError();
  536. return;
  537. }
  538. if (type == REFRESH_TOKEN) {
  539. delegate_->OnRefreshTokenResponse(access_token, expires_in_seconds);
  540. } else {
  541. delegate_->OnGetTokensResponse(refresh_token,
  542. access_token,
  543. expires_in_seconds);
  544. }
  545. break;
  546. }
  547. case ACCOUNT_CAPABILITIES: {
  548. delegate_->OnGetAccountCapabilitiesResponse(std::move(response_dict));
  549. break;
  550. }
  551. case NO_PENDING_REQUEST:
  552. NOTREACHED();
  553. }
  554. }
  555. GaiaOAuthClient::GaiaOAuthClient(
  556. scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) {
  557. core_ = new Core(std::move(url_loader_factory));
  558. }
  559. GaiaOAuthClient::~GaiaOAuthClient() {
  560. }
  561. void GaiaOAuthClient::GetTokensFromAuthCode(
  562. const OAuthClientInfo& oauth_client_info,
  563. const std::string& auth_code,
  564. int max_retries,
  565. Delegate* delegate) {
  566. return core_->GetTokensFromAuthCode(oauth_client_info,
  567. auth_code,
  568. max_retries,
  569. delegate);
  570. }
  571. void GaiaOAuthClient::RefreshToken(
  572. const OAuthClientInfo& oauth_client_info,
  573. const std::string& refresh_token,
  574. const std::vector<std::string>& scopes,
  575. int max_retries,
  576. Delegate* delegate) {
  577. return core_->RefreshToken(oauth_client_info,
  578. refresh_token,
  579. scopes,
  580. max_retries,
  581. delegate);
  582. }
  583. void GaiaOAuthClient::GetUserEmail(const std::string& access_token,
  584. int max_retries,
  585. Delegate* delegate) {
  586. return core_->GetUserEmail(access_token, max_retries, delegate);
  587. }
  588. void GaiaOAuthClient::GetUserId(const std::string& access_token,
  589. int max_retries,
  590. Delegate* delegate) {
  591. return core_->GetUserId(access_token, max_retries, delegate);
  592. }
  593. void GaiaOAuthClient::GetUserInfo(const std::string& access_token,
  594. int max_retries,
  595. Delegate* delegate) {
  596. return core_->GetUserInfo(access_token, max_retries, delegate);
  597. }
  598. void GaiaOAuthClient::GetTokenInfo(const std::string& access_token,
  599. int max_retries,
  600. Delegate* delegate) {
  601. return core_->GetTokenInfo("access_token", access_token, max_retries,
  602. delegate);
  603. }
  604. void GaiaOAuthClient::GetTokenHandleInfo(const std::string& token_handle,
  605. int max_retries,
  606. Delegate* delegate) {
  607. return core_->GetTokenInfo("token_handle", token_handle, max_retries,
  608. delegate);
  609. }
  610. void GaiaOAuthClient::GetAccountCapabilities(
  611. const std::string& oauth_access_token,
  612. const std::vector<std::string>& capabilities_names,
  613. int max_retries,
  614. Delegate* delegate) {
  615. return core_->GetAccountCapabilities(oauth_access_token, capabilities_names,
  616. max_retries, delegate);
  617. }
  618. } // namespace gaia