[英]Firebase permission denied when checking unique username
我想檢查用戶名是否已被使用。 當前用戶沒有“ username”的子代時,將調用此函數:
func createUsername()
{
let userID = FIRAuth.auth()?.currentUser?.uid
FIRDatabase.database().reference().updateChildValues([
"users/\(userID!)/username": username.text!,
"usernames/\(username.text!)": userID!
], withCompletionBlock: { (error, reference) in
if (error != nil) {
print("disallowed")
// Write was disallowed because username exists
}
})
}
結合以下規則:
{
"rules": {
"users": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid",
"username": {
".read": true,
".write": "!data.exists() && newData.exists()",
".validate": "newData.isString()"
}
}
},
"usernames": {
"$username": {
".read": true,
".write": "!data.exists() && newData.exists()",
".validate": "newData.isString() && newData.val() == root.child('users/' + auth.uid + '/username').val()"
}
}
}
}
我從以下網址得到了答案: https : //groups.google.com/forum/#!topic/firebase-talk/dA1Lkykd-tk我收到此錯誤消息:
[Firebase / Database] [I-RDB03812] updateChildValues:位於/失敗:Permission_denied
我不確定為什么這行不通。 我還嘗試了以下答案: Firebase android:使用戶名唯一,但這對我不起作用。 規則有問題,但我不知道是什么。
更新,規則變化不大,仍然存在相同錯誤:
{
"rules": {
"users": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid",
"username": {
".read": true,
".write": "!data.exists() && newData.exists()",
".validate": "newData.isString()"
}
}
},
"usernames": {
"$username": {
".read": true,
".write": "!data.exists() && newData.exists()",
".validate": "newData.isString() && newData.val() == newData.parent().parent().child('users/' + auth.uid + '/username').val()"
}
}
}
}
我也更改了parent()的東西,但是它也不能正常工作。 我更改為4個父母和0個父母。 同樣的錯誤。
更新:問題來自此驗證規則:
".validate": "newData.isString() && newData.val() == root.child('users/' + auth.uid + '/username').val()"
您正在將新數據與當前根進行比較。 由於剛剛創建了用戶,因此/users/$uid
尚不存在。
您要做的是將新數據與新用戶節點進行比較。 要到達此節點,在進行比較時,您應該從newData
導航到新的根目錄:
".validate": "newData.isString() &&
newData.val() == newData.parent().parent().child('users/' + auth.uid + '/username').val()"
我將下面的答復留在下面,因為它可能有助於學習如何解決此類問題。
我只是將您的規則粘貼到我的項目中,對其進行了一些簡化,並且使用了您的代碼而沒有出現問題。 我不確定您為什么遇到問題。
編碼:
FIRAuth.auth()?.signInAnonymously(completion: { (user, error) in
let username = "puf"
let userID = FIRAuth.auth()?.currentUser?.uid
self.ref.child("42188459").updateChildValues([
"users/\(userID!)/username": username,
"usernames/\(username)": userID!
], withCompletionBlock: { (error, reference) in
if (error != nil) {
print("disallowed")
// Write was disallowed because username exists
}
})
})
規則片段:
"users": {
"$uid": {
".write": "$uid === auth.uid",
"username": {
".write": "!data.exists() && newData.exists()",
}
}
},
"usernames": {
"$username": {
".write": "!data.exists() && newData.exists()",
}
}
結果JSON:
{
"usernames" : {
"puf" : "DBP4Pw3uiwQfUaDJw1XBR8oFBUK2"
},
"users" : {
"DBP4Pw3uiwQfUaDJw1XBR8oFBUK2" : {
"username" : "puf"
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.