VueJS + VueFire - 通过身份验证向Firebase实时数据库添加数据

时间:2018-01-20 15:31:27

标签: javascript firebase firebase-realtime-database firebase-authentication vuefire

我正在将VueJS与VueFire一起使用,我需要使用用户授权将数据保存到Firebase 实时数据库

错误讯息:

  

util.js?54b5:189 FIREBASE警告:设置为/ notes / -L5J8Hk8wKHOxH-TQEhb   失败:permission_denied exports.warn @ util.js?54b5:189   Repo.js?6ebd:510

     

未捕获(承诺)错误:PERMISSION_DENIED:权限被拒绝

at eval (Repo.js?6ebd:510)
at Object.exports.exceptionGuard (util.js?54b5:556)
at Repo.callOnCompleteCallback (Repo.js?6ebd:501)
at eval (Repo.js?6ebd:278)
at eval (PersistentConnection.js?eae0:411)
at PersistentConnection.onDataMessage_ (PersistentConnection.js?eae0:444)
at Connection.onDataMessage_ (Connection.js?33e2:262)
at Connection.onPrimaryMessageReceived_ (Connection.js?33e2:256)
at WebSocketConnection.eval [as onMessage] (Connection.js?33e2:157)
at WebSocketConnection.appendFrame_ (WebSocketConnection.js?4701:197)

我的 Firebase规则用于授权:

{
  "rules": {
    "users": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
      }
    }
  }
}

VueJS代码 addnote.vue

<script>
 import Firebase from 'firebase'
  let config = {
    apiKey: '[...]',
    authDomain: '[...].firebaseapp.com',
    databaseURL: 'https://[...].firebaseio.com',
    projectId: '[...]',
    storageBucket: '',
    messagingSenderId: '[...]'
}
  let app = Firebase.initializeApp(config)
  let db = app.database()
  let notesRef = db.ref('notes')

export default {
    name: 'app',
    beforeCreate: function () {
      Firebase.auth().onAuthStateChanged((user) => {
        if (user) {
          this.user = user
          this.$bindAsArray('notes', db.ref(`notes/${user.uid}`))
        }
      })
    },
    firebase: {
      notes: notesRef
    },
    data () {
      return {
        user: null,
        newNote: {
          title: '',
          time: '',
          note: ''
        }
      }
    },
    methods: {
      addNote: function () {
        notesRef.push(this.newNote)
        this.newNote.title = ''
        this.newNote.time = ''
        this.newNote.note = ''
      },
      signInWithGoogle: function () {
        const provider = new Firebase.auth.GoogleAuthProvider()
        Firebase.auth().signInWithRedirect(provider).then((result) => {
          this.user = result.user
        }).catch(error => console.log(error))
      }
    }
}
</script>

1 个答案:

答案 0 :(得分:1)

您正在收听/notes并写入``/ notes / -L5J8Hk8wKHOxH-TQEhb , while your rules only give you permission on / users / $ uid`。由于您没有后者的权限,因此写入失败。

至少你要改变:

beforeCreate: function () {
  Firebase.auth().onAuthStateChanged((user) => {
    if (user) {
      this.user = user
      this.$bindAsArray('notes', db.ref(`/users/${user.uid}`))
    }
  })
},

addNote: function () {
    db.ref('users').child(this.user.uid).push(this.newNote)
    this.newNote.title = ''
    this.newNote.time = ''
    this.newNote.note = ''
},