Search code examples
androidandroid-studiofirebasefirebase-authenticationuser-registration

Authenticate email/password using firebase for android


i have a very basic question to ask. I am new to android app development. I was strictly following the tutorial instructions from a source. But when it came to storing user data , my tutor was using parse.com . but parse.com will shutdown next year, so that option is closed. so i decided to use firebase instead, now i installed all the packages required. I want to add email/password authentication on firebase for the signup page in my app. please provide me with the code that i should add and please also specify where it should be placed(eg. under oncreate) and also the things i should initialise

Thanks!


Solution

  • Here is my code from LoginActivity class, this includes a login with Google Account , see more in https://firebase.google.com/docs/auth/web/password-auth

    public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
    
    private EditText txtEmail;
    private EditText txtPass;
    
    private Button btnLogin;
    private Button btnRegister;
    
    private ProgressDialog mProgress;
    
    //firebase
    private FirebaseAuth firAuth;
    
    private DatabaseReference firDatabaseUsers;
    
    //gogle sign in
    private SignInButton mGoogleBtn;
    private static final int RC_SIGN_IN = 1;
    private static final String TAG = "LoginActivity";
    private GoogleApiClient mGoogleApiClient;
    
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
    
        firAuth = FirebaseAuth.getInstance();
    
    
    
        firDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users");
        firDatabaseUsers.keepSynced(true);
    
        txtEmail =(EditText) findViewById(R.id.logintxtEmail);
        txtPass = (EditText) findViewById(R.id.logintxtPass);
    
        btnLogin = (Button) findViewById(R.id.loginbtnEnter);
        btnLogin.setOnClickListener(this);
    
        mGoogleBtn = (SignInButton) findViewById(R.id.googlebtn);
        mGoogleBtn.setOnClickListener(this);
    
    
        mProgress = new ProgressDialog(this);
    
        // ---------- GOOGLE SIGN IN ------------
    
        // Configure Google Sign In
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
    
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    
                    }
                })
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();
    
    }
    
    @Override
    public void onClick(View view) {
        if(view.getId() == R.id.loginbtnEnter) {
    
            checkLogin();
        }
        else if(view.getId() == R.id.googlebtn) {
    
            signInGoogle();
        }
    }
    
    private void signInGoogle() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    
        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
    
    
            mProgress.setMessage("Iniciando sesión...");
            mProgress.show();
            if (result.isSuccess()) {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = result.getSignInAccount();
                firebaseAuthWithGoogle(account);
            } else {
                // Google Sign In failed, update UI appropriately
                // ...
    
                mProgress.dismiss();
    
            }
        }
    }
    
    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
    
        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        firAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
    
                        // 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.
                        if (!task.isSuccessful()) {
                            Log.w(TAG, "signInWithCredential", task.getException());
                            Toast.makeText(LoginActivity.this, "Autenticación Fallida.",
                                    Toast.LENGTH_SHORT).show();
                        }
                        else {
                            mProgress.dismiss();
                            checkUserExist();
    
                        }
                        // ...
    
    
                    }
                });
    }
    
    
    private void checkLogin () {
    
        String _email = txtEmail.getText().toString().trim();
        String _pass = txtPass.getText().toString().trim();
    
        if(!TextUtils.isEmpty(_email) && !TextUtils.isEmpty(_pass)) {
    
            mProgress.setMessage("Comprobando");
            mProgress.show();
    
            firAuth.signInWithEmailAndPassword(_email, _pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
    
                    if(task.isSuccessful() ) {
    
                        mProgress.dismiss();
    
                        checkUserExist();
    
                    }
                    else {
    
                        mProgress.dismiss();
                        Toast.makeText(LoginActivity.this, "Error al ingresar", Toast.LENGTH_LONG).show();
                    }
                }
            });
    
    
        }
    }
    
    private void checkUserExist () {
    
        if(firAuth.getCurrentUser() != null) {
    
            final String _user_id = firAuth.getCurrentUser().getUid();
    
            firDatabaseUsers.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
    
                    if (dataSnapshot.hasChild(_user_id)) {
    
                        Intent iSetup = new Intent(LoginActivity.this, MainActivity.class);
                        iSetup.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    
                        startActivity(iSetup);
    
                    } else {
    
                        Intent iSetup = new Intent(LoginActivity.this, MainActivity.class);
                        iSetup.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    
                        startActivity(iSetup);
    
                    }
    
                }
    
                @Override
                public void onCancelled(DatabaseError databaseError) {
    
                }
            });
        }
    
    }
    

    }

    To register an user yo need to run this code

        final String _name = txtName.getText().toString().trim();
        String _email = txtEmail.getText().toString().trim();
        String _pass = txtPass.getText().toString().trim();
    
        if(!TextUtils.isEmpty(_name) && !TextUtils.isEmpty(_email) && !TextUtils.isEmpty(_pass) ) {
    
            mProgress.setMessage("Registrando ...");
            mProgress.show();
    
            firAuth.createUserWithEmailAndPassword(_email, _pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
    
                    if(task.isSuccessful()) {
    
                       //the user has been registered
    
                    }
                }
            });
    

    hope it helps