// Copyright (c) 2012 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 "google_apis/gaia/gaia_oauth_client.h" #include "base/json/json_reader.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/values.h" #include "google_apis/gaia/gaia_urls.h" #include "googleurl/src/gurl.h" #include "net/base/escape.h" #include "net/http/http_status_code.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_fetcher_delegate.h" #include "net/url_request/url_request_context_getter.h" namespace { const char kAccessTokenValue[] = "access_token"; const char kRefreshTokenValue[] = "refresh_token"; const char kExpiresInValue[] = "expires_in"; } namespace gaia { class GaiaOAuthClient::Core : public base::RefCountedThreadSafe, public net::URLFetcherDelegate { public: Core(const std::string& gaia_url, net::URLRequestContextGetter* request_context_getter) : gaia_url_(gaia_url), num_retries_(0), request_context_getter_(request_context_getter), delegate_(NULL), request_type_(NO_PENDING_REQUEST) { } void GetTokensFromAuthCode(const OAuthClientInfo& oauth_client_info, const std::string& auth_code, int max_retries, GaiaOAuthClient::Delegate* delegate); void RefreshToken(const OAuthClientInfo& oauth_client_info, const std::string& refresh_token, int max_retries, GaiaOAuthClient::Delegate* delegate); void GetUserInfo(const std::string& oauth_access_token, int max_retries, Delegate* delegate); // net::URLFetcherDelegate implementation. virtual void OnURLFetchComplete(const net::URLFetcher* source) OVERRIDE; private: friend class base::RefCountedThreadSafe; enum RequestType { NO_PENDING_REQUEST, TOKENS_FROM_AUTH_CODE, REFRESH_TOKEN, USER_INFO, }; virtual ~Core() {} void MakeGaiaRequest(const std::string& post_body, int max_retries, GaiaOAuthClient::Delegate* delegate); void HandleResponse(const net::URLFetcher* source, bool* should_retry_request); GURL gaia_url_; int num_retries_; scoped_refptr request_context_getter_; GaiaOAuthClient::Delegate* delegate_; scoped_ptr request_; RequestType request_type_; }; void GaiaOAuthClient::Core::GetTokensFromAuthCode( const OAuthClientInfo& oauth_client_info, const std::string& auth_code, int max_retries, GaiaOAuthClient::Delegate* delegate) { DCHECK_EQ(request_type_, NO_PENDING_REQUEST); request_type_ = TOKENS_FROM_AUTH_CODE; std::string post_body = "code=" + net::EscapeUrlEncodedData(auth_code, true) + "&client_id=" + net::EscapeUrlEncodedData(oauth_client_info.client_id, true) + "&client_secret=" + net::EscapeUrlEncodedData(oauth_client_info.client_secret, true) + "&redirect_uri=" + net::EscapeUrlEncodedData(oauth_client_info.redirect_uri, true) + "&grant_type=authorization_code"; MakeGaiaRequest(post_body, max_retries, delegate); } void GaiaOAuthClient::Core::RefreshToken( const OAuthClientInfo& oauth_client_info, const std::string& refresh_token, int max_retries, GaiaOAuthClient::Delegate* delegate) { DCHECK_EQ(request_type_, NO_PENDING_REQUEST); request_type_ = REFRESH_TOKEN; std::string post_body = "refresh_token=" + net::EscapeUrlEncodedData(refresh_token, true) + "&client_id=" + net::EscapeUrlEncodedData(oauth_client_info.client_id, true) + "&client_secret=" + net::EscapeUrlEncodedData(oauth_client_info.client_secret, true) + "&grant_type=refresh_token"; MakeGaiaRequest(post_body, max_retries, delegate); } void GaiaOAuthClient::Core::GetUserInfo(const std::string& oauth_access_token, int max_retries, Delegate* delegate) { DCHECK_EQ(request_type_, NO_PENDING_REQUEST); DCHECK(!request_.get()); request_type_ = USER_INFO; delegate_ = delegate; num_retries_ = 0; request_.reset(net::URLFetcher::Create( 0, GURL(GaiaUrls::GetInstance()->oauth_user_info_url()), net::URLFetcher::GET, this)); request_->SetRequestContext(request_context_getter_); request_->AddExtraRequestHeader( "Authorization: OAuth " + oauth_access_token); request_->SetMaxRetriesOn5xx(max_retries); // Fetchers are sometimes cancelled because a network change was detected, // especially at startup and after sign-in on ChromeOS. Retrying once should // be enough in those cases; let the fetcher retry up to 3 times just in case. // http://crbug.com/163710 request_->SetAutomaticallyRetryOnNetworkChanges(3); request_->Start(); } void GaiaOAuthClient::Core::MakeGaiaRequest( const std::string& post_body, int max_retries, GaiaOAuthClient::Delegate* delegate) { DCHECK(!request_.get()) << "Tried to fetch two things at once!"; delegate_ = delegate; num_retries_ = 0; request_.reset(net::URLFetcher::Create( 0, gaia_url_, net::URLFetcher::POST, this)); request_->SetRequestContext(request_context_getter_); request_->SetUploadData("application/x-www-form-urlencoded", post_body); request_->SetMaxRetriesOn5xx(max_retries); // See comment on SetAutomaticallyRetryOnNetworkChanges() above. request_->SetAutomaticallyRetryOnNetworkChanges(3); request_->Start(); } // URLFetcher::Delegate implementation. void GaiaOAuthClient::Core::OnURLFetchComplete( const net::URLFetcher* source) { bool should_retry = false; HandleResponse(source, &should_retry); if (should_retry) { // Explicitly call ReceivedContentWasMalformed() to ensure the current // request gets counted as a failure for calculation of the back-off // period. If it was already a failure by status code, this call will // be ignored. request_->ReceivedContentWasMalformed(); num_retries_++; // We must set our request_context_getter_ again because // URLFetcher::Core::RetryOrCompleteUrlFetch resets it to NULL... request_->SetRequestContext(request_context_getter_); request_->Start(); } } void GaiaOAuthClient::Core::HandleResponse( const net::URLFetcher* source, bool* should_retry_request) { // Keep the URLFetcher object in case we need to reuse it. scoped_ptr old_request = request_.Pass(); DCHECK_EQ(source, old_request.get()); // RC_BAD_REQUEST means the arguments are invalid. No point retrying. We are // done here. if (source->GetResponseCode() == net::HTTP_BAD_REQUEST) { delegate_->OnOAuthError(); return; } scoped_ptr response_dict; if (source->GetResponseCode() == net::HTTP_OK) { std::string data; source->GetResponseAsString(&data); scoped_ptr message_value(base::JSONReader::Read(data)); if (message_value.get() && message_value->IsType(Value::TYPE_DICTIONARY)) { response_dict.reset( static_cast(message_value.release())); } } if (!response_dict.get()) { // If we don't have an access token yet and the the error was not // RC_BAD_REQUEST, we may need to retry. if ((source->GetMaxRetriesOn5xx() != -1) && (num_retries_ > source->GetMaxRetriesOn5xx())) { // Retry limit reached. Give up. delegate_->OnNetworkError(source->GetResponseCode()); } else { request_ = old_request.Pass(); *should_retry_request = true; } return; } RequestType type = request_type_; request_type_ = NO_PENDING_REQUEST; switch (type) { case USER_INFO: { std::string email; response_dict->GetString("email", &email); delegate_->OnGetUserInfoResponse(email); break; } case TOKENS_FROM_AUTH_CODE: case REFRESH_TOKEN: { std::string access_token; std::string refresh_token; int expires_in_seconds = 0; response_dict->GetString(kAccessTokenValue, &access_token); response_dict->GetString(kRefreshTokenValue, &refresh_token); response_dict->GetInteger(kExpiresInValue, &expires_in_seconds); if (access_token.empty()) { delegate_->OnOAuthError(); return; } if (type == REFRESH_TOKEN) { delegate_->OnRefreshTokenResponse(access_token, expires_in_seconds); } else { delegate_->OnGetTokensResponse(refresh_token, access_token, expires_in_seconds); } break; } default: NOTREACHED(); } } GaiaOAuthClient::GaiaOAuthClient(const std::string& gaia_url, net::URLRequestContextGetter* context_getter) { core_ = new Core(gaia_url, context_getter); } GaiaOAuthClient::~GaiaOAuthClient() { } void GaiaOAuthClient::GetTokensFromAuthCode( const OAuthClientInfo& oauth_client_info, const std::string& auth_code, int max_retries, Delegate* delegate) { return core_->GetTokensFromAuthCode(oauth_client_info, auth_code, max_retries, delegate); } void GaiaOAuthClient::RefreshToken(const OAuthClientInfo& oauth_client_info, const std::string& refresh_token, int max_retries, Delegate* delegate) { return core_->RefreshToken(oauth_client_info, refresh_token, max_retries, delegate); } void GaiaOAuthClient::GetUserInfo(const std::string& access_token, int max_retries, Delegate* delegate) { return core_->GetUserInfo(access_token, max_retries, delegate); } } // namespace gaia