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