Search in sources :

Example 61 with FirebaseUser

use of com.google.firebase.auth.FirebaseUser in project MadMax by deviz92.

the class ProfileEdit method updateAccount.

private boolean updateAccount() {
    Log.i(TAG, "createAccount");
    if (!validateForm()) {
        Log.i(TAG, "submitted form is not valid");
        Toast.makeText(this, getString(R.string.invalid_form), Toast.LENGTH_SHORT).show();
        return false;
    }
    final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    if (user == null) {
        Log.e(TAG, "Error while retriving current user from db");
        Toast.makeText(this, getString(R.string.error_user_db), Toast.LENGTH_LONG).show();
        return false;
    }
    final String currentUserID = currentUser.getID();
    String newName = nameView.getText().toString();
    String newSurname = surnameView.getText().toString();
    String newUsername = usernameView.getText().toString();
    // String newEmail = emailView.getText().toString();
    String newPassword = passwordView.getText().toString();
    if (!newName.isEmpty() && (currentUser.getName() == null || !currentUser.getName().equals(newName))) {
        currentUser.setName(newName);
        databaseReference.child("users").child(currentUserID).child("name").setValue(currentUser.getName());
    }
    if (!newSurname.isEmpty() && (currentUser.getSurname() == null || !currentUser.getSurname().equals(newSurname))) {
        currentUser.setSurname(newSurname);
        databaseReference.child("users").child(currentUserID).child("surname").setValue(currentUser.getSurname());
    }
    if (!newUsername.isEmpty() && (currentUser.getUsername() == null || !currentUser.getUsername().equals(newUsername))) {
        currentUser.setUsername(newUsername);
        databaseReference.child("users").child(currentUserID).child("username").setValue(currentUser.getUsername());
    }
    if (IMAGE_CHANGED) {
        // for saving image
        StorageReference uProfileImageFilenameRef = storageReference.child("users").child(currentUserID).child(currentUserID + "_profileImage.jpg");
        // Get the data from an ImageView as bytes
        profileImageView.setDrawingCacheEnabled(true);
        profileImageView.buildDrawingCache();
        Bitmap bitmap = profileImageView.getDrawingCache();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] data = baos.toByteArray();
        UploadTask uploadTask = uProfileImageFilenameRef.putBytes(data);
        uploadTask.addOnFailureListener(new OnFailureListener() {

            @Override
            public void onFailure(@NonNull Exception exception) {
                // todo Handle unsuccessful uploads
                Log.e(TAG, "image upload failed");
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
                currentUser.setProfileImage(taskSnapshot.getMetadata().getDownloadUrl().toString());
                databaseReference.child("users").child(currentUserID).child("image").setValue(currentUser.getProfileImage());
            }
        });
    }
    if (!newPassword.isEmpty() && !currentUser.getPassword().equals(User.encryptPassword(newPassword))) {
        try {
            user.updatePassword(newPassword);
        } catch (Exception e) {
            Log.e(TAG, e.getClass().toString() + ", message: " + e.getMessage());
            Toast.makeText(this, getString(R.string.error_password), Toast.LENGTH_LONG).show();
            return false;
        }
        currentUser.setPassword(newPassword);
        databaseReference.child("users").child(currentUserID).child("password").setValue(currentUser.getPassword());
    }
    return true;
}
Also used : StorageReference(com.google.firebase.storage.StorageReference) FirebaseUser(com.google.firebase.auth.FirebaseUser) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Bitmap(android.graphics.Bitmap) UploadTask(com.google.firebase.storage.UploadTask) NonNull(android.support.annotation.NonNull) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 62 with FirebaseUser

use of com.google.firebase.auth.FirebaseUser in project MadMax by deviz92.

the class ProfileEdit method updateAccount.

private boolean updateAccount() {
    Log.i(TAG, "createAccount");
    if (!validateForm()) {
        Log.i(TAG, "submitted form is not valid");
        Toast.makeText(this, "Invalid form!", Toast.LENGTH_SHORT).show();
        return false;
    }
    final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    if (user == null) {
        Log.e(TAG, "Error while retriving current user from db");
        Toast.makeText(this, "Error while retriving current user from db", Toast.LENGTH_LONG).show();
        return false;
    }
    final String currentUserID = currentUser.getID();
    String newName = nameView.getText().toString();
    String newSurname = surnameView.getText().toString();
    String newUsername = usernameView.getText().toString();
    //String newEmail = emailView.getText().toString();
    String newPassword = passwordView.getText().toString();
    if (!newName.isEmpty() && (currentUser.getName() == null || !currentUser.getName().equals(newName))) {
        currentUser.setName(newName);
        databaseReference.child("users").child(currentUserID).child("name").setValue(currentUser.getName());
    }
    if (!newSurname.isEmpty() && (currentUser.getSurname() == null || !currentUser.getSurname().equals(newSurname))) {
        currentUser.setSurname(newSurname);
        databaseReference.child("users").child(currentUserID).child("surname").setValue(currentUser.getSurname());
    }
    if (!newUsername.isEmpty() && (currentUser.getUsername() == null || !currentUser.getUsername().equals(newUsername))) {
        currentUser.setUsername(newUsername);
        databaseReference.child("users").child(currentUserID).child("username").setValue(currentUser.getUsername());
    }
    if (IMAGE_CHANGED) {
        // for saving image
        StorageReference uProfileImageFilenameRef = storageReference.child("users").child(currentUserID).child(currentUserID + "_profileImage.jpg");
        // Get the data from an ImageView as bytes
        profileImageView.setDrawingCacheEnabled(true);
        profileImageView.buildDrawingCache();
        Bitmap bitmap = profileImageView.getDrawingCache();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] data = baos.toByteArray();
        UploadTask uploadTask = uProfileImageFilenameRef.putBytes(data);
        uploadTask.addOnFailureListener(new OnFailureListener() {

            @Override
            public void onFailure(@NonNull Exception exception) {
                // todo Handle unsuccessful uploads
                Log.e(TAG, "image upload failed");
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
                currentUser.setProfileImage(taskSnapshot.getMetadata().getDownloadUrl().toString());
                databaseReference.child("users").child(currentUserID).child("image").setValue(currentUser.getProfileImage());
            }
        });
    }
    if (!newPassword.isEmpty() && !currentUser.getPassword().equals(User.encryptPassword(newPassword))) {
        try {
            user.updatePassword(newPassword);
        } catch (Exception e) {
            Log.e(TAG, e.getClass().toString() + ", message: " + e.getMessage());
            Toast.makeText(this, "Can't update password", Toast.LENGTH_LONG).show();
            return false;
        }
        currentUser.setPassword(newPassword);
        databaseReference.child("users").child(currentUserID).child("password").setValue(currentUser.getPassword());
    }
    return true;
}
Also used : StorageReference(com.google.firebase.storage.StorageReference) FirebaseUser(com.google.firebase.auth.FirebaseUser) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Bitmap(android.graphics.Bitmap) UploadTask(com.google.firebase.storage.UploadTask) NonNull(android.support.annotation.NonNull) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 63 with FirebaseUser

use of com.google.firebase.auth.FirebaseUser in project SocialRec by Jkuras.

the class SignIn_SignUp method sendEmailVerification.

private void sendEmailVerification() {
    // Disable button
    // findViewById(R.id.verify_email_button).setEnabled(false);
    // Send verification email
    // [START send_email_verification]
    final FirebaseUser user = mAuth.getCurrentUser();
    user.sendEmailVerification().addOnCompleteListener(this, new OnCompleteListener<Void>() {

        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                Toast.makeText(SignIn_SignUp.this, "Verification email sent to " + user.getEmail(), Toast.LENGTH_SHORT).show();
            } else {
                Log.e(TAG, "sendEmailVerification", task.getException());
                Toast.makeText(SignIn_SignUp.this, "Failed to send verification email.", Toast.LENGTH_SHORT).show();
            }
        // [END_EXCLUDE]
        }
    });
// [END send_email_verification]
}
Also used : FirebaseUser(com.google.firebase.auth.FirebaseUser)

Example 64 with FirebaseUser

use of com.google.firebase.auth.FirebaseUser in project ShelterApp by farzamtn.

the class LoginActivity method newLogin.

/**
 * Event handler for Login Button - uses FireBase email/password authentication to validate
 * the email and password entered by user.
 *
 * @param view the current view
 */
public void newLogin(View view) {
    // Reset errors.
    email.setError(null);
    password.setError(null);
    String user = email.getText().toString();
    final String pass = password.getText().toString();
    boolean cancel = false;
    View focusView = null;
    // Check for a valid password.
    if (TextUtils.isEmpty(pass)) {
        password.setError(getString(R.string.error_field_required));
        focusView = password;
        cancel = true;
    } else if (!Login.isPasswordValid(pass)) {
        password.setError(getString(R.string.error_minimum_password));
        focusView = password;
        cancel = true;
    }
    // Check for a valid email.
    if (TextUtils.isEmpty(user)) {
        email.setError(getString(R.string.error_field_required));
        focusView = email;
        cancel = true;
    } else if (!Login.isUsernameValid(user)) {
        email.setError(getString(R.string.error_invalid_email));
        focusView = email;
        cancel = true;
    }
    if (cancel) {
        // There was an error; don't attempt registration and ask for focus.
        focusView.requestFocus();
    } else {
        // Show a progress spinner, and kick off a background task to
        // perform the user login attempt.
        progressBar.setVisibility(View.VISIBLE);
        // authenticate user
        mAuth.signInWithEmailAndPassword(user, pass).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {

            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                // If sign in fails, display a message to the user. If sign in succeeds
                // the auth state listener will be notified and logic to handle the
                // signed in user can be handled in the listener.
                progressBar.setVisibility(View.GONE);
                if (!task.isSuccessful()) {
                    Log.d("Firebase Auth error: ", task.getException().toString());
                    // there was an error
                    Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
                } else {
                    // following TODO: Tried getting ChildrenCount from dataSnapShot and comparing it with getItems().size() but it returns 0 everytime
                    if (shelterModel.getItems().size() == 0) {
                        populateShelterInfo();
                    }
                    // Getting the correct type of user based on their login info
                    FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
                    String RegisteredUserID = currentUser.getUid();
                    conditionRef = mLoginDatabase.child("Users").child(RegisteredUserID);
                    conditionRef.addValueEventListener(new ValueEventListener() {

                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            String disabled = dataSnapshot.child("Disabled").getValue(String.class);
                            if (disabled.equals("true")) {
                                View focusView = email;
                                email.setError("User is Banned");
                                FirebaseAuth.getInstance().signOut();
                                return;
                            }
                            String userType = dataSnapshot.child("User Type").getValue(String.class);
                            if (userType.equals("Admin")) {
                                Intent intentUser = new Intent(LoginActivity.this, AdminActivity.class);
                                intentUser.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(intentUser);
                                finish();
                            } else if (userType.equals("Shelter Employee")) {
                                Intent intentUser = new Intent(LoginActivity.this, MapsMasterActivity.class);
                                intentUser.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(intentUser);
                                finish();
                            } else if (userType.equals("Shelter Seeker")) {
                                Intent intentUser = new Intent(LoginActivity.this, MapsMasterActivity.class);
                                intentUser.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(intentUser);
                                finish();
                            } else {
                                Toast.makeText(LoginActivity.this, "Failed Login. Please Try Again", Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                            Log.d("User DB Error (login)", databaseError.getMessage());
                        }
                    });
                }
            }
        });
    }
}
Also used : AuthResult(com.google.firebase.auth.AuthResult) Intent(android.content.Intent) FirebaseUser(com.google.firebase.auth.FirebaseUser) DataSnapshot(com.google.firebase.database.DataSnapshot) View(android.view.View) DatabaseError(com.google.firebase.database.DatabaseError) ValueEventListener(com.google.firebase.database.ValueEventListener)

Example 65 with FirebaseUser

use of com.google.firebase.auth.FirebaseUser in project ShelterApp by farzamtn.

the class User method updateDBUserBeds.

/**
 * Update a currentUser's bed attribute in the database
 * @param newBeds number to be put into database
 */
public static void updateDBUserBeds(int newBeds) {
    DatabaseReference userDB = FirebaseDatabase.getInstance().getReference().child("Users");
    FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
    DatabaseReference userRef = userDB.child(currentUser.getUid());
    userRef.addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            userRef.child("Beds").setValue(newBeds);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            System.out.print(databaseError.getMessage());
        }
    });
}
Also used : DatabaseError(com.google.firebase.database.DatabaseError) DatabaseReference(com.google.firebase.database.DatabaseReference) FirebaseUser(com.google.firebase.auth.FirebaseUser) ValueEventListener(com.google.firebase.database.ValueEventListener) DataSnapshot(com.google.firebase.database.DataSnapshot)

Aggregations

FirebaseUser (com.google.firebase.auth.FirebaseUser)100 AuthResult (com.google.firebase.auth.AuthResult)26 Intent (android.content.Intent)22 FirebaseAuth (com.google.firebase.auth.FirebaseAuth)16 DataSnapshot (com.google.firebase.database.DataSnapshot)12 DatabaseError (com.google.firebase.database.DatabaseError)12 OnFailureListener (com.google.android.gms.tasks.OnFailureListener)11 AuthCredential (com.google.firebase.auth.AuthCredential)11 DatabaseReference (com.google.firebase.database.DatabaseReference)11 ValueEventListener (com.google.firebase.database.ValueEventListener)11 View (android.view.View)10 Task (com.google.android.gms.tasks.Task)10 Button (android.widget.Button)9 NonNull (android.support.annotation.NonNull)8 OnCompleteListener (com.google.android.gms.tasks.OnCompleteListener)7 FirebaseAuthUserCollisionException (com.google.firebase.auth.FirebaseAuthUserCollisionException)7 TextView (android.widget.TextView)6 Test (org.junit.Test)6 Context (android.content.Context)5 SharedPreferences (android.content.SharedPreferences)5