我希望用户1的节点下的值仅对用户1可读和可写,并且用户2的节点下的值仅对用户2可读和可写,以此类推。这意味着用户1无法在其他用户的节点下读写值,反之亦然。为此,我必须为数据库设置规则。
以下规则是我尝试的。到目前为止,用户1只能在自己的节点下写值,而不能在其他用户的节点下写值,反之亦然,这正是我想要的。问题是用户1仍可以读取其他用户节点下的值,这是不希望的。我阅读了一些解释数据库规则的文档,但这对我来说很难理解。我尝试了多种方法来重写规则,但仍然失败。我需要帮助来解决此问题。
{
"rules": {
".read": "auth.uid != null",
".write":"auth.uid != null",
"Users' Input History": {
"$user": {
".validate":"$user === auth.uid"
}
},
"Users' Vocabulary List": {
"$user": {
".validate":"$user === auth.uid"
}
}
}
}
为了进行记录,我使用了规则模拟器,如下图所示。我切换了“ validated”选项,选择“ Google”作为提供者,将模拟的UID设置为“ Kad06bqeNChhjaksxgP9cVtoFMh1”(用户1),然后单击执行按钮。结果分别在第3行和第4行允许“读取”和“设置”。
下面是我用于用户身份验证并将值提交到数据库的代码:
GoogleSignInActivity:
public class GoogleSignInActivity extends BaseActivity implements
View.OnClickListener {
private static final String TAG = "GoogleActivity";
private static final int RC_SIGN_IN = 9001;
// [START declare_auth]
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
// [END declare_auth]
private GoogleSignInClient mGoogleSignInClient;
private TextView mStatusTextView; // For displaying user's email
private TextView mDetailTextView; // For displaying user's UID
private TextView mScreenNameTextView; // For displaying user's display name (user.getDisplayName())
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_sign_in);
// Views
mStatusTextView = findViewById(R.id.status);
mDetailTextView = findViewById(R.id.detail);
mScreenNameTextView = findViewById(R.id.screen_name_textView);
setProgressBar(R.id.progressBar);
// Button listeners
findViewById(R.id.signInButton).setOnClickListener(this);
// [START config_signin]
// Configure Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
// [END config_signin]
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
// [START initialize_auth]
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
// [END initialize_auth]
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
toastMessage("Successfully signed in with: " + user.getEmail());
mStatusTextView.setText(getString(R.string.Google_status_fmt, user.getEmail()));
mDetailTextView.setText(getString(R.string.Firebase_status_fmt, user.getUid()));
username = mDetailTextView.getText().toString();
}
}
};
}
// [START on_start_check_user]
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
// Check if user is signed in (non-null).
FirebaseUser currentUser = mAuth.getCurrentUser();
}
// [END on_start_check_user]
@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
// [START onActivityResult]
@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);
Toast.makeText(getApplicationContext(), getResources().getString(R.string.Login_successful), Toast.LENGTH_LONG).show();
username = mDetailTextView.getText().toString();
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
}
}
}
// [END onActivityResult]
// [START auth_with_google]
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
// [START_EXCLUDE silent]
showProgressBar();
// [END_EXCLUDE]
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Snackbar.make(findViewById(R.id.main_layout), "Authentication Failed.", Snackbar.LENGTH_SHORT).show();
}
// [START_EXCLUDE]
hideProgressBar();
// [END_EXCLUDE]
}
});
}
// [END auth_with_google]
// [START signin]
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
// [END signin]
@Override
public void onClick(View v) {
int i = v.getId();
if (i == R.id.signInButton) {
signIn();
}
}
}
我将值推入数据库的代码:
EditText wordInputView;
String searchKeyword;
String username;
public static DatabaseReference mRootReference = FirebaseDatabase.getInstance().getReference();
public static DatabaseReference mChildReferenceForInputHistory = mRootReference.child("Users' Input History");
public static DatabaseReference mChildReferenceForVocabularyList = mRootReference.child("Users' Vocabulary List");
searchKeyword = wordInputView.getText().toString();
Query query = mChildReferenceForInputHistory.child(username).orderByValue().equalTo(searchKeyword);
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
//If a duplicate value (searchKeyword) is found, remove it.
snapshot.getRef().setValue(null);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
mChildReferenceForInputHistory.child(username).push().setValue(searchKeyword);
//Initialize the adapter
userInputArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, userInputArraylist);
userInputListview.setAdapter(userInputArrayAdapter);
mChildReferenceForInputHistory.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String previousChildKey) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
String value = snapshot.getValue(String.class);
userInputArraylist.add(value);
HashSet<String> myVocabularyArraylistHashSet = new HashSet<>();
myVocabularyArraylistHashSet.addAll(userInputArraylist);
userInputArraylist.clear();
userInputArraylist.addAll(myVocabularyArraylistHashSet);
//Alphabetic sorting
Collections.sort(userInputArraylist);
userInputArrayAdapter.notifyDataSetChanged();
}
}
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
从Firebase文档: