com.google.firebase.auth.GetTokenResult Java Examples

The following examples show how to use com.google.firebase.auth.GetTokenResult. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Util.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Nullable
public static String getCurrentAuthToken(@Nullable InternalAuthProvider authProvider) {
  try {
    String token = null;

    if (authProvider != null) {
      Task<GetTokenResult> pendingResult = authProvider.getAccessToken(false);
      GetTokenResult result =
          Tasks.await(pendingResult, MAXIMUM_TOKEN_WAIT_TIME_MS, TimeUnit.MILLISECONDS);
      token = result.getToken();
    }

    if (!TextUtils.isEmpty(token)) {
      return token;
    } else {
      Log.w(TAG, "no auth token for request");
    }
  } catch (ExecutionException | InterruptedException | TimeoutException e) {
    Log.e(TAG, "error getting token " + e);
  }
  return null;
}
 
Example #2
Source File: FirebaseAuthRxWrapper.java    From outlay with Apache License 2.0 6 votes vote down vote up
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);
            }
        });
    });
}
 
Example #3
Source File: RxFirebaseUser.java    From rxfirebase with Apache License 2.0 6 votes vote down vote up
/**
 * @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();
        }
    });
}
 
Example #4
Source File: FirebaseAuthCredentialsProvider.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized Task<String> getToken() {
  boolean doForceRefresh = forceRefresh;
  forceRefresh = false;
  Task<GetTokenResult> res = authProvider.getAccessToken(doForceRefresh);

  // Take note of the current value of the tokenCounter so that this method can fail (with a
  // FirebaseFirestoreException) if there is a token change while the request is outstanding.
  final int savedCounter = tokenCounter;
  return res.continueWithTask(
      Executors.DIRECT_EXECUTOR,
      task -> {
        synchronized (this) {
          // Cancel the request since the token changed while the request was outstanding so the
          // response is potentially for a previous user (which user, we can't be sure).
          if (savedCounter != tokenCounter) {
            Logger.debug(LOG_TAG, "getToken aborted due to token change");
            return getToken();
          }

          if (task.isSuccessful()) {
            return Tasks.forResult(task.getResult().getToken());
          } else {
            return Tasks.forException(task.getException());
          }
        }
      });
}
 
Example #5
Source File: ConversationListFragment.java    From chat21-android-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
    public void onSwipeMenuClosed(Conversation conversation, int position) {
//        Log.i(TAG, "onSwipeMenuClosed: conversation: " + conversation.toString() + " position: " + position);

        String conversationId = conversation.getConversationId();
        boolean isSupportConversation = conversationId.startsWith("support-group");

        // retrieve the firebase user token
        GetTokenResult task = FirebaseAuth.getInstance().getCurrentUser().getIdToken(false).getResult();
        String token = task.getToken();

        // create the header parameters
        Map<String, String> headerParams = new HashMap<>();
        headerParams.put("Accept", "application/json");
        headerParams.put("Content-Type", "application/json");
        headerParams.put("Authorization", "Bearer " + token);

        if (!isSupportConversation) {
            // is not support group
            deleteConversation(conversationId, headerParams);
        } else {
            // is support group
            closeSupportGroup(conversationId, headerParams);
        }

        // NOTE: dismiss is not necessary because the view disappears when the conversation is removed
//        // dismiss the swipe menu
//        conversationsListAdapter.dismissSwipeMenu(recyclerViewConversations, position);
//        conversationsListAdapter.notifyItemChanged(position);
    }
 
Example #6
Source File: GoogleSignInActivity.java    From endpoints-samples with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #7
Source File: FacebookLoginActivity.java    From endpoints-samples with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #8
Source File: FirestackAuth.java    From react-native-firestack with MIT License 5 votes vote down vote up
@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);
          }
        });
}
 
Example #9
Source File: FirestackAuth.java    From react-native-firestack with MIT License 5 votes vote down vote up
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);
              }
            });
    }
 
Example #10
Source File: FirebaseAuthHelper.java    From q-municate-android with Apache License 2.0 5 votes vote down vote up
public void refreshInternalFirebaseToken(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 IllegalStateException("Current Firebase User is null"));
        return;
    }

    threadPoolExecutor.execute(new Runnable() {
        @Override
        public void run() {
            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());
                    }
                }
            });
        }
    });
}