Not passing proper parameters Parse.com - javascript

I am developing an application using Parse.com
According to it's error system, it's saying I'm not passing the proper parameters when trying to "login."
Here is my code:
function signInUser() {
Parse.initialize("", "");
var username = this.$("#signin-username").val();
var password = this.$("#signin-password").val();
Parse.User.logIn(username, password, {
success: function(user) {
alert("You successfully logged in!");
},
error: function(user, error) {
alert("Error: " + error.code + " " + error.message);
}
});
}

I was board at work so I made up a simple register and login so you can compare with your code with mine.

Related

UserCannotBeAlteredWithoutSessionError when updating PFUser on Parse from Heroku node.js app

I'm trying to update a PFUser in my Parse database from a node.js app running on Heroku. I'm calling the Parse cloud function from an iOS app.
Here's the part of the code I use to update the user on parse as well as creating the user on Stripe (the Stripe part works fine):
Parse.Cloud.define("createCustomerWithCreditCardToken", function(request, response) {
var userId = request.user.id;
var sourceId = request.params.creditCardToken;
var customerId;
var userSessionToken = request.user.getSessionToken();
console.log('userId: ' + userId + ' source: ' + sourceId + ' userSessionToken: ' + userSessionToken);
stripe.customers.create({
source: sourceId,
description: userId
}, function(error, customer) {
if (error !== null) {
response.error('error creating customer: ' + error);
}else {
var userQuery = new Parse.Query('User');
userQuery.equalTo('objectId', userId);
userQuery.first({sessionToken: userSessionToken}).then(function(user) {
console.log('user from parse query: ' + user.get("username"));
user.set("stripeCustomerId", customer.id);
user.save(null, {
success: function(parseCustomer) {
console.log('customer saved to parse: ' + parseCustomer);
},
error: function(error, parseCustomer) {
console.log('customer save failed: ' + JSON.stringify(error, null, 2) + ' with error: ' + JSON.stringify(parseCustomer,null, 2));
}
});
});
customerId = customer.id;
console.log('customerId: '+ customerId);
// response.success(customer);
response.success('Customer: ' + JSON.stringify(customer, null, 2) + 'error: ' + error);
}
});
});
I get the following error log output when I run this:
error log output
error: { "code": 206, "message": "Parse::UserCannotBeAlteredWithoutSessionError" }
In this post the current user concept in a node.js app context is discussed by a Parse engineer.
Also in Cloud Code, the concept of a method that returns the current
user makes sense, as it does in JavaScript on a web page, because
there’s only one active request and only one user. However in a
context like node.js, there can’t be a global current user, which
requires explicit passing of the session token.
Essentially he advises to do this:
Parse.Cloud.define('findBacon', function(req, res) {
var token = req.user.getSessionToken();
var query = new Parse.Query('Bacon');
// Pass the session token to the query
query.find({ sessionToken: token }).then( ... );
});
I have also tried using {useMasterKey:true} instead of {sessionToken:userSessionToken} which produces the same error.
I might just be missing some obvious detail, but I just can't seem to find it. Any ideas on how to solve this are greatly appreciated.
Turns out there's a third way of handling credentials:
Parse.Cloud.useMasterKey();
I placed this line in the beginning of the entire method, that did it for me. I'm not sure of the implications of giving the whole function these credentials though.
I'm not sure when you would use the other options either.
If someone comes across this and would like to elaborate, I'll be happy to give the right answer to a good explanation of when to grant which credentials.

Parse.com JavaScript query error handling does not work

I'm playing around with the Parse backend and NodeJS but I have a problem right now and I am not able to figure it out. I have a get request like this.
app.get("/movie", function (req, res) {
var Review = Parse.Object.extend("Review");
var query = new Parse.Query(Review);
var movie = req.query.movie;
query.equalTo("movie", movie);
query.first({
success: function (movie) {
console.log("Success");
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});});
This works fine but the error handling kinda doesn't. If, for example, I change
query.equalTo("movie", movie);
to query.equalTo("movie", "xyz");
or query.equalTo("abc", "xyz");
which does not exist in my table, I'm still getting the success statement. And yes, I have restarted the server every time.
Update
I tried the same query using the iOS SDK(Swift) and here I get into the error case. I always get the same error though, which shouldn't be, but at least I get an error while in the JS sample I always get into the success case.
I believe query.first() will not error if it does not find a "first" object. You can check for (movie == null) on the success return.
Update:
Try writing it this way:
app.get("/movie", function (req, res) {
var movie = req.query.movie;
var query = new Parse.Query("Review");
query.equalTo("movie", movie);
query.first().then(function (movie) {
// Success
console.log("Success");
}, function (error) {
// Error
console.log("Error: " + error.code + " " + error.message);
});
});
query.find() always success even if there is no match data in your table/collections
Let's try it
query.find().then(function (movies) {
if(movies.length > 0){
console.log("success");
}else{
console.log("query success but no data found");
}
}, function (error) {
// Error
console.log("Error: " + error.code + " " + error.message);
});

Parse Javascript - Adding user error

I created a factory in angularJS to store data to Parse User object. Every time I click to process the details and open an account for the user, it shows the following error in console:
Failed to load resource: https://api.parse.com/1/users the server
responded with a status of 400 (Bad Request)
I checked if the service parameter is valid with attributes content, and yes it has content (not empty). This is the service body:
.factory('CreateUserService', function() {
return {
createAccount: function(user) {
console.log("Service User: " + user.name);
var parseUser = new Parse.User();
parseUser.set("username", user.username);
parseUser.set("email", user.username);
parseUser.set("name", user.username);
parseUser.set("password", user.username);
parseUser.set("mobile", user.username);
/*Attempt to create user in DB*/
parseUser.signUp(null, {
success: function(parseUser) {
// Hooray! Let them use the app now.
//alert("success!");
return 1;
},
error: function(parseUser, error) {
// Show the error message somewhere and let the user try again.
//alert("Error: " + error.code + " " + error.message);
return error;
}
});
}
}
});
I added the Parse CDN in the index.html of my application with:
<script src="http://www.parsecdn.com/js/parse-1.6.7.min.js"></script>
Update: In Parse API Guide, this is the body of the signup:
user.signUp(null, {
success: function(user) {
// Hooray! Let them use the app now.
},
error: function(user, error) {
// Show the error message somewhere and let the user try again.
alert("Error: " + error.code + " " + error.message);
}
});
The user object in Parse (I review through the browser) is not showing any changes to the rows number hence user not added. Any idea what is going wrong?
Thanks
Update: When I deleted the existing empty user object in Parse and ran the code, it worked and created a user Object with all columns specified in the code. Then if I try to add another user, I get a POST error. There must be a way around this since signup method by parse surely considered adding multiple users to the User object.

unable to get email address, location, values using oauth.io

I am integrating facebook, twitter, github, linkedin using https://oauth.io/signin third party site.
I integrated facebook and was able to successfully get id, name, gender properties directly but am seeing difficulty in getting email address, location values.
In oauth.io site, I even added scope permissions for facebook
I am using the below code to get info of the logged in user.
OAuth.popup('facebook')
.done(function (result) {
res = result;
result.me().done(function (response) {
debugger;
console.log('me ' + response.name);
console.log('me ' + response.email);
});
})
.fail(function (error) {
alert('fail');
});
I even tried filtering the results only to give email, birthdate values using
OAuth.popup('facebook')
.done(function (result) {
res = result;
result.me(['email', 'birthdate', 'location']).done(function (response) {
debugger;
console.log('me ' + response.name);
console.log('me ' + response.email);
});
})
.fail(function (error) {
alert('fail');
});
But it just returned empty object.
Can some one let me know if I am missing something?
I was able to get the required fields for facebook using
result.get('/me?fields=name,email,gender,birthday').done(function (response) {
console.log('me ' + response.name);
});
But the same code is not working for twitter.
Still looking for an answer which works in a generic way for most of the apis

order of operations parse cloud

I was wondering what the order of operations are in the parse cloud. I currently am running into trouble trying to do multiple things at once inside my job on the cloud. I am currently trying to make an HTTP request for each user in my user table (there are 2) and then get the webpage or httprequest.text from the webpage. My code is as followed
Parse.Cloud.job("WeatherUpdates2", function(request, status) {
var query = new Parse.Query(Parse.User);
query.exists("City");
query.each(
function(result){
var object = result;
console.log(object.id);
var city = object.get("City");
city = city.replace(" ", "");
city = city.replace(" ", "");
// get the country code.
var countryCode = object.get("CountryCode");
var woeidUrl = "http://where.yahooapis.com/v1/places.q(" + city + "," + countryCode + ")?appid=(appid)";
console.log(woeidUrl);
var woeID = "An error occured retrieving your WOEID.";
Parse.Cloud.run('httpRequest', { url: woeidUrl }, {
success: function(WOEID) {
console.log("returned from http request.");
},
error: function(error) {
console.log("Error occurred while making request for WOEID " + error.message);
status.error(error.message);
}
});
},
{
success: function() {
// results is an array of Parse.Object.
console.log('#Query');
status.success("Updated Records!!");
},
error: function(error) {
// error is an instance of Parse.Error.
console.log('#error');
response.error("Failed to save vote. Error=" + error.message);
}
});
});
Where the job httpRequest is:
Parse.Cloud.define("httpRequest", function(request, response) {
var webpage = "Something went wrong.";
Parse.Cloud.httpRequest({
url: request.params.url,
success: function (httpResponse) {
webpage = httpResponse.text;
webpage = webpage.toString();
response.success(webpage);
},
error: function (error)
{
console.log("Error in http request " + error.message);
response.error(error.message);
}
});
});
now I would expect to be printed would be the, object id of first user, their url, the job running, the message"returned from http request." then repeated another time for the second user and finally the job finishing with the message "Updated Records". but instead I get:
I2014-07-22T15:15:16.013Z] A5hod7qKE3
I2014-07-22T15:15:16.045Z] http:/where.yahooapis.com/v1/places.q(Draper,US)?appid=(appid)
I2014-07-22T15:15:16.053Z] GmuqxpTUpM
I2014-07-22T15:15:16.066Z] http:/where.yahooapis.com/v1/places.q(SaltLakeCity,US)?appid=(appid)
I2014-07-22T15:15:16.082Z] #Query
I2014-07-22T15:15:16.131Z] v385: Ran cloud function httpRequest with:
Input: {"url":"http://where.yahooapis.com/v1/places.q(SaltLakeCity,US)?appid=(appid)"}
Result:
2487610TownSalt Lake CityUnited StatesUtahSalt LakeSalt Lake City40.777561-111.93071740.699890-112.10125740.852951-111.739479511America/Denver
I2014-07-22T15:15:16.141Z] v385: Ran cloud function httpRequest with:
Input: {"url":"'http://where.yahooapis.com/v1/places.q(Draper,US)?appid=(appid)'"}
Result:
http://where.yahooapis.com/v1/schema.rng'" xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" yahoo:start="0" yahoo:count="1" yahoo:total="11">2393601TownDraperUnited StatesUtahDraper8402040.524139-111.86627240.442921-111.92212740.544361-111.78304349America/Denver
I removed 1 / from both the printing urls so I could posts this because I don't have high enough rep to post more than 2 links. I also have put in my appid into the (appid) so the url does return to me the according woeid from yahoo.com. The problem here being I can't actually get into the success function of the http request job. Any help is greatly appreciated!
EDIT:
I was trying to figure out how to run a job in a for loop but couldn't get it to work. I tried to make a promise and do what Fosco said below, but have had no luck. Here is my code.
for(var i = 0; i < woeIDs.length; i++)
{
console.log("hello");
var weatherURL = "http://weather.yahooapis.com/forecastrss?w=" + woeIDs[i] + "&u=f";
var promise = Parse.Cloud.run('httpRequest', { url: weatherURL }, {
success: function(WOEID) {
console.log("got here");
},
error: function(error) {
console.log("Error occurred while making request for WOEID " + error.message);
status.error(error.message);
}
});
Parse.Promise.when([promise]).then(function() { status.success(); });
}
if I run this code I get a hello twice then the two job calls then the "got here" message once. I have tried adding a return statement to it and with no luck also. Thanks again for all the help!!!
The issue here is that inside the each callback, you need to return the promise from your cloud function call if you want to ensure the tasks complete, and have it wait before going to the next object.
Simplified and using promises:
query.each(function(object) {
...
return Parse.Cloud.run(...);
}).then(function() {
// success
}, function(err) {
// error
});
For looping over a promise-returning function like Parse.Cloud.run:
var promises = [];
for (i = 0; i < 5; i++) {
promises.push(Parse.Cloud.run('...', {}));
}
Parse.Promise.when(promises).then(function() {
// all done
}, function(err) {
// error
});

Categories

Resources