Clu*_*nce 2 javascript firebase firebase-authentication firebase-realtime-database
我有这个 JavaScript 代码,用户可以使用他们的 Google 帐户登录我的应用程序。
//firebase db congifurations
const config = {
apiKey: "my_api_key",
authDomain: "my-app.firebaseapp.com",
projectId: "my-app",
databaseURL: "https://my-app.firebaseio.com",
};
//signin callback implemented using - https://developers.google.com/identity/sign-in/web/sign-in
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
let fullName = profile.getName().split(" ");
let userName = profile.getEmail().replace(/@.*$/, "");
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
this.database = firebase.database();
let userRef = this.database.ref("users/" + userName);
userRef.set({
firstName: fullName[0],
lastName: fullName[1],
displayPicture: profile.getImageUrl(),
});
}
Run Code Online (Sandbox Code Playgroud)
当我执行此代码时,放置一个调试器let userRef = this.database.ref("users/" + userName);并尝试在控制台上运行它:
userRef.set({
firstName: "Clutch",
lastName: "Prince",
displayPicture: "any_url_that_i_want_to_inject",
});
Run Code Online (Sandbox Code Playgroud)
这个实际上被执行了,我的数据库受到了影响。有没有安全的方法来做到这一点?
我的实时数据库规则:
{
"rules": {
".read": true,
".write": true
}
}
Run Code Online (Sandbox Code Playgroud)
Firebase 规则是最重要的部分。除了您之外没有人可以编辑这些内容。因此请确保它们是安全的。你.write: true意味着任何人都可以编写你的数据库。为了防止这种情况,您应该制定安全规则。您可以查看此链接以了解大多数规则组合。
查看您的问题,设置规则如下:
{
"rules": {
"Users": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
确保将所有用户数据存储在不同的节点中。将节点值保留为其 UID。那么上面的规则应该就派上用场了
现在用户可以编辑或只读他们的信息。即使他们尝试通过控制台编辑它,至少您可以保证其他人的安全。如果这是一场比赛,如果你发现他们,一定要继续加罚 XD。
这仍然可以允许用户至少编辑他们的信息,如前所述。因此,如果您要存储某种游戏统计数据以及玩家拥有多少资源,那么您需要通过执行以下操作来阻止写入访问:
".write": false
现在,这可能会让您感到困惑,如果写入访问被拒绝,那么玩家将如何更新他们的分数,或者如何在数据库中添加用户名。
为此,您需要依赖云功能。每当新玩家创建帐户时,我都会运行一个云函数来添加默认级别和其他内容。下面是代码示例:
export const onNewuserJoined = functions.auth.user().onCreate((user) => {
const newUserUID = user.uid
const newUserEmail = user.email
return Promise.all([
admin.database().ref(player_stats_path).set({ "Level": initLevel, "Cash": initCash}),
admin.database().ref(player_info_path).set({ "UID": newUserUID, "E-Mail": newUserEmail})
])
})
Run Code Online (Sandbox Code Playgroud)
现在,这些player_stats_path将player_info_path仅具有读取访问权限,因此除了云功能之外,没有人可以乱搞它,因为它会覆盖任何存在的规则。如果您需要在某人完成特定任务时更改其统计数据,则只需通过云功能即可完成。所有游戏代码都在后端真是太好了。
| 归档时间: |
|
| 查看次数: |
1101 次 |
| 最近记录: |