Cloud Firestore安全规则权限

时间:2019-01-15 12:46:58

标签: java android firebase firebase-security firebase-security-rules

如何在注册过程中将用户信息登录到数据库并启用用户权限以写入数据库。

service cloud.firestore {
match /databases/{database}/documents {
match /Users/{userId} {
  // Anybody can write to their ouser doc
  allow read, write: if request.auth.uid == userId;
    }
  }
}

我无法使用这些限制注册用户,如何设置好的限制以在确认电子邮件后启用日志记录信息?

image         register.setOnClickListener(new View.OnClickListener(){             @Override             public void onClick(View view){

            if(imageUri!=null){
                username_=username.getText().toString();
                name_=name.getText().toString();
                email_=email.getText().toString();
                pass_=password.getText().toString();
                location_=location.getText().toString();

                mDialog.show();

                if (TextUtils.isEmpty(username_)) {

                    AnimationUtil.shakeView(username, RegisterActivity.this);
                    mDialog.dismiss();

                }

                if (TextUtils.isEmpty(name_)) {

                    AnimationUtil.shakeView(name, RegisterActivity.this);
                    mDialog.dismiss();

                }
                if (TextUtils.isEmpty(email_)) {

                    AnimationUtil.shakeView(email, RegisterActivity.this);
                    mDialog.dismiss();

                }
                if (TextUtils.isEmpty(pass_)) {

                    AnimationUtil.shakeView(password, RegisterActivity.this);
                    mDialog.dismiss();

                }

                if (TextUtils.isEmpty(location_)) {

                    AnimationUtil.shakeView(location, RegisterActivity.this);
                    mDialog.dismiss();

                }

                if (!TextUtils.isEmpty(name_) || !TextUtils.isEmpty(email_) ||
                        !TextUtils.isEmpty(pass_) || !TextUtils.isEmpty(username_) || !TextUtils.isEmpty(location_)) {

                    firebaseFirestore.collection("Usernames")
                            .document(username_)
                            .get()
                            .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
                                @Override
                                public void onSuccess(DocumentSnapshot documentSnapshot) {
                                    if(!documentSnapshot.exists()){
                                        registerUser();
                                    }else{
                                        Toast.makeText(RegisterActivity.this, "Username already exists", Toast.LENGTH_SHORT).show();
                                        AnimationUtil.shakeView(username, RegisterActivity.this);
                                        mDialog.dismiss();
                                    }
                                }
                            })
                            .addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception e) {
                                    Log.e("Error",e.getMessage());
                                }
                            });

                }else{

                    AnimationUtil.shakeView(username, RegisterActivity.this);
                    AnimationUtil.shakeView(name, RegisterActivity.this);
                    AnimationUtil.shakeView(email, RegisterActivity.this);
                    AnimationUtil.shakeView(password, RegisterActivity.this);
                    AnimationUtil.shakeView(location, RegisterActivity.this);
                    mDialog.dismiss();

                }

            }else{
                AnimationUtil.shakeView(profile_image, RegisterActivity.this);
                Toast.makeText(RegisterActivity.this, "We recommend you to set a profile picture", Toast.LENGTH_SHORT).show();
                mDialog.dismiss();
            }

        }
    });


}

private void registerUser() {

    mAuth.createUserWithEmailAndPassword(email_, pass_).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull final Task<AuthResult> task) {
            if (task.isSuccessful()) {

                Map<String,Object> usernameMap=new HashMap<String, Object>();
                usernameMap.put("username",username_);

                firebaseFirestore.collection("Usernames")
                        .document(username_)
                        .set(usernameMap)
                        .addOnSuccessListener(new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void aVoid) {
                                task.getResult()
                                        .getUser()
                                        .sendEmailVerification()
                                        .addOnSuccessListener(new OnSuccessListener<Void>() {
                                            @Override
                                            public void onSuccess(Void aVoid) {

                                                final String userUid = task.getResult().getUser().getUid();
                                                final StorageReference user_profile = storageReference.child(userUid + ".png");
                                                user_profile.putFile(imageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                                                    @Override
                                                    public void onComplete(@NonNull final Task<UploadTask.TaskSnapshot> task) {
                                                        if (task.isSuccessful()) {

                                                           user_profile.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                                               @Override
                                                               public void onSuccess(Uri uri) {

                                                                   //noinspection deprecation
                                                                   String token_id = FirebaseInstanceId.getInstance().getToken();

                                                                   Map<String, Object> userMap = new HashMap<>();
                                                                   userMap.put("id", userUid);
                                                                   userMap.put("name", name_);
                                                                   userMap.put("image", uri.toString());
                                                                   userMap.put("email", email_);
                                                                   userMap.put("bio",getString(R.string.default_bio));
                                                                   userMap.put("username", username_);
                                                                   userMap.put("location", location_);
                                                                   userMap.put("token_id", "");

                                                                   firebaseFirestore.collection("Users").document(userUid).set(userMap).addOnSuccessListener(new OnSuccessListener<Void>() {
                                                                       @Override
                                                                       public void onSuccess(Void aVoid) {
                                                                           mDialog.dismiss();
                                                                           Toast.makeText(RegisterActivity.this, "Verification email sent", Toast.LENGTH_SHORT).show();
                                                                           finish();
                                                                       }
                                                                   }).addOnFailureListener(new OnFailureListener() {
                                                                       @Override
                                                                       public void onFailure(@NonNull Exception e) {
                                                                           mDialog.dismiss();
                                                                           Toast.makeText(RegisterActivity.this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                                                                       }
                                                                   });

                                                               }
                                                           }).addOnFailureListener(new OnFailureListener() {
                                                                       @Override
                                                                       public void onFailure(@NonNull Exception e) {
                                                                           mDialog.dismiss();
                                                                       }
                                                            });


                                                        } else {
                                                            mDialog.dismiss();
                                                        }
                                                    }
                                                });

                                            }
                                        })
                                        .addOnFailureListener(new OnFailureListener() {
                                            @Override
                                            public void onFailure(@NonNull Exception e) {
                                                task.getResult().getUser().delete();
                                            }
                                        });
                            }
                        })
                        .addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                Log.e("Error",e.getMessage());
                            }
                        });


            } else {
                mDialog.dismiss();
                Toast.makeText(RegisterActivity.this, "Error: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    });

}

1 个答案:

答案 0 :(得分:0)

要解决此问题,请使用以下代码行:

service cloud.firestore {
  match /databases/{database}/documents {
    match /Users/{userId} {
      allow read, update, delete: if request.auth.uid == userId;
      allow create: if request.auth.uid != null;
    }
  }
}

这基本上意味着您可以在request.auth.uid != null时创建用户文档,并且仅在request.auth.uid == userId时才能读取,更新和删除。

编辑:

您收到该PERMISSION_DENIED警告,因为在尝试写入以下内容之前:

firebaseFirestore.collection("Users").document(userUid).set(userMap)

您还试图将数据写入:

firebaseFirestore.collection("Usernames").document(username_).set(usernameMap)

您没有权限的地方。请在第一次写入操作中添加相应的权限,一切都会好起来。