Search code examples
androidfirebasefirebase-securityrolesuser-roles

Role-based authentification in android app using Firebase


I am developing an android app and using firebase database. It contains authorization and few activities for different roles. If you are entering as "Installer" opens one activity and if as "Contact-Centre" - another, but now it's not important. So I need to check a role of entered pair of email and password. So what I should to do?

Here is my database structure:

database structure

Sign in code:

mAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {
        if(task.isSuccessful()){
            Toast.makeText(MainActivity.this,"Аутентификация прошла успешно",Toast.LENGTH_SHORT).show();
            startActivity(new Intent(getApplicationContext(),RoleInstallerForm.class));
        }
        else {
            Toast.makeText(MainActivity.this,"Проверьте правильность введённых данных", Toast.LENGTH_SHORT).show();
                            ProgressBar.setVisibility(View.GONE);
        }
    }
});

Solution

  • Modify your code to this:

    mAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if(task.isSuccessful()){
                Toast.makeText(MainActivity.this,"Àóòåíòèôèêàöèÿ ïðîøëà óñïåøíî",Toast.LENGTH_SHORT).show();
    
                try {
                    currentUserUID = FirebaseAuth.getInstance().getCurrentUser().getUid();
                }catch (Throwable throwable){
                    throwable.printStackTrace();
                }
    
                roleRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserUID).child("Role");
                roleRef.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        try {
                            String userRole = dataSnapshot.getValue().toString();
                            //Add if-else here if you need any
                            //For example:
                            //I DONT UNDERSTAND RUSSIAN ROLE YOU TYPE
                            // JUST REPLACE THE ROLE NAMES
                            if(userRole.equals(leader)){
                                startActivity(new Intent(MainActivity.this, some-activity.class));
                            }else{
                                startActivity(new Intent(MainActivity.this, other-activity.class));
                            }
                        }catch (Throwable e){
                            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
                        }
                     }
                     @Override
                     public void onCancelled(@NonNull DatabaseError databaseError) {
                         Toast.makeText(getApplicationContext(), databaseError.toString(), Toast.LENGTH_SHORT).show();
                     }
                 });   
    
             }
             else {
                 Toast.makeText(MainActivity.this,"Ïðîâåðüòå ïðàâèëüíîñòü ââåä¸ííûõ äàííûõ", Toast.LENGTH_SHORT).show();
                 ProgressBar.setVisibility(View.GONE);
             }
         }
     });