CloudCode User afterSave requires useMasterKey - why? - parse-platform

It woked while ago, but suddenly stopped. Looks like it has something to do with session migration but I don't know why and how to deal with it.
So I've got simple cloud code sample:
Parse.Cloud.define("hello", function(request, response) {
response.success("Hello world!");
});
It works fine naturally.
And I want to run it from afterSave trigger like this:
Parse.Cloud.afterSave(Parse.User, function(request) {
Parse.Cloud.run('hello', { test: 'test'}, {
success: function(success) {
console.log(' Hello success.');
},
error: function(error) {
console.error(' hello failed.');
console.error("Got an error " + error.code + " : " + error.message);
}
});
});
Everything like parse commanded in docs
But when I save user it produces error:
I2015-08-14T06:33:16.709Z] hello failed.
I2015-08-14T06:33:16.711Z]Got an error 209 : invalid session token
How can it be? Am I doing something wrong?
[EDIT]
putting this at the beginning of afterSave trigger helped:
Parse.Cloud.useMasterKey();
I understand this is kind of root command, omitting all ACL restrictions. Can't see where I crossed such restrictions while running simple Hello World function example.

Related

Cloud Code Error in Saving user

I have a function in my cloud code, which works, but I'm not sure how to fix a problem related to it.
Original Problem:
Parse.Cloud.define("assignTokenToUser", function(request, response) {
console.log("Inside assignTokenToUser");
var token = Math.random().toString(30).substring(7);
query = new Parse.Query("User"),
email = request.params.email;
query.equalTo("username", email);
query.find({ useMasterKey: true }).then(function(results) {
query.first({
success: function(user) {
// Successfully retrieved the object.
user.set("emailToken", token);
user.save();
console.log("success...");
response.success(token);
},
error: function(error) {
console.log("error 1...");
response.error(error);
}
});
}, function(error) {
console.log("error 2...");
response.error(error);
});
});
This seemed to be a common problem after scanning the internet, and my analysis is that the useMasterKey needs to be passed each time we use the query object. Correspondingly, my log file shows that when trying to save the user, it gives a Code 206 error.
Log file output:
Inside assignTokenToUser
success...
^[[32minfo^[[39m: Ran cloud function assignTokenToUser for user undefined with:
Input: {"email":"maryam.zafar#emumba.com"}
Result: "p66qm34jd80p0j6ne03fe1q7f" functionName=assignTokenToUser, email=maryam.zafar#emumba.com, user=undefined
going to send an email... with result: p66qm34jd80p0j6ne03fe1q7f
fullLink: https://beatthegym.com/emailVerified?username=maryam.zafar#emumba.com&token=p66qm34jd80p0j6ne03fe1q7f
^[[31merror^[[39m: Error generating response. ParseError { code: 206, message: 'Cannot modify user 4m0VZFsKVt.' } code=206, message=Cannot modify user 4m0VZFsKVt.
[object Object]
So I went on to change my code to the following:
Code:
Parse.Cloud.define("assignTokenToUser", function(request, response) {
console.log("Inside assignTokenToUser");
var token = Math.random().toString(30).substring(7);
query = new Parse.Query("User"),
email = request.params.email;
query.equalTo("username", email);
query.find({ useMasterKey: true }).then(function(results) {
console.log("inside query.find...");
query.first(null, { useMasterKey: true }).then(function(user) {
console.log("inside query.first...");
// Successfully retrieved the object.
user.set("emailToken", token);
user.save(null, { useMasterKey: true }).then(function() {
console.log("inside user.save...");
response.success();
}, function(error) {
response.error(error);
});
response.success(token);
},
function(error) {
console.log("error 1...");
response.error(error);
});
}, function(error) {
console.log("error 2...");
response.error(error);
});
});
Log file:
Inside assignTokenToUser
inside query.find...
inside query.first...
^[[32minfo^[[39m: Ran cloud function assignTokenToUser for user undefined with:
Input: {"email":"maryam.zafar#emumba.com"}
Result: "tqc8m9lo2tcsrqn69c3q0e1q7f" functionName=assignTokenToUser, email=maryam.zafar#emumba.com, user=undefined
inside user.save...
^[[32minfo^[[39m: Ran cloud function assignTokenToUser for user undefined with:
Input: {"email":"maryam.zafar#emumba.com"}
Result: undefined functionName=assignTokenToUser, email=maryam.zafar#emumba.com, user=undefined
[object Object]
Now, the log file gives me a user as "undefined", and the call to the function gives me a pending status in the Chrome Network tab in the Inspector tool, until it turns into 502, and then the request is auto generated by the browser again. All other requests get a correct 200 response.
However, the data seems to be saved.. the record against this email address saves the token generated correctly. But the request from the browser fails and the user is "undefined" while in the original log file, I see the correct user Id... everytime it fails, the function automatically runs again (because the browser is generating another request everytime it gets a 502) and since it is actually supposed to send an email, it's running again and again keeps on generating infinate emails...
Thank you in advance..
Understood this finally:
The user will remain undefined until and unlesss I obtain it using the Parse.User.current() method. The data does save into the database because it is a forced update to the record, however until the user is aunthenticated using the current() method, it will remain undefined.
I see this is an old post but I spotted clear error in the code:
query = new Parse.Query("User")
Should be:
query = new Parse.Query(Parse.User)
Or at least:
query = new Parse.Query("_User")
As User is a predefined class in Parse.

Parse Cloud Code query causing "No such app" error

I'm running Parse Server on heroku and my cloud code functions work except when I try to query.
Parse.Cloud.define('debuggingFn', function(request, response) {
var query = new Parse.Query("Speech");
query.equalTo("speechId", "s_1456277936842");
query.find({
success: function(results) {
console.log('SUCCESS', results)
response.success("Success", results);
},
error: function(a, b) {
// ERROR CAUGHT HERE: 'Heroku | No such app'
console.log('ERROR', a, b)
response.error("Error");
}
});
});
Speech is a valid class and that speechId exists. I don't know what I'm missing?
Found the issue. My SERVER_URL config field in heroku had a typo in it. Fixed that and everything seems to work now :)

Parse.com: Retrieving object by objectId does not work. Why? It is very simple query

I got an error with message "101 Object not found."
The below code is just copy from the official guide. And I changed the class name and the objectId.
I know this is very simple query but I don't know why? Help me how to debug in this case...
This code is in cloud code. I set up "applicationId" and "masterKey" in global.json.
Thanks..
require('cloud/app.js');
Parse.Cloud.define("sample", function(request, response) {
var GameScore = Parse.Object.extend("Item");
var query = new Parse.Query(GameScore);
query.get("XXXXXX", {
success: function(gameScore) {
},
error: function(object, error) {
console.error("error: " + error.code + " " + error.message);
}
});
});
I tend to use the promise method and I'd possibly rewrite it like this...
Parse.Cloud.define("sample", function(request, response) {
var query = new Parse.Query("Item");
// put this in as a debug message.
console.log("Just checking I'm here!");
query.get("XXXXXX").then (function(item) {
response.success(item);
}, function(error) {
console.error("error: " + error.code + " " + error.message);
response.error(error);
});
});
But it should work as it is. Odd. Are you sure the error message is coming from your code?
Try adding a log before it.
EDIT
It seems that permissions were not set properly on your item object.
With iOS you can specify a default ACL for objects at create time. You can also create a custom ACL object and pass it to the object when saving it.

Parse.com fails when changing user password in beforeSave

I'm trying to reset the passwords of certain test users to a known state for integration testing purposes. However, the line
user.set("password", "testpassword");
Causes the save request to fail with:
Error Domain=Parse Code=141 "The operation couldn’t be completed. (Parse error 141.)"
Here is the relevant beforeSave code:
Parse.Cloud.beforeSave(Parse.User, function(request, response) {
var user = request.object;
Parse.Cloud.useMasterKey();
if (user.get("username").substring(0, 4) === "test") {
console.log("overwriting password for test user.");
user.set("password", "testpassword");
}
response.success();
});
for a full writeup on code 141 check out my other post:
https://stackoverflow.com/a/25360806/3204895
but in this case I'd guess that you're simply accessing the fields in a way that Parse doesn't allow, I see that you're using the master key already so the ACL shouldn't be blocking you, but try using the reserved methods for accessing username and setting the password:
if (user.getUsername().substring(0, 4) === "test") {
console.log("overwriting password for test user.");
user.setPassword("testpassword");
}
if it's that the response.success is happening at the wrong point, although the code looks just fine, account for the async with a promise:
user.save({
password: "testpassword"
}).then(function(savedUser) {
// The save was successful.
response.success(savedUser.getUsername() + "now has a password of 'testpassword'");
}, function(error) {
// The save failed. Error is an instance of Parse.Error.
response.error(user.getUsername() + " saving failed with an error | code: " + error.code + " | message: " + error.message);
});

Parse Cloud Code afterSave not working

Hey I'm using Parse as my backend and I love it but I have a problem with the afterSave hook.
Here is the Code I'm using:
Parse.Cloud.afterSave ("JGZwoelf",function (request) {
Parse.Push.send({
//Selecting the Channel
channels: [ request.object.get('JGZwoelfPush') ],
data: {
//Selecting the Key inside the Class
alert: request.object.get('AusfallInfo')
}
}, {
success: function () {
//Push was send successfully
},
error: function (error) {
//Handle error
throw "Got an error" + error.code + " : " + error.message;
}
});
});
Every time the logs console is telling me: Result:
Uncaught Got an error112 : Missing channel name.
I just don't understand what is wrong! It must be in that JavaScript code. If I enter the push notification manually everything works fine :/
Edit:
The part Parse.Push.send should look like this:
Parse.Push.send ({
//Selecting the already existing Push Channel
channels: ["JGAchtPush"], //This has to be the name of your push channel!!
data: {
//Selecting the Key inside the Class
alert: request.object.get ("AusfallInfo")
}
}, {
success: function () {
//Push was sent successfully
//nothing was loged
},
error: function (error) {
throw "Got and error" + error.code + " : " + error.message;
}
});
The channel name needs to be something like ["exampleChannel"].
Thanks in advance for any given help :)
The first argument to afterSave should be a class name, not an objectId.
following is for new folks (like me), it is the exact same code in original question, plus a few more comments, plus the correction from accepted answer. purpose is to show example of what few pieces of code need changing for this to work in your parse cloud code. thank you Constantin Jacob and bklimt.
Parse.Cloud.afterSave ("UserVideoMessage",function (request) { // name of my parse class is "UserVideoMessage"
Parse.Push.send ({
//Selecting the already existing Push Channel
channels: ["admin"], //This has to be the name of your push channel!!
data: {
//Selecting the Key inside the Class, this will be the content of the push notification
alert: request.object.get ("from")
}
}, {
success: function () {
//Push was sent successfully
//nothing was loged
},
error: function (error) {
throw "Got and error" + error.code + " : " + error.message;
}
});
});

Resources