使用 Firebase 认证验证用户

huangapple 未分类评论53阅读模式
英文:

validate user using firebase auth

问题

我希望已经在用户应用程序中注册的用户不能登录到管理员或医生应用程序中。
或者在医生应用程序中注册的医生不能登录到用户或管理员应用程序中。
或者在管理员应用程序中注册的管理员不能登录到医生或用户应用程序中。

使用 Firebase 认证验证用户

我尝试过的用户验证方法是

private void updateUI(final FirebaseUser user) {
    if (user != null) {

        final DatabaseReference adminsRef = FirebaseDatabase.getInstance().getReference().child("Admins").child(user.getUid());
        final DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference().child("Users").child(user.getUid());
        adminsRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {

                    userRole = dataSnapshot.child("role").getValue(String.class);
                    if (user.equals("admin")) {
                        FancyToast.makeText(getApplicationContext(), "User already registered as an Admin", FancyToast.LENGTH_LONG, FancyToast.INFO, false).show();
                        FirebaseAuth.getInstance().signOut();
                        if (AccessToken.getCurrentAccessToken() != null) {
                            LoginManager.getInstance().logOut();
                        }
                        startActivity(new Intent(MainActivity.this, MainActivity.class));
                        finish();
                    } else {
                        FirebaseDatabase database = FirebaseDatabase.getInstance();
                        DatabaseReference userRef = database.getReference("Doctors").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("uid", FirebaseAuth.getInstance().getCurrentUser().getUid());
                        map.put("email", FirebaseAuth.getInstance().getCurrentUser().getEmail());
                        map.put("name", FirebaseAuth.getInstance().getCurrentUser().getDisplayName());
                        map.put("profile_status", "incomplete");
                        map.put("role", "doctor");
                        //map.put("location", getIntent().getExtras().get("location").toString());
                        userRef.updateChildren(map).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                if (task.isSuccessful()) {
                                    FancyToast.makeText(getApplicationContext(), "User details updated successfully", FancyToast.LENGTH_LONG, FancyToast.SUCCESS, true).show();
                                } else {
                                    FancyToast.makeText(getApplicationContext(), "User details update unsuccessful", FancyToast.LENGTH_LONG, FancyToast.SUCCESS, true).show();
                                }
                            }
                        });
                        Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                        startActivity(intent);
                        finish();
                    }

                }
            }

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

            }
        });
        usersRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {
                    userRole = dataSnapshot.child("role").getValue(String.class);
                    if (userRole.equals("user")) {
                        FancyToast.makeText(getApplicationContext(), "User already registered as a Customer", FancyToast.LENGTH_LONG, FancyToast.INFO, false).show();
                        FirebaseAuth.getInstance().signOut();
                        if (AccessToken.getCurrentAccessToken() != null) {
                            LoginManager.getInstance().logOut();
                        }
                        startActivity(new Intent(MainActivity.this, MainActivity.class));
                        finish();
                    } else {
                        FirebaseDatabase database = FirebaseDatabase.getInstance();
                        DatabaseReference userRef = database.getReference("Doctors").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("uid", FirebaseAuth.getInstance().getCurrentUser().getUid());
                        map.put("email", FirebaseAuth.getInstance().getCurrentUser().getEmail());
                        map.put("name", FirebaseAuth.getInstance().getCurrentUser().getDisplayName());
                        map.put("profile_status", "incomplete");
                        map.put("role", "doctor");
                        //map.put("location", getIntent().getExtras().get("location").toString());
                        userRef.updateChildren(map).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                if (task.isSuccessful()) {
                                    FancyToast.makeText(getApplicationContext(), "User details updated successfully", FancyToast.LENGTH_LONG, FancyToast.SUCCESS, true).show();
                                } else {
                                    FancyToast.makeText(getApplicationContext(), "User details update unsuccessful", FancyToast.LENGTH_LONG, FancyToast.SUCCESS, true).show();
                                }
                            }
                        });
                        Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                        startActivity(intent);
                        finish();
                    }

                }
            }

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

            }
        });

    }

}
英文:

I want that the users those who have signed up in user app cannot sign into the admin or doctors app.
Or the doctors those who have signed up in doctors app cannot sign into user or admin app.
Or the admin those who have signed up in admin app cannot sign into doctors or users app.

使用 Firebase 认证验证用户

The method i tried for user validation is

private void updateUI(final FirebaseUser user) {
    if (user!=null){

        final DatabaseReference adminsRef = FirebaseDatabase.getInstance().getReference().child(&quot;Admins&quot;).child(user.getUid());
        final DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference().child(&quot;Users&quot;).child(user.getUid());
        adminsRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()){

                    userRole = dataSnapshot.child(&quot;role&quot;).getValue(String.class);
                    if (user.equals(&quot;admin&quot;)){
                        FancyToast.makeText(getApplicationContext(),&quot;User already registered as an Admin&quot;,FancyToast.LENGTH_LONG,FancyToast.INFO,false).show();
                        FirebaseAuth.getInstance().signOut();
                        if (AccessToken.getCurrentAccessToken() != null) {
                            LoginManager.getInstance().logOut();
                        }
                        startActivity(new Intent(MainActivity.this,MainActivity.class));
                        finish();
                    }
                    else {
                        FirebaseDatabase database = FirebaseDatabase.getInstance();
                        DatabaseReference userRef = database.getReference(&quot;Doctors&quot;).child(FirebaseAuth.getInstance().getCurrentUser().getUid());
                        HashMap&lt;String, Object&gt; map = new HashMap&lt;&gt;();
                        map.put(&quot;uid&quot;, FirebaseAuth.getInstance().getCurrentUser().getUid());
                        map.put(&quot;email&quot;, FirebaseAuth.getInstance().getCurrentUser().getEmail());
                        map.put(&quot;name&quot;, FirebaseAuth.getInstance().getCurrentUser().getDisplayName());
                        map.put(&quot;profile_status&quot;,&quot;incomplete&quot;);
                        map.put(&quot;role&quot;,&quot;doctor&quot;);
                        //map.put(&quot;location&quot;, getIntent().getExtras().get(&quot;location&quot;).toString());
                        userRef.updateChildren(map).addOnCompleteListener(new OnCompleteListener&lt;Void&gt;() {
                            @Override
                            public void onComplete(@NonNull Task&lt;Void&gt; task) {
                                if (task.isSuccessful()) {
                                    FancyToast.makeText(getApplicationContext(), &quot;User details updated successfully&quot;, FancyToast.LENGTH_LONG, FancyToast.SUCCESS, true).show();
                                } else {
                                    FancyToast.makeText(getApplicationContext(), &quot;User details update unsuccessful&quot;, FancyToast.LENGTH_LONG, FancyToast.SUCCESS, true).show();
                                }
                            }
                        });
                        Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                        startActivity(intent);
                        finish();
                    }

                }
            }

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

            }
        });
        usersRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()){
                    userRole = dataSnapshot.child(&quot;role&quot;).getValue(String.class);
                    if (userRole.equals(&quot;user&quot;)){
                        FancyToast.makeText(getApplicationContext(),&quot;User already registered as a Customer&quot;,FancyToast.LENGTH_LONG,FancyToast.INFO,false).show();
                        FirebaseAuth.getInstance().signOut();
                        if (AccessToken.getCurrentAccessToken() != null) {
                            LoginManager.getInstance().logOut();
                        }
                        startActivity(new Intent(MainActivity.this,MainActivity.class));
                        finish();
                    }
                    else {
                        FirebaseDatabase database = FirebaseDatabase.getInstance();
                        DatabaseReference userRef = database.getReference(&quot;Doctors&quot;).child(FirebaseAuth.getInstance().getCurrentUser().getUid());
                        HashMap&lt;String, Object&gt; map = new HashMap&lt;&gt;();
                        map.put(&quot;uid&quot;, FirebaseAuth.getInstance().getCurrentUser().getUid());
                        map.put(&quot;email&quot;, FirebaseAuth.getInstance().getCurrentUser().getEmail());
                        map.put(&quot;name&quot;, FirebaseAuth.getInstance().getCurrentUser().getDisplayName());
                        map.put(&quot;profile_status&quot;,&quot;incomplete&quot;);
                        map.put(&quot;role&quot;,&quot;doctor&quot;);
                        //map.put(&quot;location&quot;, getIntent().getExtras().get(&quot;location&quot;).toString());
                        userRef.updateChildren(map).addOnCompleteListener(new OnCompleteListener&lt;Void&gt;() {
                            @Override
                            public void onComplete(@NonNull Task&lt;Void&gt; task) {
                                if (task.isSuccessful()) {
                                    FancyToast.makeText(getApplicationContext(), &quot;User details updated successfully&quot;, FancyToast.LENGTH_LONG, FancyToast.SUCCESS, true).show();
                                } else {
                                    FancyToast.makeText(getApplicationContext(), &quot;User details update unsuccessful&quot;, FancyToast.LENGTH_LONG, FancyToast.SUCCESS, true).show();
                                }
                            }
                        });
                        Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                        startActivity(intent);
                        finish();
                    }

                }
            }

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

            }
        });



    }

}

答案1

得分: 0

你正在做几乎需要完成的工作。
只需检查用户 UID 是否存在于“Users”子节点或“admin”子节点中,使用数据快照。

以下是如何获取用户角色的方法:

String userRole;

roleRef = FirebaseDatabase.getInstance().getReference().child("Users").child(firebaseAuth.getCurrentUser().getUid());
roleRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

        try {
            userRole = dataSnapshot.child("role").getValue().toString();
            userProf_username.setText(userNameInData);
        } catch (Throwable e) {
            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
        }

    }

现在用户的角色存储在字符串 userRole 中。因此,您可以检查用户是管理员还是普通客户。

然后添加一个 if-else 块:

if (userRole.equals("admin")) {
    startActivity(new Intent(MainActivity.this, adminActivity.class));
} else {
    startActivity(new Intent(MainActivity.this, userActivity.class));
}
英文:

You are doing almost what needs to be done.
Just check if the user UID exists on Users child node or in admin child node using Data snapshot.

Here is how you can fetch the user role:

String userRole;

roleRef = FirebaseDatabase.getInstance().getReference().child(&quot;Users&quot;).child(firebaseAuth.getCurrentUser().getUid());
        roleRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                try {
                    userRole = dataSnapshot.child(&quot;role&quot;).getValue().toString();
                    userProf_username.setText(userNameInData);
                }catch (Throwable e){
                    Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
                }

            }

Now the role of user is in the string userRole. So now you can check if user is admin or normal client.

Then add an if-else block:

if(userRole.equals(&quot;admin&quot;)){
startActivity(new Intent(MainActivity.this, adminActivity.class);
}
else{
startActivity(new Intent(MainActivity.this, userActivity.class);
}

huangapple
  • 本文由 发表于 2020年4月7日 01:27:30
  • 转载请务必保留本文链接:https://java.coder-hub.com/61065457.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定