Delete a user in parse User table from windows 8.1 app - parse-platform

I am developing a windows 8.1 app using Parse as back-end, I want to delete a user from windows app,How to achieve this

You can delete a user using Cloud Code.
Parse.Cloud.define("deleteUser", function(request, response) {
var query = new Parse.Query(Parse.User);
query.equalTo("objectId", reques.parsams.userId);
query.first({
success: function(result) {
result.destroy({
success: function() {
response.success("Success");
},
error: function(error) {
response.error("Could not delete object");
}
});
},
error: function() {
response.error("Could not run query");
}
});
});
You'd call the above function in Windows 8, where xxxxxxx is the objectId of the user you'd like to delete.
IDictionary<string, object> params = new Dictionary<string, object>
{
{ "userId", "xxxxxxx" }
};
var result = await ParseCloud.CallFunctionAsync<IDictionary<string, object>>("deleteUser", params);

Related

Update Parse user via Cloud Code

I'm trying to update some attributes on my user via cloud code, but even when there is no error, nothing is being updated??? Any thoughts?
Parse.Cloud.define("updateDetailsUser", function (request, response) {
var query = new Parse.Query("User");
query.equalTo("objectId", request.user.id);
var mobileNumber = request.params.mobileNumber;
var fullName = request.params.fullName;
var email = request.params.email;
query.first({
success: function (user) {
user.set("mobileNumber", mobileNumber);
user.set("fullName", fullName);
user.set("email", email);
user.save(null, {
useMasterKey: true,
success: function (updated) {
}
});
}
});
});
For all the classes that are built-in, it suggests to use the Parse class name for them. In case of User, you need to use Parse.User.
So, to fix this, just replace
var query = new Parse.Query("User"); with var query = new Parse.Query(Parse.User); and it should work.
To read further : http://parseplatform.org/Parse-SDK-JS/api/

Update user object from Parse cloud code is not saving

Currently I am trying to update the username and password from parse cloud code, but In the parse.com console I am seeing the success messages, but the object is not actually saved in the parse.com database. Here is the contents of cloud/main.js
// code to update username
Parse.Cloud.define("updateUserName", function(request, response){
if(!request.user){
response.error("Must be signed in to update the user");
return;
}
Parse.Cloud.useMasterKey();
var userId = request.params.id;
var userName = request.params.userName;
// var User = Parse.Object.extend("User");
var updateQuery = new Parse.Query(Parse.User);
updateQuery.get(userId,{
success: function(userRecord){
console.log(userRecord.get("id"));
userRecord.set("username", userName);
// userRecord.set("resetToken", "Apple");
userRecord.save(null,{
success: function(successData){
response.success("username updated successfully.");
// userRecord.fetch();
},
error: function(errorData){
console.log("Error while updating the username: ",errorData);
}
});
},
error: function(errorData){
console.log("Error: ",errorData);
}
});
});
Parse.Cloud.define("resetPassword", function(request, response){
var successMsg = "";
if(!request.user){
response.error("Must be signed in to update the user");
return;
}
Parse.Cloud.useMasterKey();
var resetToken = request.params.resetToken;
var password = request.params.password;
// var User = Parse.Object.extend("User");
var updateQuery = new Parse.Query(Parse.User);
// updateQuery.equalTo("resetToken", resetToken);
updateQuery.get(resetToken,{
success: function(userRecord){
// console.log(userRecord.get("id"));
// userRecord.set("password",password)
userRecord.set("password",password);
userRecord.save(null, {
success: function(successData){
successMsg = "Password Changed !";
console.log("Password changed!");
userRecord.set("resetToken", "");
userRecord.save();
},
error: function(errorData){
response.error("Uh oh, something went wrong");
}
})
},
error: function(errorData){
console.log("Error: ",errorData);
}
});
response.success(successMsg);
});
The code actually runs without any error, but it is not updating the values in the database. Here is how I am calling these cloud functions in js/index.js
$(".update-user").click(function(){
Parse.Cloud.run("updateUserName", {id: $(this).data("id"), username: $(".uname").val()},
{
success: function(successData){
console.log("username updated successfully.");
$("#editModal").modal("hide");
$(".edit-modal").hide();
},
error: function(errorData){
}
});
});
The contents that I see in the firefox console username updated successfully.
The contents that I see in parse.com console
I2015-12-11T06:15:13.361Z]v106 Ran cloud function updateUserName for user chfgGhaPEl with:
Input: {"id":"MAvm9FlGgg","username":"testuser12"}
Result: username updated successfully.
But this line of code userRecord.set("resetToken", "Apple"); is updating the resetToken column in the database, but why not it is not letting me update the username/password(or other columns that I didn't try updating) columns ?
I analyse your code. Instead of using get to retrieve correlated user, use first where you specify the user id as query constraint. One example (working) code is below where user information is updated in Parse User table. Hope this helps.
Regards.
Parse.Cloud.define("updateUser", function(request, response)
{
Parse.Cloud.useMasterKey();
var query = new Parse.Query(Parse.User);
var objectId = request.params.objectId;
var username = request.params.username;
var email = request.params.email;
var userType = request.params.userType;
var password = request.params.password;
query.equalTo("objectId", objectId);
query.first({
success: function(object)
{
object.set("username", username);
object.set("email", email);
object.set("userType", userType);
object.set("password", password);
object.save();
response.success("Success");
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
response.error("Error");
}
});
});
What worked for me is
//cloud/main.js
Parse.Cloud.define("updateUserName", function(request, response){
if(!request.user){
response.error("Must be signed in to update the user");
return;
}
if(request.params.IsAdmin == false){
response.error("Only the administrators can edit username.");
return;
}
Parse.Cloud.useMasterKey();
// var userId = request.params.Id; --> I guess he was the main culprit, the params and the actual column value should match. Instead of passing Id from my client code(see below) I just passed objectId and it worked.
var userId = request.params.objectId;
// var userName = request.params.username;
var name = request.params.name;
// var User = Parse.Object.extend("User");
var updateQuery = new Parse.Query(Parse.User);
console.log("id from params: "+userId);
updateQuery.equalTo("objectId", userId);
updateQuery.first({
success: function(userRecord){
// userRecord.set("username", userName);
userRecord.set("name", name);
userRecord.save(null,{
success: function(successData){
response.success("username updated successfully.");
userRecord.fetch();
},
error: function(errorData){
console.log("Error while updating the username: ",errorData);
}
});
},
error: function(errorData){
console.log("Error: ",errorData);
response.error(errorData);
}
});
});
// js/index.js
/* initially I was using Id instead of objectId, the field names are case
sensitive
Parse.Cloud.run("updateUserName", {id: $(this).data("id"), name: $(".name").val(),IsAdmin: Parse.User.current().get("IsAdmin") },*/
Parse.Cloud.run("updateUserName", {objectId: $(this).data("id"), name: $(".name").val(),IsAdmin: Parse.User.current().get("IsAdmin") },
{
success: function(successData){
console.log("username updated successfully.");
$("#editModal").modal("hide");
$(".edit-user-server-error").html("");
$(".edit-modal").hide();
location.reload();
},
error: function(errorData){
console.log(errorData);
$(".edit-user-server-error").html("");
$(".edit-user-server-error").html(errorData.message);
}
});
So I had referred to this post and it gave me an hint, based on that I just did one trial and error thing and got it working.
You can pass any sort of values in the parameters to this Cloud Function, so you might want to specify exactly which properties you wish to update in this manner. Also, don't forget to actually validate that request.user is allowed to perform such an operation.
Parse doesn't support HTTP PUT requests to save the data. Hence we need to use PUSH request containing a method call to save the data.
However it has to have a the line, Parse.Cloud.useMasterKey(); before calling the save method.

How can I assign multiple roles to one user in Parse?

I've written a bit of Cloud Code which executes after every user is saved. Inside, I would like to add the user to two roles, Alpha and Free, but this code only successfully adds new users to the Alpha role; the Free role has no data in the users table. Is there a way in Parse to assign users multiple roles?
Here is my Cloud Code.
Parse.Cloud.afterSave(Parse.User, function(request, response) {
Parse.Cloud.useMasterKey(); // grant administrative access to write to roles
var user = request.object;
query = new Parse.Query(Parse.Role);
query.equalTo("name", "Alpha");
query.first ( {
success: function(object) {
object.relation("users").add(user);
object.save();
response.success("The user has been authorized.");
},
error: function(error) {
response.error("User authorization failed!");
}
});
query = new Parse.Query(Parse.Role);
query.equalTo("name", "Free");
query.first ( {
success: function(object) {
object.relation("users").add(user);
object.save();
response.success("The user has been authorized.");
},
error: function(error) {
response.error("User authorization failed!");
}
});
});
The problem is sequencing. We need all of the queries and saves to complete before response.success() is called. As it is now, the timing of actions in the code is not deterministic. Clean it up by using the promises returned by the parse sdk...
Parse.Cloud.afterSave(Parse.User, function(request, response) {
Parse.Cloud.useMasterKey(); // grant administrative access to write to roles
var user = request.object;
query = new Parse.Query(Parse.Role);
query.equalTo("name", "Alpha");
query.first().then(function(object) {
object.relation("users").add(user);
return object.save();
}).then(function() {
query = new Parse.Query(Parse.Role);
query.equalTo("name", "Free");
return query.first();
}).then(function(object) {
object.relation("users").add(user);
return object.save();
}).then(function() {
response.success("The user has been authorized.");
}, function(error) {
response.error("error: " + error.message);
});
});

Adding contraints to a column on Parse Data

I'm saving some objects into tables on my Parse Data. But I need to add a constraint or make sure that the data i'm trying to insert is unique. I'm using something like the following code. But i want to guarantee that the eventId (that I'm getting from facebook API) is unique in my tables, so i don't have any redundant information. What is the best way to make it work?
var Event = Parse.Object.extend("Event");
var event = new Event();
event.set("eventId", id);
event.set("eventName", name);
event.save(null, {
success: function(event) {
console.log('New object created with objectId: ' + event.eventId);
},
error: function(event, error) {
console.log('Failed to create new object, with error code: ' + error.message);
}
});
Update:
I'm calling it inside a httpRequest. The following is pretty much what I have and I cant figure out just how to call a beforeSave inside it.
Parse.Cloud.define("hello", function(request, response) {
var query = new Parse.Query("Location");
query.find({
success: function(results) {
console.log(results);
var totalResults = results.length;
var completedResults = 0;
var completion = function() {
response.success("Finished");
};
for (var i = 0; i < totalResults; ++i){
locationId = results[i].get("locationFbId");
Parse.Cloud.httpRequest({
url: 'https://graph.facebook.com/v2.2/'+locationId+'/events?access_token='+accessToken,
success: function(httpResponse) {
console.log(httpResponse.data);
console.log("dsa"+locationId);
for (var key in httpResponse.data) {
var obj = httpResponse.data[key];
for (var prop in obj) {
var eventObj = obj[prop];
if (typeof(eventObj) === 'object' && eventObj.hasOwnProperty("id")) {
var FbEvent = Parse.Object.extend("FbEvent");
var fbEvent = new FbEvent();
fbEvent.set("startDate",eventObj["start_time"]);
fbEvent.set("locationFbId", locationId);
fbEvent.set("fbEventId", eventObj["id"]);
fbEvent.set("fbEventName", eventObj["name"]);
Parse.Cloud.beforeSave("FbEvent", function(request, response) {
var query = new Parse.Query("FbEvent");
query.equalTo("fbEventId", request.params.fbEventId);
query.count({
success: function(number) {
if(number>0){
response.error("Event not unique");
} else {
response.success();
}
},
error: function(error) {
response.error(error);
}
});
});
}
}
}
completedResults++;
if (completedResults == totalResults) {
completion();
}
},
error:function(httpResponse){
completedResults++;
if (completedResults == totalResults)
response.error("Failed to login");
}
});
}
},
error: function() {
response.error("Failed on getting locationId");
}
});
});
So this is occurring in Cloud Code correct? (Im assuming since this is Javascript)
What you could do is create a function that occurs before each "Event" object is saved and run a query to make sure that the event is unique (query based off of "eventId" key, not objectId since the id comes from Facebook). If the event is unique, return response.success(), otherwise return response.error("Event not unique")
EX:
Parse.Cloud.beforeSave("Event", function(request, response) {
if(request.object.dirty("eventId")){
var query = var new Parse.Query("Event");
query.equalTo("eventId", request.object.eventId);
query.count({
success: function(number) {
if(number>0){
response.error("Event not unique");
} else {
response.success();
}
},
error: function(error) {
response.error(error);
}
});
} else {
response.success();
}
});
Parse.Cloud.define("hello", function(request, response) {
var query = new Parse.Query("Location");
query.find({
success: function(results) {
console.log(results);
var totalResults = results.length;
var completedResults = 0;
var completion = function() {
response.success("Finished");
};
for (var i = 0; i < totalResults; ++i){
locationId = results[i].get("locationFbId");
Parse.Cloud.httpRequest({
url: 'https://graph.facebook.com/v2.2/'+locationId+'/events?access_token='+accessToken,
success: function(httpResponse) {
console.log(httpResponse.data);
console.log("dsa"+locationId);
for (var key in httpResponse.data) {
var obj = httpResponse.data[key];
for (var prop in obj) {
var eventObj = obj[prop];
if (typeof(eventObj) === 'object' && eventObj.hasOwnProperty("id")) {
var FbEvent = Parse.Object.extend("FbEvent");
var fbEvent = new FbEvent();
fbEvent.set("startDate",eventObj["start_time"]);
fbEvent.set("locationFbId", locationId);
fbEvent.set("fbEventId", eventObj["id"]);
fbEvent.set("fbEventName", eventObj["name"]);
// Our beforeSave function is automatically called here when we save it (this will happen every time we save, so we could even upgrade our method as shown in its definition above)
fbEvent.save(null, {
success: function(event) {
console.log('New object created with objectId: ' + event.eventId);
},
error: function(event, error) {
console.log('Failed to create new object, with error code: ' + error.message);
}
});
}
}
}
completedResults++;
if (completedResults == totalResults) {
completion();
}
},
error:function(httpResponse){
completedResults++;
if (completedResults == totalResults)
response.error("Failed to login");
}
});
}
},
error: function() {
response.error("Failed on getting locationId");
}
});
});
This can also be accomplished before ever calling the save by querying and only saving if the query returns with a number == 0.
Summary: For those joining later, what we are doing here is checking to see if an object is unique (this time based on key eventId, but we could use any key) by overriding Parse's beforeSave function. This does mean that when we save our objects (for the first time) we need to be extra sure we have logic to handle the error that the object is not unique. Otherwise this could break the user experience (you should have error handling that doesn't break the user experience anyway though).

Getting multiple queries from parse.com

I am using the following code to get a single entry from parse.com in my corona sdk app. Is there a way to get two entries at the same time, say x1=55.317269 and x1=55.21354. I need the corresponding values for both entries rather than one.
local params = {x1=55.317269}
params.headers = headers
params.body = json.encode ( params )
network.request( "https://api.parse.com/1/functions/getFeatured","POST",getData,params)
The following is my cloud function.
Parse.Cloud.define("getFeatured", function(request, response) {
var query = new Parse.Query("testClass");
query.equalTo("x1", request.params.x1);
query.find({
success: function(results) {
var sum = 0;
sum = results[1].get("y1");
response.success(sum);
},
error: function() {
response.error("movie lookup failed");
}
});
});
Try this -
Parse.Cloud.define("getFeatured", function(request, response) {
var query = new Parse.Query("testClass");
query.containedIn("x1", ARRAY_OF_VALUES_TO_BE_MATCHED);
query.find({
success: function(results) {
// Modify/Create Proper Response Here
respones.success(results);
},
error: function() {
response.error("movie lookup failed");
}
});
});

Resources