有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java检查云Firestore中是否已存在用户Google登录凭据

我在谷歌登录时遇到了一个问题,每当我使用谷歌登录时,我都会设置要添加到数据库中的凭据(如:姓名和电子邮件),但问题是,所有这些都正常工作,只是现在每次我使用同一个谷歌帐户登录时,它都会再次添加到数据库中(一遍又一遍地添加相同的凭据),因此,我想检查数据库中是否已经存在Google登录凭据,无需全部添加凭据

以下是onCreate中的Google登录代码:

private FirebaseAuth firebaseAuth;
private FirebaseFirestore firebaseFirestore;
private GoogleSignInClient mGoogleSignInClient;
private static final int RC_SIGN_IN = 100;


googleImageBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            progresBarDim.setVisibility(View.VISIBLE);
            signIn();
        }
    });

// TODO : Firebase Authentication
    firebaseAuth = FirebaseAuth.getInstance();
    firebaseFirestore = FirebaseFirestore.getInstance();
    googleRequest();

以下是谷歌登录的方法:

private void googleRequest(){
    // Configure Google Sign In
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();

    // Build a GoogleSignInClient with the options specified by gso.
    mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}

private void signIn() {
    Intent signInIntent = mGoogleSignInClient.getSignInIntent();
    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) {
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        try {
            // Google Sign In was successful, authenticate with Firebase
            GoogleSignInAccount account = task.getResult(ApiException.class);
            firebaseAuthWithGoogle(account);
        } catch (ApiException e) {
            progresBarDim.setVisibility(View.GONE);
            // Google Sign In failed, update UI appropriately
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
            // ...
        }
    }
}

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {


    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    firebaseAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(LoginActivity.this);
                        final String name = signInAccount.getDisplayName().trim();
                        final String email =signInAccount.getEmail().trim();

                        Map<Object, String> userdata = new HashMap<>();
                        userdata.put("Nom et prénom", name);
                        userdata.put("Address émail", email);

                        firebaseFirestore.collection("USERS")
                                .add(userdata);

                        // Sign in success, update UI with the signed-in user's information
                        FirebaseUser user = firebaseAuth.getCurrentUser();
                        Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
                        startActivity(intent);

                    } else {
                        progresBarDim.setVisibility(View.GONE);
                        // If sign in fails, display a message to the user.
                        Toast.makeText(LoginActivity.this, "sorry auth failed!", Toast.LENGTH_SHORT).show();
                    }
                    progresBarDim.setVisibility(View.GONE);

                    // ...
                }
            });
}

共 (1) 个答案

  1. # 1 楼答案

    it gets added again in Realtime database( same credentials over and over)

    之所以会发生这种情况,是因为您一次又一次地添加数据。以下代码行负责此行为:

    firebaseFirestore.collection("USERS")
                                .add(userdata);
    

    使用add(Object data)时:

    Adds a new document to this collection with the specified data, assigning it a document ID automatically.

    因此,每次调用上述代码行时,都会创建一个新文档。要解决此问题,应将数据添加到特定位置,例如,在以下引用处:

    Firestore-root
      |
       - users (collection)
           |
            - uid  (document)
                |
                 - Nom et prénom: "User Name"
                |
                 - Address émail: "User Email"
    

    您可以使用以下代码行从FirebaseUser对象获取uid

    String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    

    现在,要编写数据,请使用以下代码:

    firebaseFirestore.collection("USERS").document(uid)
                                .set(userdata);
    

    但是我没有使用add(),而是在DocumentReference对象上使用了set()。为了避免每次用户登录Google时都写入数据,您需要检查该用户是否已经存在,这可以使用我在以下帖子中的回答来完成:

    但是,您不应该检查用户名,而应该检查uid

    另外,在设置标记时,您的代码表明您正在使用Cloud Firestore和而不是Firebase实时数据库