Firestore权限被拒绝

时间:2018-12-07 07:33:50

标签: javascript firebase firebase-authentication google-cloud-firestore

我是Firebase的新手,所以请保持柔和。我正在制作一个网络应用程序,人们可以在其中存储图像。图像通过 上传文件#full_example。将它们上传后,我将downloadUrl保存在我的实时数据库中。用户必须通过Firebase进行身份验证。

login(username: string, password: string): any {
    this.httpStatus.setHttpStatus(true);
    return this.firebase
        .auth()
        .signInWithEmailAndPassword(username, password)
        .then((firebaseUser: firebase.auth.UserCredential) => {
            this.httpStatus.setHttpStatus(false);
            this.userService.setUser(firebaseUser);
            if (!this.userService.getUser().emailVerified) {
                this.userService.getUser().sendEmailVerification();
            }
            this.router.navigate(['/profile']);
        });
}

这是我从客户端上传的方式:

uploadFile() {
    this.httpStatus.setHttpStatus(true);
    const file = this.file.nativeElement.files[0];
    const uid = this.userService.getUser().uid;
    const firebase = this.firebaseService.firebase;
    const storageRef = firebase.storage().ref();

    // Create the file metadata
    const metadata = {
        contentType: file.type
    };
    console.log(file);
    // Upload file and metadata to the object 'images/mountains.jpg'
    const uploadTask = storageRef
        .child('userFiles' + '/' + uid + '/' + file.name)
        .put(file, metadata);

    // Listen for state changes, errors, and completion of the upload.
    uploadTask.on(
        firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
        function(snapshot) {
            // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
            const progress =
                (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            console.log('Upload is ' + progress + '% done');
            switch (snapshot.state) {
                case firebase.storage.TaskState.PAUSED: // or 'paused'
                    console.log('Upload is paused');
                    break;
                case firebase.storage.TaskState.RUNNING: // or 'running'
                    console.log('Upload is running');
                    break;
            }
        },
        function(error) {
            this.httpStatus.setHttpStatus(false);
            this.error.emit(error);
        },
        () => {
            // Upload completed successfully, now we can get the download URL
            uploadTask.snapshot.ref.getDownloadURL().then(downloadURL => {
                this.httpStatus.setHttpStatus(false);
                this.success.emit({url: downloadURL, name: file.name});
            });
        }
    );
}

这是我将URL保存到数据库中的方式:

async setDocument(req, callback, errorCallback) {
    const url = req.body.url;
    const user = req.body.user;
    const fileName = req.body.name;
    try {
        await this.verify(req.body.token);
        const result = await this.db
            .collection('users')
            .doc(user.uid)
            .collection('docs')
            .doc(fileName)
            .set({
                url,
                fileName
            });
        callback(result);
    } catch (error) {
        errorCallback(error);
    }
}

这是我返回这些URL的方式:

async getDocuments(req, callback, errorCallback) {
    const url = req.body.url;
    const user = req.body.user;
    try {
        await this.verifySameUIDOrAccesslevel(
            req.body.token,
            req.body.user.uid,
            5
        );
        const result = await this.db
            .collection('users')
            .doc(user.uid)
            .collection('docs')
            .get();
        const data = [];
        result.forEach(each => data.push(each.data()));
        callback(data);
    } catch (error) {
        console.log(error);
        errorCallback(error);
    }
}

这是对客户端的响应:

[{"url":"https://firebasestorage.googleapis.com/v0/b/{{projectId}}.appspot.com/o/userFiles%2FIZxlZnKhQzYEonZf5F6SpMvu1af1%2FNelson_Neves_picuture.gif?alt=media&token=27cce93f-41a3-460b-84e9-4e8b8ceafc41","fileName":"Nelson_Neves_picuture.gif"}]

在个人资料上,我有一个带有该URL的锚标记src。解析为:

{
  "error": {
    "code": 403,
    "message": "Permission denied. Could not perform this operation"
 }
}

我知道这与“ token = 222adabc-2bc4-4b07-b57f-60cbf2aa204c”有关,我只是不明白为什么有些文件可以读取而另一些文件不能读取。

我的存储规则很简单:

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

有人可以向我解释此令牌以及如何与经过身份验证的用户共享永久URL吗?

欢呼

1 个答案:

答案 0 :(得分:1)

问题在于您如何调用下载网址。您必须使用相同的文件引用url而不是uploadTask ref。

this.imageFile.name.substr(this.imageFile.name.lastIndexOf('.'));
  const fileRef = this.storage.ref(this.filePath); <--- here
  this.task = this.storage.upload(this.filePath, this.imageFile);
  this.uploadPercent = this.task.percentageChanges();
  this.task
    .snapshotChanges()
    .pipe(
      finalize(() => {
        this.downloadURL = fileRef.getDownloadURL(); <--- here
        this.downloadURL.subscribe(url => {
          this.imageUrl = url;
        });
      })
    )
    .subscribe();
  return this.uploadPercent;
}