Firebase存储规则未经授权

时间:2017-12-18 10:57:57

标签: angular firebase firebase-authentication angularfire firebase-storage

firebase storage rules

我试图上传文件,除非我使用alllow读取,写入,否则我将获得未经授权。

FirebaseStorageError {code_: "storage/unauthorized", message_: "Firebase 
Storage: User does not have permission to…2/dxbdIGnx2Qdm9MfTtG5e/if_spider-
web_345348.png'.", serverResponse_: "{↵  "error": {↵    "code": 403,↵    
"message": "Pe…n denied. Could not perform this operation"↵  }↵}", name_: 
"FirebaseError"}

我想知道firebase如何知道用户已登录?在我的代码中,我在尝试上传文件时不发送任何身份验证。

这是我上传文件的代码:

let uploadTask = storageRef.child(`user_content`).child(uid).child(upload.podcast_id).child(upload.file.name).put(upload.file);
  uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
    (snapshot) =>{
      // upload in progress
      upload.progress = Math.floor((uploadTask.snapshot.bytesTransferred / uploadTask.snapshot.totalBytes )* 100)
    },
    (error) =>{
      // upload failed
      this.flashMessagesService.show('Oh snap! please try again..',  { cssClass: 'alert alert-danger', timeout: 1500 })      
      console.log(error)
    },
    () => {
      // upload success
      upload.url = uploadTask.snapshot.downloadURL;
          //  upload.name is the name ref in firebase storage
      upload.name = uploadTask.snapshot.ref.name;
      upload.ref = uploadTask.snapshot.ref.fullPath;
      this.flashMessagesService.show('File was successfuly uploaded!',  { cssClass: 'alert alert-success', timeout: 1500 })

    }
  )
 }

我有一项身份验证服务,要求用户登录才能访问此上传页面:

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import {FlashMessagesService} from 'angular2-flash-messages';

import * as firebase from'firebase/app';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import  {Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/switchMap'
import { User } from '../models/user'
@Injectable()
export class AuthService {
user: Observable<User>;
currentUser: firebase.User;
  constructor(
    private afAuth: AngularFireAuth,
    private afs: AngularFirestore,
    private router: Router,
    public flashMessagesService: FlashMessagesService,
  ) { 
      // Get auth data, then get firestore user document // null
      this.user = this.afAuth.authState
      .switchMap(user => {
        if(user){
          return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
        } else {
          return Observable.of(null)
        } 
      })
 }

getCurrentUser(){
  return this.afAuth.auth.currentUser;
}

getAuthState(){
let currentUser = this.afAuth.auth.currentUser;

  if(currentUser){
    return true;
  }else{
    return false;
  }

}

 googleLogin() {
  const provider = new firebase.auth.GoogleAuthProvider();
   return this.oAuthLogin(provider);
  }
facebookLogin(){
  const provider = new firebase.auth.FacebookAuthProvider();
  return this.oAuthLogin(provider);
}
anonymousLogin(){
  const provider = new firebase.auth.EmailAuthProvider();
  return this.oAuthLogin(provider);
}

  private oAuthLogin(provider){
    return this.afAuth.auth.signInWithPopup(provider)
    .then((credential)=> {
      this.updateUserData(credential)
      this.router.navigate(['/home'])
    })
  }

  private updateUserData(credential){
    const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${credential.user.uid}`);
    const data: User = {
      uid: credential.user.uid,
      email: credential.user.email,
      displayName: credential.user.displayName,
      photoURL: credential.user.photoURL,
      accessToken: credential.credential.accessToken,
    } 
    if(!data.gender){
      data.gender = 'Unassigned'
    }
    this.flashMessagesService.show('You are now logged in ', { cssClass: 'alert alert-success', timeout: 3000 })

    return userRef.set(data)
  }
  signOut() {
    this.afAuth.auth.signOut().then(() => {
      this.flashMessagesService.show('You are now logged out ', { cssClass: 'alert alert-success', timeout: 3000 })

        this.router.navigate(['/']);
    });
  }
}

我在这个例子中使用google登录。仍然不清楚firebase如何知道用户已登录,因为我在上传文件时没有发送任何授权。如果你可以对此有所了解,那就太棒了,因为我已经在这3天内打破了我的球。

0 个答案:

没有答案