error Caused by: java.io.IOException: { "error": { "code": 403, "message": "Permission denied. Could not perform this operation" }}

huangapple go评论81阅读模式
英文:

error Caused by: java.io.IOException: { "error": { "code": 403, "message": "Permission denied. Could not perform this operation" }}

问题

以下是代码的翻译部分:

package com.example.db1;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class Register extends AppCompatActivity {

    private static final String TAG = "MyActivity";
    EditText Name, Email, Contact, Password;
    Button Register;
    ImageView user_image;
    FirebaseFirestore db;
    FirebaseAuth mAuth;
    ProgressBar progressBar;

    String user_id;
    Uri download_uri;
    StorageReference storageReference;
    Bitmap compressed;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        Name = findViewById(R.id.name);
        Email = findViewById(R.id.email);
        Contact = findViewById(R.id.contact);
        Register = findViewById(R.id.register);
        Password = findViewById(R.id.password);
        user_image = findViewById(R.id.im1);
        progressBar = findViewById(R.id.pb1);

        progressBar.setVisibility(View.GONE);

        db = FirebaseFirestore.getInstance();
        mAuth = FirebaseAuth.getInstance();

        storageReference = FirebaseStorage.getInstance().getReference();

        user_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                    if (ContextCompat.checkSelfPermission(Register.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

                        Toast.makeText(Register.this, "Permission Denied", Toast.LENGTH_LONG).show();

                        ActivityCompat.requestPermissions(Register.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
                    } else {
                        choseImage();
                    }
                } else {
                    choseImage();
                }
            }
        });

        Register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String name = Name.getText().toString().trim();
                final String email = Email.getText().toString().trim();
                final String contact = Contact.getText().toString().trim();
                final String pass = Password.getText().toString().trim();

                if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(name) && !TextUtils.isEmpty(contact) && !TextUtils.isEmpty(pass) && user_image != null) {

                    progressBar.setVisibility(View.VISIBLE);

                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

                    compressed.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);

                    byte[] thumbData = byteArrayOutputStream.toByteArray();

                    UploadTask image_path = storageReference.child("user_image").child(user_id + ".jpg").putBytes(thumbData);

                    image_path.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {

                        @Override
                        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {

                            if (task.isSuccessful()) {
                                storeData(task, name, email, contact, pass);
                            } else {
                                String error = task.getException().getMessage();
                                Toast.makeText(Register.this, "(IMAGE Error) : " + error, Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                } else {
                    progressBar.setVisibility(View.GONE);
                    Toast.makeText(Register.this, "Please fill all fields", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void storeData(Task<UploadTask.TaskSnapshot> task, String name, String email, String contact, String pass) {

        if (task != null) {
            download_uri = task.getResult().getUploadSessionUri();

            Map<String, Object> user = new HashMap<>();
            user.put("mName", name);
            user.put("mEmail", email);
            user.put("mContact", contact);
            user.put("mPassword", pass);
            user.put("userImage", download_uri.toString());

            db.collection("users").add(user).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                @Override
                public void onSuccess(DocumentReference documentReference) {
                    Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
                    Toast.makeText(Register.this, "User data save successfully", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(Register.this, Result.class));
                }
            })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Log.w(TAG, "Error adding document", e);
                            Toast.makeText(Register.this, "User data is not Save", Toast.LENGTH_SHORT).show();
                        }
                    });
        } else {
            Toast.makeText(Register.this, "Error in Data Upload", Toast.LENGTH_SHORT).show();
        }
    }

    private void choseImage() {

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(Intent.createChooser(intent, "pick an image"), 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1 && resultCode == RESULT_OK) {

            try {
                InputStream inputStream = getContentResolver().openInputStream(data.getData());
                compressed = BitmapFactory.decodeStream(inputStream);
                user_image.setImageBitmap(compressed);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}
英文:

> I was getting this error Caused by: java.io.IOException: { "error": { "code": 403, "message": "Permission denied. Could not perform this operation" }} or user does not have permission to access this object. when i try to upload data in firebase
> firestore and i already grant the permission in the firestore rule.
>
> here is my code

package com.example.db1;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class Register extends AppCompatActivity {
private static final String TAG = &quot;MyActivity&quot;;
EditText Name, Email, Contact,Password;
Button Register;
ImageView user_image;
FirebaseFirestore db;
FirebaseAuth mAuth;
ProgressBar progressBar;
String user_id;
Uri download_uri;
StorageReference storageReference;
Bitmap compressed;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Name = findViewById(R.id.name);
Email = findViewById(R.id.email);
Contact = findViewById(R.id.contact);
Register = findViewById(R.id.register);
Password = findViewById(R.id.password);
user_image = findViewById(R.id.im1);
progressBar = findViewById(R.id.pb1);
progressBar.setVisibility(View.GONE);
db = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
storageReference = FirebaseStorage.getInstance().getReference();
user_image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(Register.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(Register.this, &quot;Permission Denied&quot;, Toast.LENGTH_LONG).show();
ActivityCompat.requestPermissions(Register.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
} else {
choseImage();
}
} else {
choseImage();
}
}
});
Register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String name = Name.getText().toString().trim();
final String email = Email.getText().toString().trim();
final String contact = Contact.getText().toString().trim();
final String pass = Password.getText().toString().trim();
if(!TextUtils.isEmpty(email) &amp;&amp; !TextUtils.isEmpty(name) &amp;&amp; !TextUtils.isEmpty(contact) &amp;&amp; !TextUtils.isEmpty(pass) &amp;&amp; user_image!=null){
progressBar.setVisibility(View.VISIBLE);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
compressed.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] thumbData = byteArrayOutputStream.toByteArray();
UploadTask image_path = storageReference.child(&quot;user_image&quot;).child(user_id + &quot;.jpg&quot;).putBytes(thumbData);
image_path.addOnCompleteListener(new OnCompleteListener&lt;UploadTask.TaskSnapshot&gt;() {
@Override
public void onComplete(@NonNull Task&lt;UploadTask.TaskSnapshot&gt; task) {
if (task.isSuccessful()) {
storeData(task, name, email, contact, pass);
} else {
String error = task.getException().getMessage();
Toast.makeText(Register.this, &quot;(IMAGE Error) : &quot; + error, Toast.LENGTH_LONG).show();
}
}
});
}
else{
progressBar.setVisibility(View.GONE);
Toast.makeText(Register.this,&quot;Please fill all fields&quot;,Toast.LENGTH_SHORT).show();
}
}
});
}
private void storeData(Task&lt;UploadTask.TaskSnapshot&gt; task, String name, String email, String contact, String pass) {
if (task != null) {
download_uri = task.getResult().getUploadSessionUri();
Map&lt;String, Object&gt; user = new HashMap&lt;&gt;();
user.put(&quot;mName&quot;, name);
user.put(&quot;mEmail&quot;, email);
user.put(&quot;mContact&quot;, contact);
user.put(&quot;mPassword&quot;, pass);
user.put(&quot;userImage&quot;,download_uri.toString());
db.collection(&quot;users&quot;).add(user).addOnSuccessListener(new OnSuccessListener&lt;DocumentReference&gt;() {
@Override
public void onSuccess(DocumentReference documentReference) {
Log.d(TAG, &quot;DocumentSnapshot added with ID: &quot; + documentReference.getId());
Toast.makeText(Register.this,&quot;User data save successfully&quot;,Toast.LENGTH_SHORT).show();
startActivity(new Intent(Register.this,Result.class));
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, &quot;Error adding document&quot;, e);
Toast.makeText(Register.this,&quot;User data is not Save&quot;,Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(Register.this,&quot;Error in Data Upload&quot;,Toast.LENGTH_SHORT).show();
}
}
private void choseImage() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(&quot;image/*&quot;);
startActivityForResult(Intent.createChooser(intent,&quot;pick an image&quot;),1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 &amp;&amp; resultCode== RESULT_OK) {
try {
InputStream inputStream = getContentResolver().openInputStream(data.getData());
compressed = BitmapFactory.decodeStream(inputStream);
user_image.setImageBitmap(compressed);
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
}

答案1

得分: 1

值得仔细查看您的Firestore规则

> 基本规则包括一个匹配语句,指定文档路径,以及一个允许表达式,详细说明何时允许读取指定的数据:

service cloud.firestore {
match /databases/{database}/documents {
// 匹配 'cities' 集合中的任何文档
match /cities/{city} {
allow read: if <condition>;
allow write: if <condition>;
}
}
}

您的错误指向这个注意

> 您只能访问安全规则明确允许您访问的文档。

例如,在@Alex Mamo提到的问题中,解决方案如下:

service firebase.storage {
match /b/{bucket}/o {
match /{userId} {
match /{allPaths=**}{
allow read, write: if request.auth.uid == userId;
} 
}
}
}
英文:

It is well worth to take a look into your Firestore rules:

> Basic rules consist of a match statement specifying a document path and an allow expression detailing when reading the specified data is allowed:

service cloud.firestore {
match /databases/{database}/documents {
// Match any document in the &#39;cities&#39; collection
match /cities/{city} {
allow read: if &lt;condition&gt;;
allow write: if &lt;condition&gt;;
}
}
}

Your error points to this Note:

>You can only access documents that your security rules specifically allow you to access.

For instance: in the question mentioned by @Alex Mamo, the solution was:

service firebase.storage {
match /b/{bucket}/o {
match /{userId} {
match /{allPaths=**}{
allow read, write: if request.auth.uid == userId;
} 
}
}
}

答案2

得分: 0

为Kotlin,在Firebase存储中进行规则更改,并替换带引号标记的部分...
允许读取、写入:"如果请求授权不为空;"

英文:

for kotlin,
go rules on firebase storage and change with place that marked with quotes
... allow read, write: &quot;if request.auth!=null;&quot;

huangapple
  • 本文由 发表于 2020年8月11日 03:19:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/63346667.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定