我的Firebase实时数据库有以下规则:
{
"rules": {
"users": {
"$user_id": {
".read": "auth !== null && auth.uid == $user_id",
".write": "auth !== null && auth.uid == $user_id",
".validate": "data.hasChildren(['calculations', 'daily', 'firstName', 'lastName', 'monthly', 'profileImageUrl', 'uid', 'username', 'weekly'])",
"calculations": {
".validate": "data.isNumber()",
},
"daily": {
".validate": "data.isNumber()",
},
"firstName": {
".validate": "data.isString()",
},
"lastName": {
".validate": "data.isString()",
},
"monthly": {
".validate": "data.isNumber()",
},
"profileImageUrl": {
".validate": "data.isString()",
},
"uid": {
".validate": "data.isString()",
},
"username": {
".validate": "data.isString()",
},
"weekly": {
".validate": "data.isNumber()",
},
"$other": {
".validate": false
}
}
}
}
}
适用于新用户的旧Firebase实时数据库规则:
{
"rules": {
".read": "auth.uid == $user_id",
".write": "auth.uid == $user_id"
}
}
使用电子邮件和密码进行Firebase身份验证:
// Firebase Authentication to create a user with email and password
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
val user = auth.currentUser
// Send an email verification to the user. Only allow them to login after they
// have verified their email.
user!!.sendEmailVerification().addOnCompleteListener { task ->
if (task.isSuccessful) {
// Save username, first name, and last name on Firebase Database
val uid = auth.uid ?: ""
val ref = database.getReference("/users/$uid")
val newUser = User(uid, userName, firstName, lastName, 0.0, 0.0, 0.0, 3, "")
ref.setValue(newUser)
Toast.makeText(
this,
"Please check your inbox and verify your email address.",
Toast.LENGTH_LONG).show()
val intent = Intent(this, LoginActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
}
}
}
}
// If sign in fails, display a message to the user.
.addOnFailureListener {
Toast.makeText(
baseContext, "Failed to create an account: ${it.message}",
Toast.LENGTH_LONG
).show()
}
用户类别:
@IgnoreExtraProperties
data class User(
val uid: String,
val username: String,
var firstName: String,
var lastName: String,
val daily: Double,
val weekly: Double,
val monthly: Double,
val calculations: Int,
val profileImageUrl: String
)
这些规则适用于现有用户。但是,如果我尝试创建一个新用户,这些规则将不起作用。我无法在数据库中为已注册的新用户创建新数据。我该如何解决?
我的猜测是,您需要验证新数据是否为正确的类型。所以:
"calculations": {
".validate": "newData.isNumber()",
},
如果您查看有关验证数据的Firebase文档,您会发现它们也全部进行了检查,newData
而不是data
(在写操作之前引用数据)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句