Is cloud code sessionToken change in parse server 2.4.x? - parse-platform

I just updated parse-server from 2.2.x to 2.4.x and my cloud code using sessionToken did not work. Below is simple cloud code function:
Parse.Cloud.define('find_device', function(request, response) {
var user = request.user;
if(user){
var token = user.getSessionToken();
console.log("User token " + token);
var query = new Parse.Query('devices');
query.equalTo('deviceId', "389125651274465");
query.find({ sessionToken: token })//<- sessionToken does not work
.then(function(messages) {
response.success(messages);
},function(error){
console.log(error);
response.error("error");
});
}else{
response.error("error");
}
});
It uses {sessionToken: token} to query. This code worked before, but now it does not work in parse-server 2.4.x. I received error
ParseError { code: undefined, message: 'unauthorized' }
I don't know if anything change in parse-server version 2.4.x. If i change to {useMasterKey:true} it works ok, but in this case i want to use user's token to query. Thank for your help.

They havent really changes the the ... query.find({sessionToken : token}) ... part, but maybe they have changed how User.getSessionToken() works.
The documentations says :
String getSessionToken( )
Returns the session token for this user, if
the user has been logged in, or if it is the result of a query with
the master key. Otherwise, returns undefined.
Returns: the session token, or undefined
Since in case of cloud-code, neither the user is logged in, not its the result of a query using masterKey, getSessionToken() should actually behave that way only.
To correct this, what I would suggest is, rather than making the query on-behalf of the user in the cloud-code(and thus on the server), just let the user make it from the client.

Related

GET request with query parameters returns 403 error (signature does not match) - AWS Amplify

Problem
I was trying to use 'aws-amplify' GET API request with query parameters on the client side, but it turned out to be Request failed with status code 403, and the response showed:
"message":"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
Note: React.js as front-end, Javascript as back-end.
My code
Front-end
function getData() {
const apiName = 'MyApiName';
const path = '/path';
const content = {
body:{
data:'myData',
},
};
return API.get(apiName, path, content);
}
Back-end
try {
const result = await dynamoDbLib.call("query", params);
} catch (e) {
return failure({ status: false });
}
What I did to debug
The GET lambda function works fine in Amazon Console (Tested)
If I change the backend lambda function so that the frontend request can be made without parameters, i.e. return API.get(apiName, path), then no error shows up.
My question
How can I make this GET request with query parameters works?
I changed GET to POST (return API.post()), everything works fine now.
If anyone can provide a more detailed explanation, it would be very helpful.

Parse server Having to Logout/Login on each deployment. Session getting destroyed?

Issue Description
Migrated from Parse.com to Parse Server (Sashido hosting). Whenever I deploy my cloud code, I had to logout and login on the client app (iOS) to get results. Without re-logging in, I get empty results. The session token on the client side matches with DB. My request.user prints correctly. Only the queries are not working, no session errors but empty results (array or object). This happens to all queries and it was working fine in Parse.com platform. I have ACLs defined for each row and ACL in request.user is also correct but still no results.
Steps to reproduce
Client iOS code
let configuration = ParseClientConfiguration {
$0.applicationId = PARSE_APPLICATION_ID
$0.clientKey = PARSE_CLIENT_KEY
$0.server = PARSE_SERVER_URL
$0.localDatastoreEnabled = true
}
Parse.initializeWithConfiguration(configuration)
PFUser.enableRevocableSessionInBackground()
Server
Parse.Cloud.define("getPastWalks", function(request, response) {
console.info("user:: " + JSON.stringify(request.user) + JSON.stringify(request.params));
var fromDate = request.params.fromDate;
var toDate = request.params.toDate;
var walk = Parse.Object.extend("Walk");
var pastWalksQuery = new Parse.Query(walk);
pastWalksQuery.greaterThanOrEqualTo("dateAndTime", fromDate);
pastWalksQuery.lessThanOrEqualTo("dateAndTime", toDate);
pastWalksQuery.descending("dateAndTime");
pastWalksQuery.include("service");
pastWalksQuery.limit(request.params.limit);
pastWalksQuery.find().then(function(walks) {
console.info("past walk:: " + JSON.stringify(walks));
response.success(walks);
}, function(error) {
response.error(error);
})
});
Expected Results
The above code should retrieve 'all walks for that particular request.user'.
Actual Outcome
But I am getting empty array. When I logout and login, new session token is generated and it works. Without re-logging, no session token errors, only empty array.
Environment Setup
Server
parse-server version : 2.2.25-1
Localhost or remote server? : Sashido Hosting
Database
MongoDB version: -
Localhost or remote server? : Sashido Hosting
I had to pass sessionToken in the query
pastWalksQuery.find({sessionToken: request.user.getSessionToken()})
https://github.com/ParsePlatform/parse-server/issues/3456

Making a POST request using Superagent, AWS Lambda, API Gateway

I am using AWS Lambda and API Gateway to create a custom endpoint for load tests. I have uploaded my handler function which is in a file, along with the node modules needed for the function in a zip, and set up the API Gateway API correctly according the instructions (in line with the way that I had made it work before), but I keep getting the error: {"error": "Missing Authentication Token"}. Everything I have seen online thus far points to the idea that the url that I am passing in with the POST request is invalid, but I have made a similar endpoint work with a GET request. As far as I know I have set up the POST request (using Superagent) correctly, and am passing in a valid access-token, as well as hardcoded params as part of the URL (valid params).
// Dependencies
var request = require('superagent');
var sync = require('synchronize');
exports.handler = function(event, context) {
sync.fiber(function() {
// Grabs params passed into the URL as a JSON object
var querystring = (event.querystring);
// Replaces params with an updated version which includes a single quotation
var queryStringUpdate = querystring.replace(/=/g, ":").replace(/}/g, "'}").replace(/:/g, ":'").replace(/,/g, "',");
// Updates the param information and sets it as a new string
eval('var queryString2 =' + queryStringUpdate);
// Define specific query params to be used in the REST calls
var userId = (queryString2.userId === undefined ? '229969' : queryString2.userId);
var roomdId = (queryString2.roomId === undefined ? '4' : queryString2.roomId);
var inviterId = (queryString2.inviterId === undefined ? '212733' : queryString2.inviterId);
var createInvitePost = function() {
request
.post('https://some_url/v2/invites/212733/create')
.set({'access-token': 'some_access_token'})
.set('Content-Type', 'application/json')
.query({user_id: "229969"})
.query({room_jid: "4"})
.end(function(err, res){
if (err) {
context.fail("Uh oh, something went wrong");
} else {
context.done(null, "Hurray, it worked!!");
}
});
};
try {
createInvitePost();
} catch(errOne) {
alert("No bueno!!");
}
});
};
Any thoughts on this?? Thanks
I usually get this error when I've missed some part of the URL needed for my API. In the past it's either been the name of the stage, misspelled resource name, or a missing Path parameter.
I'm from the Api Gateway team.
As others have said, the most common cause of the 403 response you're getting is an incorrect path/method. I'm not familiar with Superagent, but if you've run the same request in Postman and cURL then I would be surprised if you had the wrong path/method.
Maybe also check on a wire log if possible, to make sure that your querystring logic isn't appending a forward slash prior to the '?'.
Some things to check:
Have you deployed any recent changes to your API?
Is the stage 'v2' (I'm assuming that's the stage) pointing at a deployed version of the API that has the POST to invites/212733/create?
The 'access-token' should have no effect on the Api Gateway layer. If you're trying to use a native Api Gateway Api Key, the header is 'x-api-key'.
Jack

Parse.User.save() doesn't work with Facebook API

I'm using the Facebook SDK to auth a user, and trying to save the user's email to the record after authenticating. However, I keep getting an error on the save call.
The code in question:
Parse.FacebookUtils.logIn({
access_token: authResponse.access_token,
expiration_date: expire_date.toISOString(),
id: response.id
},
{
success: function(user) {
console.log("success!");
user.set({"email":response.email});
user.save();
window.App.navigate("#myplaces", {trigger:true});
},
...
That user.save() call returns error occurred: http://www.parsecdn.com/js/parse-1.1.14.min.js:1: TypeError: 'undefined' is not an object.
According to the docs, I have to be in an authentication call (".logIn", etc.) to perform save(), so I'm wondering if this still works with Parse.FacebookUtils.logIn. Seems like it should.
Ideas as to why this isn't working? The ideal behavior is to log the user in, retrieve information from the FB response, and save that back to the user record on Parse.
Thanks!
Justin
Not sure about this but I had the same problem in Cloud Code and I used success/error callbacks when calling save(...):
user.save(null, {
success: function(){
// Code
},
error: function(){
// Code
}
});
See also here: https://parse.com/questions/saving-a-relation-on-the-current-user

Parse.com: How do I return the session token?

I've created a signUp function for my app to call, and the Parse.com backend JS code to sign the user up.
Sure enough, the user will appear in the database. Heck, I even got the verification email to be sent (something that was much harder than it should be. It is a setting under the "settings" section of the main parse backend, not something that is programatically set).
Now I'm trying to get the sessionToken from the newly signed up user. Returning the "user" object on success of the signup and inspecting, I don't see a "sessionToken". I also don't see a sessionToken in the user database...
Can somebody give me some code that will return the sessionToken?
Here is the relevant code:
user.signUp(null, {
success: function(user) {
response.success(user);
},
error: function(user, error) {
alert("Error: " + error.code + " " + error.message);
}
});
I don't get a sessionToken here. Where do I get it from?
I think you need to check on your local storage:
Local Storage Report
There are 5 items in local storage, using 0.9KB (0.001MB)
Parse/bqfSO3dVttG65a8CIkC1SdqC0CCqiqYsp1EfsjL8/currentUser
username XXX#gmail.com
email XXX#gmail.com
objectId oVGKr1vdbG
createdAt 2013-03-20T17:17:54.815Z
updatedAt 2013-03-20T17:17:54.815Z
_id oVGKr1vdbG
_sessionToken 12aob7us2lj18pkaddkbvsal7
That is what Parse checks when you do:
var currentUser = Parse.User.current();
var sessionToken = Parse.User.current()._sessionToken;
The code i ended up using looked something like this:
endpoint : "https://api.parse.com/1/login",
parameters : getTheLoginParametersFrom(user),
success : function(response) {
tablesModule.saveSessionId(response.sessionToken);
}
}
Where the result from the "login" is the response.sessionToken.

Resources