How to make sure a user can only see and access their own data in firebase?

 ̄綄美尐妖づ 提交于 2019-12-06 10:41:39

问题


I am new to firebase. In my Android app, I want each user to only access the data he created. I was reading https://www.firebase.com/docs/security/guide/securing-data.html, but didn't make much sense out of it. Assuming I am already logged in with an email and password,

  1. How can should I write the Firebase Rules?
  2. How do write to my Firebase data in my Android Java code?

Thanks!

Firebase Rules

{
    "rules": {
        ".read": true,
        ".write": true
    }
}

Java Code

myFirebaseRef.child("message").setValue("This is the message");

回答1:


Thanks to Joey Roosing, I was able to figure out the rest of it. I need to group the data based on the uid of the user.

First, modify the Firstbase rules as Joey mentioned:

{
  "rules": {
    "users": {
      "$uid": {
        ".write": "$uid === auth.uid",
        ".read": "$uid === auth.uid"
      }
    }
  }
}

Then, in my Java Code:

Firebase rootRef = new Firebase("https://user-account.firebaseio.com/");
// Assuming the user is already logged in.
Firebase userRef = rootRef.child("users/" + rootRef.getAuth().getUid());
userRef.child("message1").setValue("Hello World");

In the end, my data would look something like this:




回答2:


This is the most basic example for if you are using oauth:

 {
  "rules": {
    "users": {
      "$uid": {
        ".write": "$uid === auth.uid",
        ".read": "$uid === auth.uid"
      }
    }
  }
}

https://www.firebase.com/docs/security/guide/user-security.html This link should help a bit more.

auth.uid i believe is the user currently connecting, $uid is how the user is known in the system (firebase in this case).

My example uses google login, but it should work for all the other types.

Im not sure about the following, but this is how i believe it works:

Firebase automatically generated a unique id representing the user on (first)successfull login, and does this only once. It then uses that data to authenticate against new requests, if a match is found, the rule $iud === auth.uid is true, and the user can in case of my example, read and write.




回答3:


You need to POJO/Custom class to efficiently write/read to a Firebase database. Idealy, you have created a class Message with setters and getters and a default constructor defined:

class Message {
  private String message;

  public Message() {
  }
  public Message(String message) {
    this.message = message;
  }

  public void getMessage() {
    return message;
  }
  public void setMessage(String message) {
    this.message = message;
  }
}

Then change your rules to this:

{
 "rules": {
   "message": {
    "$uid": {
      ".write": "$uid === auth.uid",
      ".read": "$uid === auth.uid"
   }
  }
 }
}

Then in your java code do this:

DatabaseReference mDatabaseReference;
FirebaseUser firebaseUser;

 mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            firebaseUser = firebaseAuth.getCurrentUser();
            if (firebaseUser != null) {
                // User is signed in
            } else {
                // User is signed out
            }
        }
    };
...


//To save a message associated to only the signed in user
Message message = new Message();
message.setMessage("a message");
mDatabaseReference = FirebaseDatabase.getInstance().getReference(); 
mDatabaseReference.child("message").child(firebaseUser.getUid())
     .setValue(message)
     .addOnCompleteListener(DetailsCaptureActivity.this, new OnCompleteListener<Void>() {
     ...
  });

Now, to read this data do this:

//Set up an AuthStateListener that responds to changes in the user's sign-in state:
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            firebaseUser = firebaseAuth.getCurrentUser();
            if (firebaseUser != null) {

                   databaseReference = firebaseDatabase.getReference().child("message").child(firebaseUser.getUid());
                   databaseReference.addValueEventListener(new ValueEventListener() {
                      @Override
                      public void onDataChange(DataSnapshot dataSnapshot) {
                          Message message = dataSnapshot.getValue(Message.class);
                          //You can now get your message using message.getMessage();
                      }

                      @Override
                      public void onCancelled(DatabaseError databaseError) {

                          Log.e(TAG, databaseError.getMessage());
                      }
                  });

            } else {
                Log.e(TAG, "onAuthStateChanged:signed_out");
            }
        }
    };

That's all.

You can now add your own implementation for retrieving a list of messages.Hopefully, that wouldn't be a problem.



来源:https://stackoverflow.com/questions/35820836/how-to-make-sure-a-user-can-only-see-and-access-their-own-data-in-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!