1 // Copyright 2013 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 "chrome/browser/signin/oauth2_token_service_delegate_android.h"
7 #include "base/android/jni_android.h"
8 #include "base/android/jni_array.h"
9 #include "base/android/jni_string.h"
10 #include "base/bind.h"
11 #include "base/logging.h"
12 #include "chrome/browser/profiles/profile_android.h"
13 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
14 #include "chrome/browser/sync/profile_sync_service_android.h"
15 #include "content/public/browser/browser_thread.h"
16 #include "google_apis/gaia/gaia_auth_util.h"
17 #include "google_apis/gaia/oauth2_access_token_fetcher.h"
18 #include "jni/OAuth2TokenService_jni.h"
20 using base::android::AttachCurrentThread
;
21 using base::android::ConvertJavaStringToUTF8
;
22 using base::android::ConvertUTF8ToJavaString
;
23 using base::android::ScopedJavaLocalRef
;
24 using content::BrowserThread
;
28 // Callback from FetchOAuth2TokenWithUsername().
30 // - the error, or NONE if the token fetch was successful.
31 // - the OAuth2 access token.
32 // - the expiry time of the token (may be null, indicating that the expiry
34 typedef base::Callback
<void(const GoogleServiceAuthError
&,
36 const base::Time
&)> FetchOAuth2TokenCallback
;
38 class AndroidAccessTokenFetcher
: public OAuth2AccessTokenFetcher
{
40 AndroidAccessTokenFetcher(OAuth2AccessTokenConsumer
* consumer
,
41 const std::string
& account_id
);
42 ~AndroidAccessTokenFetcher() override
;
44 // Overrides from OAuth2AccessTokenFetcher:
45 void Start(const std::string
& client_id
,
46 const std::string
& client_secret
,
47 const std::vector
<std::string
>& scopes
) override
;
48 void CancelRequest() override
;
50 // Handles an access token response.
51 void OnAccessTokenResponse(const GoogleServiceAuthError
& error
,
52 const std::string
& access_token
,
53 const base::Time
& expiration_time
);
56 std::string
CombineScopes(const std::vector
<std::string
>& scopes
);
58 std::string account_id_
;
59 bool request_was_cancelled_
;
60 base::WeakPtrFactory
<AndroidAccessTokenFetcher
> weak_factory_
;
62 DISALLOW_COPY_AND_ASSIGN(AndroidAccessTokenFetcher
);
65 AndroidAccessTokenFetcher::AndroidAccessTokenFetcher(
66 OAuth2AccessTokenConsumer
* consumer
,
67 const std::string
& account_id
)
68 : OAuth2AccessTokenFetcher(consumer
),
69 account_id_(account_id
),
70 request_was_cancelled_(false),
74 AndroidAccessTokenFetcher::~AndroidAccessTokenFetcher() {
77 void AndroidAccessTokenFetcher::Start(const std::string
& client_id
,
78 const std::string
& client_secret
,
79 const std::vector
<std::string
>& scopes
) {
80 JNIEnv
* env
= AttachCurrentThread();
81 std::string scope
= CombineScopes(scopes
);
82 ScopedJavaLocalRef
<jstring
> j_username
=
83 ConvertUTF8ToJavaString(env
, account_id_
);
84 ScopedJavaLocalRef
<jstring
> j_scope
= ConvertUTF8ToJavaString(env
, scope
);
85 scoped_ptr
<FetchOAuth2TokenCallback
> heap_callback(
86 new FetchOAuth2TokenCallback(
87 base::Bind(&AndroidAccessTokenFetcher::OnAccessTokenResponse
,
88 weak_factory_
.GetWeakPtr())));
90 // Call into Java to get a new token.
91 Java_OAuth2TokenService_getOAuth2AuthToken(
92 env
, base::android::GetApplicationContext(), j_username
.obj(),
93 j_scope
.obj(), reinterpret_cast<intptr_t>(heap_callback
.release()));
96 void AndroidAccessTokenFetcher::CancelRequest() {
97 request_was_cancelled_
= true;
100 void AndroidAccessTokenFetcher::OnAccessTokenResponse(
101 const GoogleServiceAuthError
& error
,
102 const std::string
& access_token
,
103 const base::Time
& expiration_time
) {
104 if (request_was_cancelled_
) {
105 // Ignore the callback if the request was cancelled.
108 if (error
.state() == GoogleServiceAuthError::NONE
) {
109 FireOnGetTokenSuccess(access_token
, expiration_time
);
111 FireOnGetTokenFailure(error
);
116 std::string
AndroidAccessTokenFetcher::CombineScopes(
117 const std::vector
<std::string
>& scopes
) {
118 // The Android AccountManager supports multiple scopes separated by a space:
119 // https://code.google.com/p/google-api-java-client/wiki/OAuth2#Android
121 for (std::vector
<std::string
>::const_iterator it
= scopes
.begin();
122 it
!= scopes
.end(); ++it
) {
132 bool OAuth2TokenServiceDelegateAndroid::is_testing_profile_
= false;
134 OAuth2TokenServiceDelegateAndroid::OAuth2TokenServiceDelegateAndroid() {
135 DVLOG(1) << "OAuth2TokenServiceDelegateAndroid::ctor";
136 JNIEnv
* env
= AttachCurrentThread();
137 base::android::ScopedJavaLocalRef
<jobject
> local_java_ref
=
138 Java_OAuth2TokenService_create(env
, reinterpret_cast<intptr_t>(this));
139 java_ref_
.Reset(env
, local_java_ref
.obj());
142 OAuth2TokenServiceDelegateAndroid::~OAuth2TokenServiceDelegateAndroid() {
146 jobject
OAuth2TokenServiceDelegateAndroid::GetForProfile(
149 jobject j_profile_android
) {
150 Profile
* profile
= ProfileAndroid::FromProfileAndroid(j_profile_android
);
151 ProfileOAuth2TokenService
* service
=
152 ProfileOAuth2TokenServiceFactory::GetForProfile(profile
);
153 OAuth2TokenServiceDelegate
* delegate
= service
->GetDelegate();
154 return static_cast<OAuth2TokenServiceDelegateAndroid
*>(delegate
)
158 static jobject
GetForProfile(JNIEnv
* env
,
160 jobject j_profile_android
) {
161 return OAuth2TokenServiceDelegateAndroid::GetForProfile(env
, clazz
,
165 void OAuth2TokenServiceDelegateAndroid::Initialize() {
166 DVLOG(1) << "OAuth2TokenServiceDelegateAndroid::Initialize";
167 if (!is_testing_profile_
) {
168 Java_OAuth2TokenService_validateAccounts(
169 AttachCurrentThread(), java_ref_
.obj(),
170 base::android::GetApplicationContext(), JNI_TRUE
);
174 bool OAuth2TokenServiceDelegateAndroid::RefreshTokenIsAvailable(
175 const std::string
& account_id
) const {
176 JNIEnv
* env
= AttachCurrentThread();
177 ScopedJavaLocalRef
<jstring
> j_account_id
=
178 ConvertUTF8ToJavaString(env
, account_id
);
179 jboolean refresh_token_is_available
=
180 Java_OAuth2TokenService_hasOAuth2RefreshToken(
181 env
, base::android::GetApplicationContext(), j_account_id
.obj());
182 return refresh_token_is_available
== JNI_TRUE
;
185 void OAuth2TokenServiceDelegateAndroid::UpdateAuthError(
186 const std::string
& account_id
,
187 const GoogleServiceAuthError
& error
) {
188 // TODO(rogerta): do we need to update anything, or does the system handle it?
191 std::vector
<std::string
> OAuth2TokenServiceDelegateAndroid::GetAccounts() {
192 std::vector
<std::string
> accounts
;
193 JNIEnv
* env
= AttachCurrentThread();
194 ScopedJavaLocalRef
<jobjectArray
> j_accounts
=
195 Java_OAuth2TokenService_getAccounts(
196 env
, base::android::GetApplicationContext());
197 // TODO(fgorski): We may decide to filter out some of the accounts.
198 base::android::AppendJavaStringArrayToStringVector(env
, j_accounts
.obj(),
203 std::vector
<std::string
>
204 OAuth2TokenServiceDelegateAndroid::GetSystemAccounts() {
205 std::vector
<std::string
> accounts
;
206 JNIEnv
* env
= AttachCurrentThread();
207 ScopedJavaLocalRef
<jobjectArray
> j_accounts
=
208 Java_OAuth2TokenService_getSystemAccounts(
209 env
, base::android::GetApplicationContext());
210 base::android::AppendJavaStringArrayToStringVector(env
, j_accounts
.obj(),
215 OAuth2AccessTokenFetcher
*
216 OAuth2TokenServiceDelegateAndroid::CreateAccessTokenFetcher(
217 const std::string
& account_id
,
218 net::URLRequestContextGetter
* getter
,
219 OAuth2AccessTokenConsumer
* consumer
) {
220 ValidateAccountId(account_id
);
221 return new AndroidAccessTokenFetcher(consumer
, account_id
);
224 void OAuth2TokenServiceDelegateAndroid::InvalidateAccessToken(
225 const std::string
& account_id
,
226 const std::string
& client_id
,
227 const OAuth2TokenService::ScopeSet
& scopes
,
228 const std::string
& access_token
) {
229 ValidateAccountId(account_id
);
230 JNIEnv
* env
= AttachCurrentThread();
231 ScopedJavaLocalRef
<jstring
> j_access_token
=
232 ConvertUTF8ToJavaString(env
, access_token
);
233 Java_OAuth2TokenService_invalidateOAuth2AuthToken(
234 env
, base::android::GetApplicationContext(), j_access_token
.obj());
237 void OAuth2TokenServiceDelegateAndroid::ValidateAccounts(
240 jstring j_current_acc
,
241 jboolean j_force_notifications
) {
242 std::string signed_in_account
;
243 DVLOG(1) << "OAuth2TokenServiceDelegateAndroid::ValidateAccounts from java";
245 signed_in_account
= ConvertJavaStringToUTF8(env
, j_current_acc
);
246 if (!signed_in_account
.empty())
247 signed_in_account
= gaia::CanonicalizeEmail(signed_in_account
);
248 ValidateAccounts(signed_in_account
, j_force_notifications
!= JNI_FALSE
);
251 void OAuth2TokenServiceDelegateAndroid::ValidateAccounts(
252 const std::string
& signed_in_account
,
253 bool force_notifications
) {
254 std::vector
<std::string
> prev_ids
= GetAccounts();
255 std::vector
<std::string
> curr_ids
= GetSystemAccounts();
256 std::vector
<std::string
> refreshed_ids
;
257 std::vector
<std::string
> revoked_ids
;
259 // Canonicalize system accounts. |prev_ids| is already done.
260 for (size_t i
= 0; i
< curr_ids
.size(); ++i
)
261 curr_ids
[i
] = gaia::CanonicalizeEmail(curr_ids
[i
]);
262 for (size_t i
= 0; i
< prev_ids
.size(); ++i
)
263 ValidateAccountId(prev_ids
[i
]);
265 DVLOG(1) << "OAuth2TokenServiceDelegateAndroid::ValidateAccounts:"
266 << " sigined_in_account=" << signed_in_account
267 << " prev_ids=" << prev_ids
.size() << " curr_ids=" << curr_ids
.size()
268 << " force=" << (force_notifications
? "true" : "false");
270 if (!ValidateAccounts(signed_in_account
, prev_ids
, curr_ids
, refreshed_ids
,
271 revoked_ids
, force_notifications
)) {
275 ScopedBatchChange
batch(this);
277 JNIEnv
* env
= AttachCurrentThread();
278 ScopedJavaLocalRef
<jobjectArray
> java_accounts(
279 base::android::ToJavaArrayOfStrings(env
, curr_ids
));
280 Java_OAuth2TokenService_saveStoredAccounts(
281 env
, base::android::GetApplicationContext(), java_accounts
.obj());
283 for (std::vector
<std::string
>::iterator it
= refreshed_ids
.begin();
284 it
!= refreshed_ids
.end(); it
++) {
285 FireRefreshTokenAvailable(*it
);
288 for (std::vector
<std::string
>::iterator it
= revoked_ids
.begin();
289 it
!= revoked_ids
.end(); it
++) {
290 FireRefreshTokenRevoked(*it
);
294 bool OAuth2TokenServiceDelegateAndroid::ValidateAccounts(
295 const std::string
& signed_in_account
,
296 const std::vector
<std::string
>& prev_account_ids
,
297 const std::vector
<std::string
>& curr_account_ids
,
298 std::vector
<std::string
>& refreshed_ids
,
299 std::vector
<std::string
>& revoked_ids
,
300 bool force_notifications
) {
301 if (std::find(curr_account_ids
.begin(), curr_account_ids
.end(),
302 signed_in_account
) != curr_account_ids
.end()) {
303 // Test to see if an account is removed from the Android AccountManager.
304 // If so, invoke FireRefreshTokenRevoked to notify the reconcilor.
305 for (std::vector
<std::string
>::const_iterator it
= prev_account_ids
.begin();
306 it
!= prev_account_ids
.end(); it
++) {
307 if (*it
== signed_in_account
)
310 if (std::find(curr_account_ids
.begin(), curr_account_ids
.end(), *it
) ==
311 curr_account_ids
.end()) {
312 DVLOG(1) << "OAuth2TokenServiceDelegateAndroid::ValidateAccounts:"
313 << "revoked=" << *it
;
314 revoked_ids
.push_back(*it
);
318 if (force_notifications
||
319 std::find(prev_account_ids
.begin(), prev_account_ids
.end(),
320 signed_in_account
) == prev_account_ids
.end()) {
321 // Always fire the primary signed in account first.
322 DVLOG(1) << "OAuth2TokenServiceDelegateAndroid::ValidateAccounts:"
323 << "refreshed=" << signed_in_account
;
324 refreshed_ids
.push_back(signed_in_account
);
327 for (std::vector
<std::string
>::const_iterator it
= curr_account_ids
.begin();
328 it
!= curr_account_ids
.end(); it
++) {
329 if (*it
!= signed_in_account
) {
330 if (force_notifications
||
331 std::find(prev_account_ids
.begin(), prev_account_ids
.end(), *it
) ==
332 prev_account_ids
.end()) {
333 DVLOG(1) << "OAuth2TokenServiceDelegateAndroid::ValidateAccounts:"
334 << "refreshed=" << *it
;
335 refreshed_ids
.push_back(*it
);
341 // Currently signed in account does not any longer exist among accounts on
342 // system together with all other accounts.
343 if (std::find(prev_account_ids
.begin(), prev_account_ids
.end(),
344 signed_in_account
) != prev_account_ids
.end()) {
345 DVLOG(1) << "OAuth2TokenServiceDelegateAndroid::ValidateAccounts:"
346 << "revoked=" << signed_in_account
;
347 revoked_ids
.push_back(signed_in_account
);
349 for (std::vector
<std::string
>::const_iterator it
= prev_account_ids
.begin();
350 it
!= prev_account_ids
.end(); it
++) {
351 if (*it
== signed_in_account
)
353 DVLOG(1) << "OAuth2TokenServiceDelegateAndroid::ValidateAccounts:"
354 << "revoked=" << *it
;
355 revoked_ids
.push_back(*it
);
361 void OAuth2TokenServiceDelegateAndroid::FireRefreshTokenAvailableFromJava(
364 const jstring account_name
) {
365 std::string account_id
= ConvertJavaStringToUTF8(env
, account_name
);
366 // Notify native observers.
367 FireRefreshTokenAvailable(account_id
);
370 void OAuth2TokenServiceDelegateAndroid::FireRefreshTokenAvailable(
371 const std::string
& account_id
) {
372 DVLOG(1) << "OAuth2TokenServiceDelegateAndroid::FireRefreshTokenAvailable id="
374 JNIEnv
* env
= AttachCurrentThread();
375 ScopedJavaLocalRef
<jstring
> account_name
=
376 ConvertUTF8ToJavaString(env
, account_id
);
377 Java_OAuth2TokenService_notifyRefreshTokenAvailable(env
, java_ref_
.obj(),
379 OAuth2TokenServiceDelegate::FireRefreshTokenAvailable(account_id
);
382 void OAuth2TokenServiceDelegateAndroid::FireRefreshTokenRevokedFromJava(
385 const jstring account_name
) {
386 std::string account_id
= ConvertJavaStringToUTF8(env
, account_name
);
387 // Notify native observers.
388 FireRefreshTokenRevoked(account_id
);
391 void OAuth2TokenServiceDelegateAndroid::FireRefreshTokenRevoked(
392 const std::string
& account_id
) {
393 DVLOG(1) << "OAuth2TokenServiceDelegateAndroid::FireRefreshTokenRevoked id="
395 JNIEnv
* env
= AttachCurrentThread();
396 ScopedJavaLocalRef
<jstring
> account_name
=
397 ConvertUTF8ToJavaString(env
, account_id
);
398 Java_OAuth2TokenService_notifyRefreshTokenRevoked(env
, java_ref_
.obj(),
400 OAuth2TokenServiceDelegate::FireRefreshTokenRevoked(account_id
);
403 void OAuth2TokenServiceDelegateAndroid::FireRefreshTokensLoadedFromJava(
406 // Notify native observers.
407 FireRefreshTokensLoaded();
410 void OAuth2TokenServiceDelegateAndroid::FireRefreshTokensLoaded() {
411 DVLOG(1) << "OAuth2TokenServiceDelegateAndroid::FireRefreshTokensLoaded";
412 JNIEnv
* env
= AttachCurrentThread();
413 Java_OAuth2TokenService_notifyRefreshTokensLoaded(env
, java_ref_
.obj());
414 OAuth2TokenServiceDelegate::FireRefreshTokensLoaded();
417 void OAuth2TokenServiceDelegateAndroid::RevokeAllCredentials() {
418 DVLOG(1) << "OAuth2TokenServiceDelegateAndroid::RevokeAllCredentials";
419 ScopedBatchChange
batch(this);
420 std::vector
<std::string
> accounts
= GetAccounts();
421 for (std::vector
<std::string
>::iterator it
= accounts
.begin();
422 it
!= accounts
.end(); it
++) {
423 FireRefreshTokenRevoked(*it
);
426 // Clear everything on the Java side as well.
427 std::vector
<std::string
> empty
;
428 JNIEnv
* env
= AttachCurrentThread();
429 ScopedJavaLocalRef
<jobjectArray
> java_accounts(
430 base::android::ToJavaArrayOfStrings(env
, empty
));
431 Java_OAuth2TokenService_saveStoredAccounts(
432 env
, base::android::GetApplicationContext(), java_accounts
.obj());
435 // Called from Java when fetching of an OAuth2 token is finished. The
436 // |authToken| param is only valid when |result| is true.
437 void OAuth2TokenFetched(JNIEnv
* env
,
440 jlong nativeCallback
) {
443 token
= ConvertJavaStringToUTF8(env
, authToken
);
444 scoped_ptr
<FetchOAuth2TokenCallback
> heap_callback(
445 reinterpret_cast<FetchOAuth2TokenCallback
*>(nativeCallback
));
446 // Android does not provide enough information to know if the credentials are
447 // wrong, so assume any error is transient by using CONNECTION_FAILED.
448 GoogleServiceAuthError
err(authToken
449 ? GoogleServiceAuthError::NONE
450 : GoogleServiceAuthError::CONNECTION_FAILED
);
451 heap_callback
->Run(err
, token
, base::Time());
455 bool OAuth2TokenServiceDelegateAndroid::Register(JNIEnv
* env
) {
456 return RegisterNativesImpl(env
);