Current User
The Current User Object to Access the Logged-In User.
It would be bothersome if the user had to log in every time they open your app. You can avoid this by using the cached current Moralis.User
object.
Note that this functionality is disabled by default on Node.js environments (such as React Native) to discourage stateful usages on server-side configurations.
To bypass this behaviour in this particular use case, call once Moralis.User.enableUnsafeCurrentUser()
right before using any cached-user-related functionalities.
Managing Current User
Whenever you use any signup or login methods, the user is cached in localStorage, or in any storage you configured via the Moralis.setAsyncStorage
method. You can treat this cache as a session, and automatically assume the user is logged in:
When using a platform with an async storage system, you should call currentAsync()
instead.
You can clear the current user by logging them out:
Setting the Current User
If you’ve created your own authentication routines, or otherwise logged in as a user on the server-side, you can now pass the session token to the client and use the become
method. This method will ensure the session token is valid before setting the current user.
Security For User Objects
The **Moralis.User
class is secured🔐by default. Data stored in aMoralis.User
**can only be read or modified by that user.
A Cloud Function can be used to bypass this restriction by using the useMasterKey
option.
Specifically, you are not able to invoke any of the save
or delete
methods unless the Moralis.User
was obtained using an authenticated method, like logIn
or signUp
. This ensures that only the user can alter their own data.
The following illustrates this security policy:
The Moralis.User
obtained from Moralis.User.current()
will always be authenticated.
If you need to check if a Moralis.User
is authenticated, you can invoke the authenticated
method. You do not need to check authenticated
with Moralis.User
objects that are obtained via an authenticated method.
Encrypt Current User
You may often want to be more careful with user information stored in the browser and if this is the case, you can encrypt the current user object:
Note: This function will not work if
Moralis.secret
is not set.Also, note that this only works in the browser.
Now the record in local storage looks like a random string and can only be read using Moralis.User.current()
. You can check if this feature is enabled with the function Moralis.isEncryptedUserEnabled()
.
Last updated