1

I have an app in which the user can upload images to create a task list. But, whenever I upload the image and say "create", the onFailureListener is called and "User does not have permission to access this object" occurs.

My firebase rules:

// Allow read/write access on all documents to any user signed in to the application
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{allPaths=**} {
          allow read, write: if request.auth != null;
        }
      }
    }

I tried all the rules mentioned on User does not have permission to access this object . Firebase storage android All of these result in another error which is "Error in updating Profile". This is the line I had added on the onFailureListener when the profile data is loaded initially.

Below is my CreateBoardActivity.kt class- when I upload an image and then click on the "btn_create" button, the error (User does not have permission to access this object) pops up. (I suppose the "uploadBoardImage()" method is called in this scenario)

package com.example.projectmanager.activities

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.example.projectmanager.Firebase.FireStoreClass
import com.example.projectmanager.R
import com.example.projectmanager.models.Board
import com.example.projectmanager.utils.Constants
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import kotlinx.android.synthetic.main.activity_create_board.*
import java.io.IOException

class CreateBoardActivity : BaseActivity() {

    private var mSelectedImageFileUri : Uri? = null
    private lateinit var mUserName: String
    private var mBoardImageURL : String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_create_board)

        setUpActionBar()

        if(intent.hasExtra(Constants.NAME)){
            mUserName = intent.getStringExtra(Constants.NAME).toString()
        }

        iv_board_image.setOnClickListener{
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
                Constants.showImageChooser(this)
            }else{
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), Constants.READ_STORAGE_PERMISSION_CODE)
            }
        }

        btn_create.setOnClickListener {
            if(mSelectedImageFileUri != null){
                uploadBoardImage()
            }
            else{
                showProgressDialog(resources.getString(R.string.please_wait))
                createBoard()
            }
        }
    }

    private fun createBoard(){
        val assignedUsersArrayList: ArrayList<String> = ArrayList()
        assignedUsersArrayList.add(getCurrentUserId())

        val board = Board(et_board_name.text.toString(), mBoardImageURL, mUserName, assignedUsersArrayList)
        FireStoreClass().createBoard(this, board)
    }


    private fun uploadBoardImage(){
        showProgressDialog(resources.getString(R.string.please_wait))

        val sRef : StorageReference = FirebaseStorage.getInstance().reference.child(
            "BOARD_IMAGE" + System.currentTimeMillis() + "." + Constants.getFileExtension(this, mSelectedImageFileUri))
        sRef.putFile(mSelectedImageFileUri!!).addOnSuccessListener {
                taskSnapshot->
            Log.i("Board Image URL", taskSnapshot.metadata!!.reference!!.downloadUrl.toString())

            taskSnapshot.metadata!!.reference!!.downloadUrl.addOnSuccessListener {
                    uri->
                Log.i("Downloadable Image URL", uri.toString())
                mBoardImageURL = uri.toString()

                createBoard()
            }
        }.addOnFailureListener{
                exception->
            Toast.makeText(this, exception.message, Toast.LENGTH_LONG).show()
            hideProgressionDialog()
        }

    }

    fun boardCreatedSuccessfully(){
        hideProgressionDialog()

        setResult(Activity.RESULT_OK)

        finish()
    }

    private fun setUpActionBar(){
        setSupportActionBar(toolbar_create_board_activity)
        val actionBar = supportActionBar
        if(actionBar!=null){
            actionBar.setDisplayHomeAsUpEnabled(true)
            actionBar.setHomeAsUpIndicator(R.drawable.ic_black_color_white_24dp)
            actionBar.title = resources.getString(R.string.create_board_title)
        }

        toolbar_create_board_activity.setNavigationOnClickListener { onBackPressed() }

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if(requestCode== Constants.READ_STORAGE_PERMISSION_CODE){
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED){

            }
        }else{
            Toast.makeText(this, "You have denied the permission for storage. You can allow it from settings", Toast.LENGTH_LONG).show()
        }
    }




    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(resultCode == Activity.RESULT_OK && requestCode == Constants.PICK_IMAGE_REQUEST_CODE && data!!.data != null){
            mSelectedImageFileUri = data.data

            try{
                Glide.with(this)
                    .load(mSelectedImageFileUri)
                    .centerCrop()
                    .placeholder(R.drawable.ic_board_place_holder)
                    .into(iv_board_image)
            }catch(e: IOException){
                e.printStackTrace()
            }
        }
    }
}

Please do let me know what rules I should use to fix this issue.

Aks K
  • 11
  • 2
  • Are you sure the user is authenticated when you perform that operation? – Alex Mamo Nov 15 '22 at 08:15
  • Yes, the user is signed in at that time – Aks K Nov 15 '22 at 09:55
  • Can you please edit and add you code so we can ensure the user would be logged in before the query? – Dharmaraj Nov 15 '22 at 10:11
  • Please edit your question and add the information Dharmaraj asked for, and please also respond using @. – Alex Mamo Nov 15 '22 at 10:32
  • @Dharmaraj I have added the code for the activity in which the error occurs – Aks K Nov 15 '22 at 10:38
  • I don't see any code related to Firestore that adds data. Is the `putFile()` of Firebase storage throwing that error? Firebase storage has different rules than Firestore's. Also can you try logging user's UID right before the create method is called. See the [documentation](https://firebase.google.com/docs/auth/android/manage-users#get_a_users_profile) for getting current user. – Dharmaraj Nov 15 '22 at 10:44
  • 1
    @Dharmaraj I have managed to solve the issue. thanks for the help. (just had to have different rules in the storage and different in the db) – Aks K Nov 15 '22 at 12:07
  • Check your Firebase rules in your Firebase project console, it may be preventing users from wring or reading the database. Set your rules to `allow read, write: true;` to see if the request can then be completed. If this is the case, then your user auth is incorrect – ToxicFlame427 Nov 15 '22 at 16:57

0 Answers0