Java Code Examples for com.google.firebase.auth.FirebaseAuth

The following examples show how to use com.google.firebase.auth.FirebaseAuth. These examples are extracted from open source projects. 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 Project: NITKart   Source File: newUser.java    License: MIT License 6 votes vote down vote up
private void sendVerificationEmail() {
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    user.sendEmailVerification()
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        // Email sent
                        finish();
                    } else {
                        // overridePendingTransition(0, 0);
                        // finish();
                        // overridePendingTransition(0, 0);
                        // startActivity(getIntent());
                        sendVerificationEmail();
                    }
                }
            });
}
 
Example 2
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LOGGER.fine("onCreate");

    final Bundle args = getArguments();
    speakerId = args.getString(ARG_SPEAKER_ID);
    if (Strings.isNullOrEmpty(speakerId)) {
        throw new IllegalArgumentException(ARG_SPEAKER_ID + " can't be null or empty");
    }

    favSessionButtonManager = new FavSessionButtonManager(
        FirebaseDatabase.getInstance(), FirebaseAuth.getInstance(), new MyAuthRequiredListener());

    bus = Singletons.deps.getBus();
}
 
Example 3
Source Project: UberClone   Source File: TripHistory.java    License: MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_trip_history);
    initToolbar();
    initRecyclerView();

    mAuth = FirebaseAuth.getInstance();
    database = FirebaseDatabase.getInstance();
    riderHistory = database.getReference(Common.history_driver);
    listData = new ArrayList<>();
    adapter = new historyAdapter(this, listData, new ClickListener() {
        @Override
        public void onClick(View view, int index) {

        }
    });
    rvHistory.setAdapter(adapter);
    getHistory();
}
 
Example 4
Source Project: social-app-android   Source File: LogoutHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static void signOut(GoogleApiClient mGoogleApiClient, FragmentActivity fragmentActivity) {
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    if (user != null) {
        ProfileInteractor.getInstance(fragmentActivity.getApplicationContext())
                .removeRegistrationToken(FirebaseInstanceId.getInstance().getToken(), user.getUid());

        for (UserInfo profile : user.getProviderData()) {
            String providerId = profile.getProviderId();
            logoutByProvider(providerId, mGoogleApiClient, fragmentActivity);
        }
        logoutFirebase(fragmentActivity.getApplicationContext());
    }

    if (clearImageCacheAsyncTask == null) {
        clearImageCacheAsyncTask = new ClearImageCacheAsyncTask(fragmentActivity.getApplicationContext());
        clearImageCacheAsyncTask.execute();
    }
}
 
Example 5
Source Project: Learning-Resources   Source File: FireResetPassword.java    License: MIT License 6 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.lo_fire_auth_resetpassword);

    mCrdntrlyot = (CoordinatorLayout) findViewById(R.id.cordntrlyot_fireauth_resetpaswrd);
    mTxtinptlyotEmail = (TextInputLayout) findViewById(R.id.txtinputlyot_fireauth_resetpaswrd_email);
    mTxtinptEtEmail = (TextInputEditText) findViewById(R.id.txtinptet_fireauth_resetpaswrd_email);
    mAppcmptbtnSignup = (AppCompatButton) findViewById(R.id.appcmptbtn_fireauth_resetpaswrd);
    mPrgrsbrMain = (ProgressBar) findViewById(R.id.prgrsbr_fireauth_resetpaswrd);

    mFireAuth = FirebaseAuth.getInstance();

    mAppcmptbtnSignup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // Check all field Validation and call API
            checkVldtnCallApi();
        }
    });

}
 
Example 6
Source Project: firebase-admin-java   Source File: FirebaseAuthSnippets.java    License: Apache License 2.0 6 votes vote down vote up
public void generateSignInWithEmailLink() {
  final ActionCodeSettings actionCodeSettings = initActionCodeSettings();
  final String displayName = "Example User";
  // [START sign_in_with_email_link]
  String email = "[email protected]";
  try {
    String link = FirebaseAuth.getInstance().generateSignInWithEmailLink(
        email, actionCodeSettings);
    // Construct email verification template, embed the link and send
    // using custom SMTP server.
    sendCustomPasswordResetEmail(email, displayName, link);
  } catch (FirebaseAuthException e) {
    System.out.println("Error generating email link: " + e.getMessage());
  }
  // [END sign_in_with_email_link]
}
 
Example 7
Source Project: firebase-admin-java   Source File: FirebaseAuthSnippets.java    License: Apache License 2.0 6 votes vote down vote up
@POST
@Path("/profile")
public Response verifySessionCookie(@CookieParam("session") Cookie cookie) {
  String sessionCookie = cookie.getValue();
  try {
    // Verify the session cookie. In this case an additional check is added to detect
    // if the user's Firebase session was revoked, user deleted/disabled, etc.
    final boolean checkRevoked = true;
    FirebaseToken decodedToken = FirebaseAuth.getInstance().verifySessionCookie(
        sessionCookie, checkRevoked);
    return serveContentForUser(decodedToken);
  } catch (FirebaseAuthException e) {
    // Session cookie is unavailable, invalid or revoked. Force user to login.
    return Response.temporaryRedirect(URI.create("/login")).build();
  }
}
 
Example 8
Source Project: snippets-android   Source File: MainActivity.java    License: Apache License 2.0 6 votes vote down vote up
public void taskChaining() {
    // [START task_chaining]
    Task<AuthResult> signInTask = FirebaseAuth.getInstance().signInAnonymously();

    signInTask.continueWithTask(new Continuation<AuthResult, Task<String>>() {
        @Override
        public Task<String> then(@NonNull Task<AuthResult> task) throws Exception {
            // Take the result from the first task and start the second one
            AuthResult result = task.getResult();
            return doSomething(result);
        }
    }).addOnSuccessListener(new OnSuccessListener<String>() {
        @Override
        public void onSuccess(String s) {
            // Chain of tasks completed successfully, got result from last task.
            // ...
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            // One of the tasks in the chain failed with an exception.
            // ...
        }
    });
    // [END task_chaining]
}
 
Example 9
private void handleSignInResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == RC_SIGN_IN) {
        IdpResponse response = IdpResponse.fromResultIntent(data);
        if (response == null) {
            // User pressed back button
            return;
        }
        if (resultCode == RESULT_OK) {
            setStatus("Signed in as " + getUserIdentifier(FirebaseAuth.getInstance()
                    .getCurrentUser()));
        } else if (response.getError().getErrorCode() == ErrorCodes
                .ANONYMOUS_UPGRADE_MERGE_CONFLICT) {
            setStatus("Merge conflict: user already exists.");
            mResolveMergeButton.setEnabled(true);
            mPendingCredential = response.getCredentialForLinking();
        } else {
            Toast.makeText(this, "Auth error, see logs", Toast.LENGTH_SHORT).show();
            Log.w(TAG, "Error: " + response.getError().getMessage(), response.getError());
        }

        updateUI();
    }
}
 
Example 10
Source Project: SnapchatClone   Source File: ChatFragment.java    License: MIT License 6 votes vote down vote up
private void listenForData() {
    DatabaseReference receiveDB = FirebaseDatabase.getInstance().getReference().child("users")
            .child(FirebaseAuth.getInstance().getUid()).child("received");

    receiveDB.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                for (DataSnapshot snap : dataSnapshot.getChildren()) {
                    getUserInfo(snap.getKey());
                }
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}
 
Example 11
Source Project: gdx-fireapp   Source File: AuthTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void signInAnonymously_fail() {
    // Given
    Auth auth = new Auth();
    BiConsumer biConsumer = Mockito.mock(BiConsumer.class);
    Mockito.when(task.isSuccessful()).thenReturn(false);
    Mockito.when(task.getException()).thenReturn(new Exception());
    Mockito.doReturn(task).when(firebaseAuth).signInAnonymously();

    // When
    auth.signInAnonymously()
            .fail(biConsumer);

    // Then
    PowerMockito.verifyStatic(FirebaseAuth.class, VerificationModeFactory.times(1));
    FirebaseAuth.getInstance();
    Mockito.verify(firebaseAuth, VerificationModeFactory.times(1)).signInAnonymously();
    Mockito.verify(task, VerificationModeFactory.times(1)).addOnCompleteListener(Mockito.any(OnCompleteListener.class));
    Mockito.verify(biConsumer, VerificationModeFactory.times(1)).accept(Mockito.nullable(String.class), Mockito.any(Exception.class));
}
 
Example 12
Source Project: Password-Storage   Source File: RegistrationActivity.java    License: MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Fabric.with(this, new Crashlytics());
    setContentView(R.layout.activity_registration);
    auth = FirebaseAuth.getInstance();
    appStatus=new AppStatus(getApplicationContext());
    register = (Button) findViewById(R.id.btn_register);
    existinguser = (Button) findViewById(R.id.existinguser);
    edt_Password = (EditText) findViewById(R.id.edt_Rpassword);
    edt_RePassword = (EditText) findViewById(R.id.edt_RRepassword);
    edt_Email = (EditText) findViewById(R.id.edt_email);
    progressBar=(ProgressBar)findViewById(R.id.progressBar);
    register.setOnClickListener(this);
    existinguser.setOnClickListener(this);
}
 
Example 13
@Nullable
@Override
public View onCreateView(LayoutInflater inflater,
                         @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) {
    binding = DataBindingUtil.inflate(inflater, R.layout.dialog_rating, container, false);
    binding.setHandler((cancel, rate, text) -> {
        if (! cancel) {
            final Rating rating = new Rating(FirebaseAuth.getInstance().getCurrentUser(), rate, text.toString());
            if (mRatingListener != null) {
                mRatingListener.onRating(rating);
            }
        }
        dismiss();
    });
    return binding.getRoot();
}
 
Example 14
Source Project: firebase-android-sdk   Source File: StorageTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void putShouldFailWithNotAuthorized() throws Exception {
  FirebaseAuth auth = FirebaseAuth.getInstance();
  FirebaseStorage storage = FirebaseStorage.getInstance();

  auth.signOut();
  StorageReference blob = storage.getReference("restaurants").child(TestId.create());
  byte[] data = "Google NYC".getBytes(StandardCharsets.UTF_8);

  try {
    Task<?> putTask = blob.putBytes(Arrays.copyOf(data, data.length));
    Throwable failure = Tasks2.waitForFailure(putTask);
    StorageException ex = (StorageException) failure;
    assertThat(ex.getErrorCode()).isEqualTo(StorageException.ERROR_NOT_AUTHORIZED);
  } finally {
    Tasks2.waitBestEffort(blob.delete());
  }
}
 
Example 15
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);
    btnFBLogout = findViewById(R.id.btnlogout);
    tvid = findViewById(R.id.tvId);

    mAuth = FirebaseAuth.getInstance();

    FirebaseUser user = mAuth.getCurrentUser();
    //String id = user.
   // tvid.setText(id);

    btnFBLogout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mAuth.signOut();//firebase
            LoginManager.getInstance().logOut();//facebook
            updateUI();

        }
    });
}
 
Example 16
Source Project: snippets-android   Source File: MainActivity.java    License: Apache License 2.0 6 votes vote down vote up
public void updatePassword() {
    // [START update_password]
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    String newPassword = "SOME-SECURE-PASSWORD";

    user.updatePassword(newPassword)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "User password updated.");
                    }
                }
            });
    // [END update_password]
}
 
Example 17
Source Project: snippets-android   Source File: MainActivity.java    License: Apache License 2.0 6 votes vote down vote up
public void linkAndMerge(AuthCredential credential) {
    FirebaseAuth mAuth = FirebaseAuth.getInstance();

    // [START auth_link_and_merge]
    FirebaseUser prevUser = FirebaseAuth.getInstance().getCurrentUser();
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    FirebaseUser currentUser = task.getResult().getUser();
                    // Merge prevUser and currentUser accounts and data
                    // ...
                }
            });
    // [END auth_link_and_merge]
}
 
Example 18
Source Project: wmn-safety   Source File: SignupActivity.java    License: MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_signup);

    mHelpers = new Helpers(this);
    mFirebaseAuth = FirebaseAuth.getInstance();
    mFirebaseDatabase = FirebaseDatabase.getInstance();

    mEmailText = findViewById(R.id.sign_up_email_tv);
    mNameText = findViewById(R.id.sign_up_name_tv);
    mPhoneText = findViewById(R.id.sign_up_phone_tv);
    mPasswordText = findViewById(R.id.sign_up_password_tv);

    findViewById(R.id.sign_up_button).setOnClickListener(this);
    findViewById(R.id.sign_up_login_tv).setOnClickListener(this);

}
 
Example 19
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
    user = firebaseAuth.getCurrentUser();
    if (user != null) {
        startListeningFavorites();
    }
    else {
        stopListeningFavorites();
    }
}
 
Example 20
Source Project: FirebaseUI-Android   Source File: FirestoreChatActivity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth auth) {
    mSendButton.setEnabled(isSignedIn());
    mMessageEdit.setEnabled(isSignedIn());

    if (isSignedIn()) {
        attachRecyclerViewAdapter();
    } else {
        Toast.makeText(this, R.string.signing_in, Toast.LENGTH_SHORT).show();
        auth.signInAnonymously().addOnCompleteListener(new SignInResultNotifier(this));
    }
}
 
Example 21
/**
 * Persist token to third-party servers.
 *
 * Modify this method to associate the user's FCM InstanceID token with any server-side account
 * maintained by your application.
 *
 * @param token The new token.
 */
private void sendRegistrationToServer(String token) {
    // Add custom implementation, as needed.
    FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    if(firebaseUser != null) {
        FirebaseDatabase.getInstance().getReference()
                .child("users")
                .child(firebaseUser.getUid())
                .child("instanceId")
                .setValue(token);
    }

}
 
Example 22
Source Project: firebase-admin-java   Source File: FirebaseAuthSnippets.java    License: Apache License 2.0 5 votes vote down vote up
public static void setCustomUserClaimsScript() throws FirebaseAuthException {
  // [START set_custom_user_claims_script]
  UserRecord user = FirebaseAuth.getInstance()
      .getUserByEmail("[email protected]");
  // Confirm user is verified.
  if (user.isEmailVerified()) {
    Map<String, Object> claims = new HashMap<>();
    claims.put("admin", true);
    FirebaseAuth.getInstance().setCustomUserClaims(user.getUid(), claims);
  }
  // [END set_custom_user_claims_script]
}
 
Example 23
Source Project: spring-security-firebase   Source File: Application.java    License: MIT License 5 votes vote down vote up
@Bean
public FirebaseAuth firebaseAuth() throws IOException {
	
	FileInputStream serviceAccount = new FileInputStream(
			"firebase-adminsdk.json");

	FirebaseOptions options = new FirebaseOptions.Builder()
			.setCredentials(GoogleCredentials.fromStream(serviceAccount))
			.setDatabaseUrl("https://mydatabaseurl.firebaseio.com/").build();	

	FirebaseApp.initializeApp(options);
	
	return FirebaseAuth.getInstance();
}
 
Example 24
Source Project: NaviBee   Source File: UserInfoManagerTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Before
public void setUp() {

    // create static mock
    mFirebaseAuth = mock(FirebaseAuth.class);
    PowerMockito.mockStatic(FirebaseAuth.class);

    mFirebaseFirestore = mock(FirebaseFirestore.class);
    PowerMockito.mockStatic(FirebaseFirestore.class);

    // configure mock expected interaction
    when(FirebaseAuth.getInstance()).thenReturn(mFirebaseAuth);
    when(FirebaseFirestore.getInstance()).thenReturn(mFirebaseFirestore);

}
 
Example 25
Source Project: firebase-admin-java   Source File: FirebaseAuthSnippets.java    License: Apache License 2.0 5 votes vote down vote up
public static void createUser() throws FirebaseAuthException {
  // [START create_user]
  CreateRequest request = new CreateRequest()
      .setEmail("[email protected]")
      .setEmailVerified(false)
      .setPassword("secretPassword")
      .setPhoneNumber("+11234567890")
      .setDisplayName("John Doe")
      .setPhotoUrl("http://www.example.com/12345678/photo.png")
      .setDisabled(false);

  UserRecord userRecord = FirebaseAuth.getInstance().createUser(request);
  System.out.println("Successfully created new user: " + userRecord.getUid());
  // [END create_user]
}
 
Example 26
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.action_settings:
            startActivity(EditUserActivity.getInstance(this));
            break;
        case R.id.action_logout:
            App.logout();
            startActivity(LoginActivity.getInstance(this));
            Bundle params = new Bundle();
            FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
            if (user != null) {

                params.putString(Analytics.Param.USER_ID, user.getUid());
                params.putString(Analytics.Param.USER_NAME, user.getDisplayName());
                params.putString(FirebaseAnalytics.Param.VALUE, user.getUid());

            }
            mAnalytics.logEvent(Analytics.Event.LOGOUT, params);
            finish();
            return false;
        case R.id.action_about:
            startActivity(AboutPage.getInstance(this));
            break;
        case R.id.action_licenses:
            displayLicensesAlertDialog();
            break;

    }
    return super.onOptionsItemSelected(item);
}
 
Example 27
Source Project: UberClone   Source File: onAppKilled.java    License: MIT License 5 votes vote down vote up
@Override
public void onTaskRemoved(Intent rootIntent) {
    super.onTaskRemoved(rootIntent);

    String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference("driversAvailable");
    GeoFire geoFire = new GeoFire(ref);
    geoFire.removeLocation(userId);
}
 
Example 28
Source Project: quickstart-android   Source File: GoogleSignInActivity.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mBinding = ActivityGoogleBinding.inflate(getLayoutInflater());
    setContentView(mBinding.getRoot());
    setProgressBar(mBinding.progressBar);

    // Button listeners
    mBinding.signInButton.setOnClickListener(this);
    mBinding.signOutButton.setOnClickListener(this);
    mBinding.disconnectButton.setOnClickListener(this);

    // [START config_signin]
    // Configure Google Sign In
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();
    // [END config_signin]

    mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

    // [START initialize_auth]
    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();
    // [END initialize_auth]
}
 
Example 29
Source Project: firebase-admin-java   Source File: FirebaseAuthSnippets.java    License: Apache License 2.0 5 votes vote down vote up
public static void getUserByEmail(String email) throws FirebaseAuthException {
  // [START get_user_by_email]
  UserRecord userRecord = FirebaseAuth.getInstance().getUserByEmail(email);
  // See the UserRecord reference doc for the contents of userRecord.
  System.out.println("Successfully fetched user data: " + userRecord.getEmail());
  // [END get_user_by_email]
}
 
Example 30
Source Project: RxFirebase   Source File: RxFirebaseAuth.java    License: Apache License 2.0 5 votes vote down vote up
@NonNull
public static Observable<Void> sendPasswordResetEmail(@NonNull final FirebaseAuth firebaseAuth,
                                                      @NonNull final String email) {
    return Observable.unsafeCreate(new Observable.OnSubscribe<Void>() {
        @Override
        public void call(final Subscriber<? super Void> subscriber) {
            RxTask.assignOnTask(subscriber, firebaseAuth.sendPasswordResetEmail(email));
        }
    });
}