Re-subimission of https://codereview.chromium.org/1041213003/
[chromium-blink-merge.git] / google_apis / gaia / gaia_oauth_client.cc
blobadb8c6fdcaf2562de8bf5ef9a111f08de57bd448
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_oauth_client.h"
7 #include "base/json/json_reader.h"
8 #include "base/logging.h"
9 #include "base/memory/scoped_ptr.h"
10 #include "base/strings/string_util.h"
11 #include "base/values.h"
12 #include "google_apis/gaia/gaia_urls.h"
13 #include "net/base/escape.h"
14 #include "net/base/load_flags.h"
15 #include "net/http/http_status_code.h"
16 #include "net/url_request/url_fetcher.h"
17 #include "net/url_request/url_fetcher_delegate.h"
18 #include "net/url_request/url_request_context_getter.h"
19 #include "url/gurl.h"
21 namespace {
22 const char kAccessTokenValue[] = "access_token";
23 const char kRefreshTokenValue[] = "refresh_token";
24 const char kExpiresInValue[] = "expires_in";
27 namespace gaia {
29 // Use a non-zero number, so unit tests can differentiate the URLFetcher used by
30 // this class from other fetchers (most other code just hardcodes the ID to 0).
31 const int GaiaOAuthClient::kUrlFetcherId = 17109006;
33 class GaiaOAuthClient::Core
34 : public base::RefCountedThreadSafe<GaiaOAuthClient::Core>,
35 public net::URLFetcherDelegate {
36 public:
37 Core(net::URLRequestContextGetter* request_context_getter)
38 : num_retries_(0),
39 request_context_getter_(request_context_getter),
40 delegate_(NULL),
41 request_type_(NO_PENDING_REQUEST) {
44 void GetTokensFromAuthCode(const OAuthClientInfo& oauth_client_info,
45 const std::string& auth_code,
46 int max_retries,
47 GaiaOAuthClient::Delegate* delegate);
48 void RefreshToken(const OAuthClientInfo& oauth_client_info,
49 const std::string& refresh_token,
50 const std::vector<std::string>& scopes,
51 int max_retries,
52 GaiaOAuthClient::Delegate* delegate);
53 void GetUserEmail(const std::string& oauth_access_token,
54 int max_retries,
55 Delegate* delegate);
56 void GetUserId(const std::string& oauth_access_token,
57 int max_retries,
58 Delegate* delegate);
59 void GetUserInfo(const std::string& oauth_access_token,
60 int max_retries,
61 Delegate* delegate);
62 void GetTokenInfo(const std::string& qualifier,
63 const std::string& query,
64 int max_retries,
65 Delegate* delegate);
67 // net::URLFetcherDelegate implementation.
68 void OnURLFetchComplete(const net::URLFetcher* source) override;
70 private:
71 friend class base::RefCountedThreadSafe<Core>;
73 enum RequestType {
74 NO_PENDING_REQUEST,
75 TOKENS_FROM_AUTH_CODE,
76 REFRESH_TOKEN,
77 TOKEN_INFO,
78 USER_EMAIL,
79 USER_ID,
80 USER_INFO,
83 ~Core() override {}
85 void GetUserInfoImpl(RequestType type,
86 const std::string& oauth_access_token,
87 int max_retries,
88 Delegate* delegate);
89 void MakeGaiaRequest(const GURL& url,
90 const std::string& post_body,
91 int max_retries,
92 GaiaOAuthClient::Delegate* delegate);
93 void HandleResponse(const net::URLFetcher* source,
94 bool* should_retry_request);
96 int num_retries_;
97 scoped_refptr<net::URLRequestContextGetter> request_context_getter_;
98 GaiaOAuthClient::Delegate* delegate_;
99 scoped_ptr<net::URLFetcher> request_;
100 RequestType request_type_;
103 void GaiaOAuthClient::Core::GetTokensFromAuthCode(
104 const OAuthClientInfo& oauth_client_info,
105 const std::string& auth_code,
106 int max_retries,
107 GaiaOAuthClient::Delegate* delegate) {
108 DCHECK_EQ(request_type_, NO_PENDING_REQUEST);
109 request_type_ = TOKENS_FROM_AUTH_CODE;
110 std::string post_body =
111 "code=" + net::EscapeUrlEncodedData(auth_code, true) +
112 "&client_id=" + net::EscapeUrlEncodedData(oauth_client_info.client_id,
113 true) +
114 "&client_secret=" +
115 net::EscapeUrlEncodedData(oauth_client_info.client_secret, true) +
116 "&redirect_uri=" +
117 net::EscapeUrlEncodedData(oauth_client_info.redirect_uri, true) +
118 "&grant_type=authorization_code";
119 MakeGaiaRequest(GURL(GaiaUrls::GetInstance()->oauth2_token_url()),
120 post_body, max_retries, delegate);
123 void GaiaOAuthClient::Core::RefreshToken(
124 const OAuthClientInfo& oauth_client_info,
125 const std::string& refresh_token,
126 const std::vector<std::string>& scopes,
127 int max_retries,
128 GaiaOAuthClient::Delegate* delegate) {
129 DCHECK_EQ(request_type_, NO_PENDING_REQUEST);
130 request_type_ = REFRESH_TOKEN;
131 std::string post_body =
132 "refresh_token=" + net::EscapeUrlEncodedData(refresh_token, true) +
133 "&client_id=" + net::EscapeUrlEncodedData(oauth_client_info.client_id,
134 true) +
135 "&client_secret=" +
136 net::EscapeUrlEncodedData(oauth_client_info.client_secret, true) +
137 "&grant_type=refresh_token";
139 if (!scopes.empty()) {
140 std::string scopes_string = JoinString(scopes, ' ');
141 post_body += "&scope=" + net::EscapeUrlEncodedData(scopes_string, true);
144 MakeGaiaRequest(GURL(GaiaUrls::GetInstance()->oauth2_token_url()),
145 post_body, max_retries, delegate);
148 void GaiaOAuthClient::Core::GetUserEmail(const std::string& oauth_access_token,
149 int max_retries,
150 Delegate* delegate) {
151 GetUserInfoImpl(USER_EMAIL, oauth_access_token, max_retries, delegate);
154 void GaiaOAuthClient::Core::GetUserId(const std::string& oauth_access_token,
155 int max_retries,
156 Delegate* delegate) {
157 GetUserInfoImpl(USER_ID, oauth_access_token, max_retries, delegate);
160 void GaiaOAuthClient::Core::GetUserInfo(const std::string& oauth_access_token,
161 int max_retries,
162 Delegate* delegate) {
163 GetUserInfoImpl(USER_INFO, oauth_access_token, max_retries, delegate);
166 void GaiaOAuthClient::Core::GetUserInfoImpl(
167 RequestType type,
168 const std::string& oauth_access_token,
169 int max_retries,
170 Delegate* delegate) {
171 DCHECK_EQ(request_type_, NO_PENDING_REQUEST);
172 DCHECK(!request_.get());
173 request_type_ = type;
174 delegate_ = delegate;
175 num_retries_ = 0;
176 request_.reset(net::URLFetcher::Create(
177 kUrlFetcherId, GURL(GaiaUrls::GetInstance()->oauth_user_info_url()),
178 net::URLFetcher::GET, this));
179 request_->SetRequestContext(request_context_getter_.get());
180 request_->AddExtraRequestHeader("Authorization: OAuth " + oauth_access_token);
181 request_->SetMaxRetriesOn5xx(max_retries);
182 request_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
183 net::LOAD_DO_NOT_SAVE_COOKIES);
185 // Fetchers are sometimes cancelled because a network change was detected,
186 // especially at startup and after sign-in on ChromeOS. Retrying once should
187 // be enough in those cases; let the fetcher retry up to 3 times just in case.
188 // http://crbug.com/163710
189 request_->SetAutomaticallyRetryOnNetworkChanges(3);
190 request_->Start();
193 void GaiaOAuthClient::Core::GetTokenInfo(const std::string& qualifier,
194 const std::string& query,
195 int max_retries,
196 Delegate* delegate) {
197 DCHECK_EQ(request_type_, NO_PENDING_REQUEST);
198 DCHECK(!request_.get());
199 request_type_ = TOKEN_INFO;
200 std::string post_body =
201 qualifier + "=" + net::EscapeUrlEncodedData(query, true);
202 MakeGaiaRequest(GURL(GaiaUrls::GetInstance()->oauth2_token_info_url()),
203 post_body,
204 max_retries,
205 delegate);
208 void GaiaOAuthClient::Core::MakeGaiaRequest(
209 const GURL& url,
210 const std::string& post_body,
211 int max_retries,
212 GaiaOAuthClient::Delegate* delegate) {
213 DCHECK(!request_.get()) << "Tried to fetch two things at once!";
214 delegate_ = delegate;
215 num_retries_ = 0;
216 request_.reset(net::URLFetcher::Create(
217 kUrlFetcherId, url, net::URLFetcher::POST, this));
218 request_->SetRequestContext(request_context_getter_.get());
219 request_->SetUploadData("application/x-www-form-urlencoded", post_body);
220 request_->SetMaxRetriesOn5xx(max_retries);
221 request_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
222 net::LOAD_DO_NOT_SAVE_COOKIES);
223 // See comment on SetAutomaticallyRetryOnNetworkChanges() above.
224 request_->SetAutomaticallyRetryOnNetworkChanges(3);
225 request_->Start();
228 // URLFetcher::Delegate implementation.
229 void GaiaOAuthClient::Core::OnURLFetchComplete(
230 const net::URLFetcher* source) {
231 bool should_retry = false;
232 HandleResponse(source, &should_retry);
233 if (should_retry) {
234 // Explicitly call ReceivedContentWasMalformed() to ensure the current
235 // request gets counted as a failure for calculation of the back-off
236 // period. If it was already a failure by status code, this call will
237 // be ignored.
238 request_->ReceivedContentWasMalformed();
239 num_retries_++;
240 // We must set our request_context_getter_ again because
241 // URLFetcher::Core::RetryOrCompleteUrlFetch resets it to NULL...
242 request_->SetRequestContext(request_context_getter_.get());
243 request_->Start();
247 void GaiaOAuthClient::Core::HandleResponse(
248 const net::URLFetcher* source,
249 bool* should_retry_request) {
250 // Move ownership of the request fetcher into a local scoped_ptr which
251 // will be nuked when we're done handling the request, unless we need
252 // to retry, in which case ownership will be returned to request_.
253 scoped_ptr<net::URLFetcher> old_request = request_.Pass();
254 DCHECK_EQ(source, old_request.get());
256 // HTTP_BAD_REQUEST means the arguments are invalid. HTTP_UNAUTHORIZED means
257 // the access or refresh token is invalid. No point retrying. We are
258 // done here.
259 int response_code = source->GetResponseCode();
260 if (response_code == net::HTTP_BAD_REQUEST ||
261 response_code == net::HTTP_UNAUTHORIZED) {
262 delegate_->OnOAuthError();
263 return;
266 scoped_ptr<base::DictionaryValue> response_dict;
267 if (source->GetResponseCode() == net::HTTP_OK) {
268 std::string data;
269 source->GetResponseAsString(&data);
270 scoped_ptr<base::Value> message_value(base::JSONReader::Read(data));
271 if (message_value.get() &&
272 message_value->IsType(base::Value::TYPE_DICTIONARY)) {
273 response_dict.reset(
274 static_cast<base::DictionaryValue*>(message_value.release()));
278 if (!response_dict.get()) {
279 // If we don't have an access token yet and the the error was not
280 // RC_BAD_REQUEST, we may need to retry.
281 if ((source->GetMaxRetriesOn5xx() != -1) &&
282 (num_retries_ >= source->GetMaxRetriesOn5xx())) {
283 // Retry limit reached. Give up.
284 delegate_->OnNetworkError(source->GetResponseCode());
285 } else {
286 request_ = old_request.Pass();
287 *should_retry_request = true;
289 return;
292 RequestType type = request_type_;
293 request_type_ = NO_PENDING_REQUEST;
295 switch (type) {
296 case USER_EMAIL: {
297 std::string email;
298 response_dict->GetString("email", &email);
299 delegate_->OnGetUserEmailResponse(email);
300 break;
303 case USER_ID: {
304 std::string id;
305 response_dict->GetString("id", &id);
306 delegate_->OnGetUserIdResponse(id);
307 break;
310 case USER_INFO: {
311 delegate_->OnGetUserInfoResponse(response_dict.Pass());
312 break;
315 case TOKEN_INFO: {
316 delegate_->OnGetTokenInfoResponse(response_dict.Pass());
317 break;
320 case TOKENS_FROM_AUTH_CODE:
321 case REFRESH_TOKEN: {
322 std::string access_token;
323 std::string refresh_token;
324 int expires_in_seconds = 0;
325 response_dict->GetString(kAccessTokenValue, &access_token);
326 response_dict->GetString(kRefreshTokenValue, &refresh_token);
327 response_dict->GetInteger(kExpiresInValue, &expires_in_seconds);
329 if (access_token.empty()) {
330 delegate_->OnOAuthError();
331 return;
334 if (type == REFRESH_TOKEN) {
335 delegate_->OnRefreshTokenResponse(access_token, expires_in_seconds);
336 } else {
337 delegate_->OnGetTokensResponse(refresh_token,
338 access_token,
339 expires_in_seconds);
341 break;
344 default:
345 NOTREACHED();
349 GaiaOAuthClient::GaiaOAuthClient(net::URLRequestContextGetter* context_getter) {
350 core_ = new Core(context_getter);
353 GaiaOAuthClient::~GaiaOAuthClient() {
356 void GaiaOAuthClient::GetTokensFromAuthCode(
357 const OAuthClientInfo& oauth_client_info,
358 const std::string& auth_code,
359 int max_retries,
360 Delegate* delegate) {
361 return core_->GetTokensFromAuthCode(oauth_client_info,
362 auth_code,
363 max_retries,
364 delegate);
367 void GaiaOAuthClient::RefreshToken(
368 const OAuthClientInfo& oauth_client_info,
369 const std::string& refresh_token,
370 const std::vector<std::string>& scopes,
371 int max_retries,
372 Delegate* delegate) {
373 return core_->RefreshToken(oauth_client_info,
374 refresh_token,
375 scopes,
376 max_retries,
377 delegate);
380 void GaiaOAuthClient::GetUserEmail(const std::string& access_token,
381 int max_retries,
382 Delegate* delegate) {
383 return core_->GetUserEmail(access_token, max_retries, delegate);
386 void GaiaOAuthClient::GetUserId(const std::string& access_token,
387 int max_retries,
388 Delegate* delegate) {
389 return core_->GetUserId(access_token, max_retries, delegate);
392 void GaiaOAuthClient::GetUserInfo(const std::string& access_token,
393 int max_retries,
394 Delegate* delegate) {
395 return core_->GetUserInfo(access_token, max_retries, delegate);
398 void GaiaOAuthClient::GetTokenInfo(const std::string& access_token,
399 int max_retries,
400 Delegate* delegate) {
401 return core_->GetTokenInfo("access_token", access_token, max_retries,
402 delegate);
405 void GaiaOAuthClient::GetTokenHandleInfo(const std::string& token_handle,
406 int max_retries,
407 Delegate* delegate) {
408 return core_->GetTokenInfo("token_handle", token_handle, max_retries,
409 delegate);
412 } // namespace gaia