private void getIdToken(final boolean forceRefresh, final CallbackContext callbackContext) throws JSONException { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user == null) { callbackContext.error("User is not authorized"); } else { user.getIdToken(forceRefresh) .addOnCompleteListener(cordova.getActivity(), new OnCompleteListener<GetTokenResult>() { @Override public void onComplete(Task<GetTokenResult> task) { if (task.isSuccessful()) { callbackContext.success(task.getResult().getToken()); } else { callbackContext.error(task.getException().getMessage()); } } }); } } }); }
@Override public void subscribe(final SingleEmitter<String> emitter) { OnCompleteListener<GetTokenResult> listener = new OnCompleteListener<GetTokenResult>() { @Override public void onComplete(@NonNull Task<GetTokenResult> task) { if (!task.isSuccessful()) { if (!emitter.isDisposed()) { emitter.onError(task.getException()); } return; } if (!emitter.isDisposed()) { emitter.onSuccess(task.getResult().getToken()); } } }; user.getToken(forceRefresh).addOnCompleteListener(listener); }
public static String getTokenFirebase() { final StringBuilder tokenAux = new StringBuilder(); final CountDownLatch countDownLatch = new CountDownLatch(1); FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { user.getToken(false).addOnCompleteListener(new OnCompleteListener<GetTokenResult>() { @Override public void onComplete(@NonNull Task<GetTokenResult> task) { tokenAux.append(task.getResult().getToken()); countDownLatch.countDown(); } }); try { countDownLatch.await(30L, TimeUnit.SECONDS); return tokenAux.toString(); } catch (InterruptedException ie) { return null; } } return null; }
@Test public void getToken() throws InterruptedException { TestSubscriber<GetTokenResult> testSubscriber = new TestSubscriber<>(); RxFirebaseUser.getToken(mockUser, true) .subscribeOn(Schedulers.immediate()) .subscribe(testSubscriber); testOnSuccessListener.getValue().onSuccess(tokenResult); testOnCompleteListener.getValue().onComplete(mockTokenTask); verify(mockUser).getToken(true); testSubscriber.assertNoErrors(); testSubscriber.assertValueCount(1); testSubscriber.assertReceivedOnNext(Collections.singletonList(tokenResult)); testSubscriber.assertCompleted(); testSubscriber.unsubscribe(); }
public void startLoadingProcess(final Context context) { AppPrefs prefs = new AppPrefs(context); final FirebaseAuth auth = FirebaseAuth.getInstance(); if (auth.getCurrentUser() != null) { auth.getCurrentUser().getIdToken(false).addOnCompleteListener(new OnCompleteListener<GetTokenResult>() { @Override public void onComplete(@NonNull Task<GetTokenResult> task) { if (task.isSuccessful()) { String user = auth.getCurrentUser().getUid(); String email = auth.getCurrentUser().getEmail(); checkIfOld(task.getResult().getToken(), user, context, email); } else { if (task.getException() != null) { showError(task.getException().getLocalizedMessage()); } else { showError("Unable to get user data! Please try again."); } } } }); } else { showError("Something is wrong, please try logging again."); } }
public Observable<String> getUserToken(FirebaseUser firebaseUser) { return Observable.create(subscriber -> { Task<GetTokenResult> task = firebaseUser.getToken(true); task.addOnCompleteListener(resultTask -> { if (task.isSuccessful()) { String token = task.getResult().getToken(); subscriber.onNext(token); subscriber.onCompleted(); } else { Exception e = task.getException(); subscriber.onError(e); } }); }); }
/** * @param user * @param forceRefresh * @return */ @CheckReturnValue @NonNull public static Single<String> getToken(@NonNull final FirebaseUser user, final boolean forceRefresh) { return RxTask.single(new Callable<Task<GetTokenResult>>() { @Override public Task<GetTokenResult> call() throws Exception { return user.getToken(forceRefresh); } }) .map(new Function<GetTokenResult, String>() { @Override public String apply(@NonNull GetTokenResult getTokenResult) throws Exception { return getTokenResult.getToken(); } }); }
public static void getIdTokenForCurrentUser(final RequestFirebaseIdTokenCallback callback) { if (getCurrentFirebaseUser() == null) { Log.v(TAG, "Getting Token error. ERROR = Current Firebse User is null"); SharedHelper.getInstance().saveFirebaseToken(null); callback.onError(new NullPointerException("Current Firebse User is null")); return; } getCurrentFirebaseUser().getIdToken(false).addOnCompleteListener(new OnCompleteListener<GetTokenResult>() { public void onComplete(@NonNull Task<GetTokenResult> task) { if (task.isSuccessful()) { String accessToken = task.getResult().getToken(); Log.v(TAG, "Token got successfully. TOKEN = " + accessToken); SharedHelper.getInstance().saveFirebaseToken(accessToken); callback.onSuccess(accessToken); } else { Log.v(TAG, "Getting Token error. ERROR = " + task.getException().getMessage()); callback.onError(task.getException()); } } }); }
/** * Fetches a Firebase Auth ID Token for the user; useful when authenticating against your own backend. * * @param firebaseUser current firebaseUser instance. * @param forceRefresh force to refresh the token ID. * @return a {@link Maybe} which emits an {@link GetTokenResult} if success. */ @NonNull public static Maybe<GetTokenResult> getToken(@NonNull final FirebaseUser firebaseUser, final boolean forceRefresh) { return Maybe.create(new MaybeOnSubscribe<GetTokenResult>() { @Override public void subscribe(MaybeEmitter<GetTokenResult> emitter) throws Exception { RxHandler.assignOnTask(emitter, firebaseUser.getToken(forceRefresh)); } }); }
@NonNull public static Observable<GetTokenResult> getToken(@NonNull final FirebaseUser firebaseUser, final boolean forceRefresh) { return Observable.create(new Observable.OnSubscribe<GetTokenResult>() { @Override public void call(final Subscriber<? super GetTokenResult> subscriber) { RxHandler.assignOnTask(subscriber, firebaseUser.getToken(forceRefresh)); } }); }
private void updateUI(FirebaseUser user) { hideProgressDialog(); if (user != null) { mStatusTextView.setText(getString(R.string.google_status_fmt, user.getEmail())); mDetailTextView.setText(getString(R.string.firebase_status_fmt, user.getUid())); findViewById(R.id.sign_in_button).setVisibility(View.GONE); findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE); user.getToken(true).addOnSuccessListener(new OnSuccessListener<GetTokenResult>() { @Override public void onSuccess(GetTokenResult getTokenResult) { makeEndpointsRequest(getTokenResult.getToken()); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { alert("Failed to get token from Firebase."); } }); } else { mStatusTextView.setText(R.string.signed_out); mDetailTextView.setText(null); mResponseTextView.setText(""); findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE); findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE); } }
private void updateUI(FirebaseUser user) { hideProgressDialog(); if (user != null) { mStatusTextView.setText(getString(R.string.facebook_status_fmt, user.getDisplayName())); mDetailTextView.setText(getString(R.string.firebase_status_fmt, user.getUid())); findViewById(R.id.button_facebook_login).setVisibility(View.GONE); findViewById(R.id.button_facebook_signout).setVisibility(View.VISIBLE); user.getToken(true).addOnSuccessListener(new OnSuccessListener<GetTokenResult>() { @Override public void onSuccess(GetTokenResult getTokenResult) { makeEndpointsRequest(getTokenResult.getToken()); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { alert("Failed to get token from Firebase."); } }); } else { mStatusTextView.setText(R.string.signed_out); mDetailTextView.setText(null); mResponseTextView.setText(""); findViewById(R.id.button_facebook_login).setVisibility(View.VISIBLE); findViewById(R.id.button_facebook_signout).setVisibility(View.GONE); } }
/** * Load the user's auth token if it is available. */ private void loadAuthToken() { final FirebaseUser auth = FirebaseAuth.getInstance().getCurrentUser(); if(auth != null) { try { final GetTokenResult result = Tasks.await(auth.getIdToken(true)); mAuthToken = result.getToken(); } catch(ExecutionException | InterruptedException e) { Log.e(TAG, "Failed to obtain authorization token", e); } } }
@ReactMethod public void getToken(final Callback callback) { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); user.getToken(true) .addOnCompleteListener(new OnCompleteListener<GetTokenResult>() { @Override public void onComplete(@NonNull Task<GetTokenResult> task) { if (task.isSuccessful()) { String token = task.getResult().getToken(); WritableMap resp = Arguments.createMap(); resp.putString("status", "complete"); resp.putString("token", token); callback.invoke(null, resp); } else { WritableMap err = Arguments.createMap(); err.putInt("errorCode", ERROR_FETCHING_TOKEN); err.putString("errorMessage", task.getException().getMessage()); callback.invoke(err); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception ex) { userExceptionCallback(ex, callback); } }); }
public void userCallback(FirebaseUser passedUser, final Callback callback) { if (passedUser == null) { mAuth = FirebaseAuth.getInstance(); this.user = mAuth.getCurrentUser(); } else { this.user = passedUser; } this.user.getToken(false).addOnCompleteListener(new OnCompleteListener<GetTokenResult>() { @Override public void onComplete(@NonNull Task<GetTokenResult> task) { WritableMap msgMap = Arguments.createMap(); WritableMap userMap = getUserMap(); boolean authenticated = false; if (FirestackAuthModule.this.user != null) { final String token = task.getResult().getToken(); userMap.putString("token", token); authenticated = true; } msgMap.putMap("user", userMap); msgMap.putBoolean("authenticated", authenticated); callback.invoke(null, msgMap); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception ex) { userExceptionCallback(ex, callback); } }); }
/** * Fetches a Firebase Auth ID Token for the user; useful when authenticating against your own backend. * * @param firebaseUser current firebaseUser instance. * @param forceRefresh force to refresh the token ID. * @return a {@link Maybe} which emits an {@link GetTokenResult} if success. */ @NonNull public static Maybe<GetTokenResult> getIdToken(@NonNull final FirebaseUser firebaseUser, final boolean forceRefresh) { return Maybe.create(new MaybeOnSubscribe<GetTokenResult>() { @Override public void subscribe(MaybeEmitter<GetTokenResult> emitter) throws Exception { RxHandler.assignOnTask(emitter, firebaseUser.getIdToken(forceRefresh)); } }); }
@Test public void getToken() throws Exception { TestObserver<GetTokenResult> userTestObserver = RxFirebaseUser.getIdToken(firebaseUser, ANY_FORCE_REFRESH_VALUE).test(); testOnSuccessListener.getValue().onSuccess(getTokenResult); testOnCompleteListener.getValue().onComplete(getTokenResultTask); verify(firebaseUser).getIdToken(ANY_FORCE_REFRESH_VALUE); userTestObserver.assertComplete() .assertNoErrors() .assertValueCount(1) .dispose(); }
@Test public void getTokenError() throws Exception { TestObserver<GetTokenResult> userTestObserver = RxFirebaseUser.getIdToken(firebaseUser, ANY_FORCE_REFRESH_VALUE).test(); testOnFailureListener.getValue().onFailure(EXCEPTION); verify(firebaseUser).getIdToken(ANY_FORCE_REFRESH_VALUE); userTestObserver.assertError(EXCEPTION) .dispose(); }
public static void refreshInternalFirebaseToken() { Log.i(TAG, "refreshInternalFirebaseToken() synchronously start " + new Date(System.currentTimeMillis())); final CountDownLatch countDownLatch = new CountDownLatch(1); getCurrentFirebaseUser().getIdToken(false).addOnCompleteListener(new Executor(){ @Override public void execute(@NonNull Runnable command) { command.run(); } }, new OnCompleteListener<GetTokenResult>() { public void onComplete(@NonNull Task<GetTokenResult> task) { if (task.isSuccessful()) { String accessToken = task.getResult().getToken(); Log.v(TAG, "Token got successfully. TOKEN = " + accessToken); SharedHelper.getInstance().saveFirebaseToken(accessToken); } else { Log.v(TAG, "Getting Token error. ERROR = " + task.getException().getMessage()); } countDownLatch.countDown(); } }); try { countDownLatch.await(ConstsCore.HTTP_TIMEOUT_IN_SECONDS, TimeUnit.MILLISECONDS); Log.i(TAG, "refreshInternalFirebaseToken() synchronously DONE " + new Date(System.currentTimeMillis())); } catch (InterruptedException e) { Log.i(TAG, "refreshInternalFirebaseToken() synchronously DONE_BY_TIMEOUT " + new Date(System.currentTimeMillis())); } }