如果用户每次打开您的应用程序时都必须登录,那将会很麻烦。您可以通过使用缓存的当前 Moralis.User
对象来避免这种情况。
请注意,默认情况下,此功能在Node.js环境(例如ReactNative)中被禁用,以阻止在服务器端配置中使用有状态。
要在此特定用例中绕过此行为,请在使用任何与缓存用户相关的功能之前调用一次
Moralis.User.enableUnsafeCurrentUser()
。
管理当前用户
每当您使用任何注册或登录方法时,用户都会缓存在localStorage
或您通过Moralis.setAsyncStorage
方法配置的任何存储中。您可以将此缓存视为会话,并自动假定用户已登录:
const currentUser = Moralis.User.current();if (currentUser) { // do stuff with the user} else { // show the signup or login page}
当使用带有异步存储系统的平台时,您应该调用currentAsync()
。
Moralis.User.currentAsync().then(function(user) { // do stuff with your user});
您可以通过注销来清除当前用户:
Moralis.User.logOut().then(() => { const currentUser = Moralis.User.current(); // this will now be null});
设置当前用户
如果您创建了自己的身份验证例程,或者以其他方式在服务器端以用户身份登录,您现在可以将会话令牌传递给客户端并使用become
方法。此方法将在设置当前用户之前确保会话令牌有效。
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
中的数据只能由该用户读取或修改。
通过使用useMasterKey
选项,可以使用云函数绕过此限制。
具体来说,您无法调用任何保存或删除方法,除非Moralis.User
是使用经过身份验证的方法(如logIn
或signUp
)获得的。这确保只有用户可以更改他们自己的数据。
以下说明了此安全策略:
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 methodconst 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
是否经过身份验证,您可以调用authenticated
方法。您不需要检查通过Moralis.User
对象通过身份验证方法获得的身份验证。
加密当前用户
您可能经常需要更加小心存储在浏览器中的用户信息,如果是这种情况,您可以加密当前用户对象:
Moralis.enableEncryptedUser();Moralis.secret = 'my Secrey Key';
注意:如果没有设置Moralis.secret
,此功能将不起作用。另外,请注意,这仅适用于浏览器。
现在本地存储中的记录看起来像一个随机字符串,只能使用Moralis.User.current()
读取。您可以使用Moralis.isEncryptedUserEnabled()
函数检查此功能是否启用。