Hello! At the end of this article, you will be able to update a user via Cloud Code Functions.
If you do not know what is a cloud code function but need to update a user from the cloud code, this article might be very helpful.
Firstly, let me explain the scenario: For security reasons, Parse Server does not allow us to update the user's data without using Master Key since the user class contains sensitive data.
It's unsafe using master key in your frontend code since it might be easily retrieved by someone that tries to find the headers of a request in your web application, or by a reverse engineer in your mobile application. Because of that, the safest way to update a user is through the cloud code. You can require your master key on it and set its parameters.
Now, let's start with the steps:
1. Locally in your machine, create a file called main.js and paste the following content on it:
Parse.Cloud.define("editUserProperty", async (request) => {
const { objectId, newUsername } = request.params;
const User = Parse.Object.extend(Parse.User);
const query = new Parse.Query(User);
let result = await query.get(objectId, { useMasterKey: true });
if (!result) new Error("No user found!");
result.set("username", newUsername);
try {
result.save(null, { useMasterKey: true });
return "User updated successfully!";
} catch (e) {
return e.message;
}
});
2. Deploy the file above inside the cloud folder of Cloud Code Functions on the Dashboard.
3. In my User class, I just created a new user setting the username and password columns.
4. At the left menu, go to API > Console and note that to call the cloud function, it needs an object Id and the new username to edit it. It will look like something below:
5. The result was:
{ "result": "User updated successfully!" }
Now, the same user looks like:
If you do not know how to call a cloud code function in the frontend side, you can check the guide below:
- Calling a Cloud Code function
If you face any issues or have any questions, please contact us and we will help you.
Comments
0 comments
Please sign in to leave a comment.