W3Cschool
恭喜您成為首批注冊(cè)用戶(hù)
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
如果用戶(hù)每次打開(kāi)您的應(yīng)用程序時(shí)都必須登錄,那將會(huì)很麻煩。 您可以通過(guò)使用緩存的當(dāng)前 ?Moralis.User
? 對(duì)象來(lái)避免這種情況。
請(qǐng)注意,默認(rèn)情況下,此功能在 Node.js 環(huán)境(例如 React Native)中被禁用,以阻止在服務(wù)器端配置中使用有狀態(tài)。
要在此特定用例中繞過(guò)此行為,請(qǐng)?jiān)谑褂萌魏闻c緩存用戶(hù)相關(guān)的功能之前調(diào)用一次 ?Moralis.User.enableUnsafeCurrentUser()
?。
每當(dāng)您使用任何注冊(cè)或登錄方法時(shí),用戶(hù)都會(huì)緩存在 ?localStorage
?或您通過(guò) ?Moralis.setAsyncStorage
? 方法配置的任何存儲(chǔ)中。 您可以將此緩存視為會(huì)話(huà),并自動(dòng)假定用戶(hù)已登錄:
const currentUser = Moralis.User.current();
if (currentUser) {
// do stuff with the user
} else {
// show the signup or login page
}
當(dāng)使用帶有異步存儲(chǔ)系統(tǒng)的平臺(tái)時(shí),您應(yīng)該調(diào)用 ?currentAsync()
?。
Moralis.User.currentAsync().then(function(user) {
// do stuff with your user
});
您可以通過(guò)注銷(xiāo)來(lái)清除當(dāng)前用戶(hù):
Moralis.User.logOut().then(() => {
const currentUser = Moralis.User.current(); // this will now be null
});
如果您創(chuàng)建了自己的身份驗(yàn)證例程,或者以其他方式在服務(wù)器端以用戶(hù)身份登錄,您現(xiàn)在可以將會(huì)話(huà)令牌傳遞給客戶(hù)端并使用 ?become
?方法。 此方法將在設(shè)置當(dāng)前用戶(hù)之前確保會(huì)話(huà)令牌有效。
Moralis.User.become("session-token-here").then(function (user) {
// The current user is now set to user.
}, function (error) {
// The token could not be validated.
});
默認(rèn)情況下,?Moralis.User
? 類(lèi)是受保護(hù)的。 存儲(chǔ)在 ?aMoralis.User
? 中的數(shù)據(jù)只能由該用戶(hù)讀取或修改。
通過(guò)使用 ?useMasterKey
?選項(xiàng),可以使用云函數(shù)繞過(guò)此限制。
具體來(lái)說(shuō),您無(wú)法調(diào)用任何保存或刪除方法,除非 ?Moralis.User
? 是使用經(jīng)過(guò)身份驗(yàn)證的方法(如 ?logIn
?或 ?signUp
?)獲得的。 這確保只有用戶(hù)可以更改他們自己的數(shù)據(jù)。
以下說(shuō)明了此安全策略:
const user = await Moralis.User.logIn("my_username", "my_password");
user.set("username", "my_new_username");
await user.save();
// This succeeds, since the user was authenticated on the device
// Get the user from a non-authenticated method
const query = new Moralis.Query(Moralis.User);
const userAgain = await query.get(user.objectId);
userAgain.set("username", "another_username");
await userAgain.save().catch(error => {
// This will error, since the Moralis.User is not authenticated
});
從 ?Moralis.User.current()
? 獲得的 ?Moralis.User
? 將始終被驗(yàn)證。
如果您需要檢查 ?Moralis.User
? 是否經(jīng)過(guò)身份驗(yàn)證,您可以調(diào)用 ?authenticated
方法。 您不需要檢查通過(guò) ?Moralis.User
? 對(duì)象通過(guò)身份驗(yàn)證方法獲得的身份驗(yàn)證。
您可能經(jīng)常需要更加小心存儲(chǔ)在瀏覽器中的用戶(hù)信息,如果是這種情況,您可以加密當(dāng)前用戶(hù)對(duì)象:
Moralis.enableEncryptedUser();
Moralis.secret = 'my Secrey Key';
- 注意:如果沒(méi)有設(shè)置 ?
Moralis.secret
?,此功能將不起作用。- 另外,請(qǐng)注意,這僅適用于瀏覽器。
現(xiàn)在本地存儲(chǔ)中的記錄看起來(lái)像一個(gè)隨機(jī)字符串,只能使用 ?Moralis.User.current()
? 讀取。 您可以使用 ?Moralis.isEncryptedUserEnabled()
? 函數(shù)檢查此功能是否啟用。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話(huà):173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: