Reputation: 3139
I noticed something weird in my app. First of all, I register.
And then go in the welcome screen.
And to verify that I am indeed registered in firebase I go in the console. First in Authentication
And then in Database where you see a node called Users(I declared as Users when I was registering).
But let's say that I accidentally delete this user from the db. The user is still logged in the app and tries to comment on an article. Obviously, there is going to be a response,
E/CommentActivity: User AhtNY3bm7aQdPiJewf3PBN310732 is unexpectedly null
And this comes from here.
User user = dataSnapshot.getValue(User.class);
// [START_EXCLUDE]
if (user == null) {
// User is null, error out
Log.e(TAG, "User " + userId + " is unexpectedly null");
Toast.makeText(CommentActivity.this,
"Error: could not fetch user.",
Toast.LENGTH_SHORT).show();
}
The whole code of the CommentActivity is here.
Is there any way to avoid that kind of error? I mean once the user is registered in firebase, he can post comments even if he is accidentally deleted. Maybe use any of setter/getter methods from here?
public class User {
public String username;
public String email;
public User() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public User(String username, String email) {
this.username = username;
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
UPDATE
I put this rules
{
"rules": {
".read": "auth != null",
".write": "auth != null"
},
{
"rules": {
"comments": {
".write": "auth != null && root.child('Users').hasChild(auth.uid)"
".read": "auth != null"
}
}
}
}
but I get a syntax error.
Upvotes: 0
Views: 59
Reputation: 83058
There is no automatic link between the existence of your user in the Authentication panel and the user's data under the Users
node, in your DB. So, like you mention in your post, if you delete the user
node in the DB, he/she will still be able to authenticate.
Therefore you have to secure your database with a dedicated security rule (Consider it as the authorization part of the whole authentication/authorization mechanism).
You should write this database security rule in such a way that the user's UID must exist under the Users
node to allow him/her to write a "comment", as follows:
{
"rules": {
"comments": {
".write": "auth != null && root.child('Users').hasChild(auth.uid)"
".read": ...
}
}
}
Here, we make the assumption that the comments
node is directly under the database root. It is up to you to adapt this rule to your data model (and probably includes the post UID in this path).
Have a look at the corresponding documentation on Security, here, and in particular the full example at the end of the doc.
Upvotes: 1