我是firebase的新手,我正试图通过.then()
firebase.auth().createUserWithEmailAndPassword(email, password)
将用户对象(用户电子邮件)保存到数据库
当我尝试这样做时会抛出错误:
FIREBASE警告:设置为/ users / -KlMikr6xZnfYC6dFJ6L失败:permission_denied
基本上说我没有权限将用户数据设置为用户节点。
我知道该函数何时起作用,因为当我将安全性写入规则设置为true时,会在数据库中创建userobj
。
不确定我做错了什么。
controller.js
angular.module('app')
.controller('appCtrl', function($scope){
//empty user object to store info
$scope.user = {};
//empty object to accept user password
$scope.password = {};
// add login event
$scope.signUp = function(){
const email = $scope.user.email;
const password = $scope.password.setup;
// create new firebase user
firebase.auth().createUserWithEmailAndPassword(email, password)
// add user object to database
.then(function(){
var userObj = $scope.user;
console.log($scope.user);
// set up database references
let database = firebase.database();
let ref = database.ref();
let usersRef = ref.child('users');
// push user object to database
usersRef.push(userObj);
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode);
console.log(errorMessage);
});
};
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
console.log('user signed in');
var uid = user.uid;
console.log(uid);
} else {
// No user is signed in.
console.log('user not signed in');
}
});
})
Firebase数据库规则
"rules": {
"users": {
"$uid": {
".read": true,
".write": "(auth.uid === $uid)"
}
}
}
答案 0 :(得分:0)
问题是您使用的是 .push(),它会使用新的UID创建子级。 您应检索新创建的用户UID,并将对象分配给相关参考。
let uid = firebase.auth().currentUser.uid;
let usersRef = ref.child('users').child(uid);
usersRef.set(userObj);