Query in Parse Cloud returns "unauthorized" error
The command query.find always returns error in Parse Cloud. The response is Response Body : {"code":141,"error":"Error: undefined unauthorized"}.
The request is being done by Swift SDK.
It looks that Parse Cloud can't access the classes of Parse Server.
What could be possible reasons ?
Parse.Cloud.beforeSave("Message", function(request, response) {
if (!request.object.get("uniqueCode")) {
response.error('A Message must have a uniqueCode.');
} else {
var Message = Parse.Object.extend("Message");
var query = new Parse.Query(Message);
query.equalTo("uniqueCode", request.object.get("uniqueCode"));
query.find({
success: function(results) {
if (results.length > 0) {
response.success();
} else {
response.error("A Message with this uniqueCode already exists.");
}
},
error: function(error) {
response.error("Error: " + error.code + " " + error.message);
}
});
}
});
Are you requiring/defining Parse in your cloud code file? This should not be done, as it is a global we mutate during ParseServer initialization.
No, I am not. The code above is exactly the cloud/main.js file.
Are you setting any client keys in the ParseServer initialization? (rest, js, client, dotnet)... If so, remove them.
My settings is according to the Parse Server example: It is hosted in Heroku and the env vars below are configured.
var databaseUri = process.env.DATABASE_URI || process.env.MONGOLAB_URI;
var api = new ParseServer({
databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: process.env.APP_ID || 'myAppId',
masterKey: process.env.MASTER_KEY || '',
clientKey: process.env.CLIENT_KEY || ''
});
If I remove the keys ( var api = new ParseServer() ), will the server still work and will it be able to be accessed by mobile SDK ???
The request to insert a new message (that triggers the beforeSave()) is done by Swift SDK.
I think I have the same problem as @leo-one. I can't use any queries in cloud code using the parse server as they return with the error {"code":141,"error":"Error: undefined unauthorized"}.
When diving into the source to troubleshoot I saw that all the queries (find, first, get etc) results in node_modules/parse-server/node_modules/parse/lib/node/RESTController.js:ajax() sending a post request to https://api.parse.com/1/classes/MyObject which of course will result in unauthorized as parse doesn't know anything about my local app. I tried sending a get request to http://localhost:1337/parse/classes/MyObject which works and returns objects as expected.
I'm probably missing something here, but what would you have to do to get queries working in cloud code with a local parse server?
What I missed was the serverURL option. Is it the same for you @leo-one? For me the following works perfectly for local development:
app.use('/parse', new ParseServer({
databaseURI: process.env.MONGOLAB_URI || 'mongodb://localhost:27017/myApp',
cloud: __dirname + '/cloud/main.js',
appId: 'myAppId',
masterKey: 'tmp_master_key',
serverURL: 'http://localhost:1337/parse'
}));
@simonbengtsson Just out of curiosity, what is the hosting solution are you using ?
I am using Heroku and I tried:
serverURL: 'https://localhost:1337/parse' or
serverURL: 'http://localhost:1337/parse' or serverURL: 'https://localhost:' + port + '/parse'-> received {"code":141,"error":"Error: 100 XMLHttpRequest failed: \"Unable to connect to the Parse API\""}
serverURL: 'http://localhost:' + port + '/parse'-> received {"code":141,"error":"Error: undefined unauthorized"}
None of above ones worked.
I've written the command line:
Parse.Cloud.beforeSave("Message", function(request, response) {
console.log('Parse.serverURL: ' + Parse.serverURL);
if (!request.object.get("uniqueCode")) {
//more code
and it printed app[web.1]: Parse.serverURL: http://localhost:30835/parse in Heroku as expected.
What more could be wrong ?
Im using the parse server locally. The serverurl for heroku would be something like http://your-heroku-app-id.herokuapp.com/parse. Or simply where the parse server is located.
Along with setting the serverURL in index.js make sure you are also passing a valid sessionToken otherwise it will throw an unauthorized error.
Also getting a similar response (141 / unauthorised) via Cloud Code. App ID matches client-side and in the ParseServer constructor + client keys not defined in client/server. Locally regular CloudCode functions (like the default hello function in parse-server-example) work just fine, it seems to be queries that have issues. Both all fail when deployed to heroku.
client side JS:
Parse.initialize("the_app_id", "");
Parse.serverURL = "/parse";
...
Parse.Cloud.run("validateEmail", {email:"..."}, {});
...
=>
cloud/main.js:
Parse.Cloud.define('validateEmail', function(req, res) {
// Get the email address of the user we are going to check
var email = req.params.email;
// Execute query with Parse
var query = new Parse.Query("ObjectTest");
query.equalTo('email', email);
query.find({
success: function(result) {
res.success(result);
},
error: function(err) {
res.error(err);
}
});
});
(nothing declared outside of Parse.Cloud.define, Parse not re-imported etc)
=> {"code":141,"error":{"message":"unauthorized"}}
What is your initialization code for the parse server @jamiechapman? Make sure you are using the serverURL option there as well.
@simonbengtsson
The serverURL is defined and matches that defined by the client. I have tried fully qualified URL's in the client-side (http://www etc) and a relative path, both produce error 141 for some odd reason!
var api = new ParseServer({
databaseURI: databaseUri || 'mongodb://XXXXXXX',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: process.env.APP_ID || 'XXXXXXX',
masterKey: process.env.MASTER_KEY || 'XXXXXXX',
clientKey: process.env.CLIENT_KEY || '',
serverURL: 'http://www.XXXXXXX.com/parse'
});
(XXXXXXX's subbed in place of real values, both match server/client side)
@simonbengtsson Think I sussed it! The environment variable APP_ID had an extra character at the end which likely caused the requests to (rightly) fail. Thanks for the help! :+1:
In my case, I have no clues about what's happening yet.
I tried 'https://localhost:' + port + '/parse' and 'https://www.XXXXXXX.com/parse' (using domain name).
I recreated the session token but with no effect too.
My APP_ID is correct and it is the same used in Swift and Android clients.
I do not know how to debug it. There is no additional information.
My files have the same structure as parse-example, with no modifications. The unique difference is an additional FACEBOOK_APP_ID env var (nothing related to code).
Everything works well except the Parse Cloud.
My solution, at moment, is an instance of a custom Express app (connected to the same database of the Parse Server) that handles manually the requests that would have been handled by the triggers.
Can you share the, preferably simplified, code you are using @leo-one? What do you mean with custom express app? Can you use queries in the same express app used by the parse server?
@simonbengtsson the code is simple, almost equals to Parser Server example in github page. I am using parser-server 2.0.8 version. See below:
index.js
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var databaseUri = process.env.DATABASE_URI || process.env.MONGOLAB_URI;
if (!databaseUri) {
console.log('DATABASE_URI not specified, falling back to localhost.');
}
var app = express();
var port = process.env.PORT || 1337;
var api = new ParseServer({
databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: process.env.APP_ID || 'myAppId',
masterKey: process.env.MASTER_KEY || '',
clientKey: process.env.CLIENT_KEY || '',
serverURL: 'http://localhost:' + port + '/parse'
});
// Serve the Parse API on the /parse URL prefix
app.use('/parse', api);
app.get('/', function(req, res) {
res.status(200).send('Express is running here.');
});
app.listen(port, function() {
console.log('parse-server-example running on port ' + port + '.');
});
cloud/main.js
Parse.Cloud.define('hello', function(req, res) {
res.success('Hi'); // it works
});
Parse.Cloud.beforeSave("Message", function(request, response) {
// it prints http://localhost:29257/parse as expected
console.log('Parse.serverURL: ' + Parse.serverURL);
var query = new Parse.Query("Message");
query.equalTo("uniqueCode", request.object.get("uniqueCode"));
query.find({
success: function(results) {
if (results.length > 0) {
response.success();
} else {
response.error("A Message with this uniqueCode already exists.");
}
},
error: function(error) {
response.error("Error: " + error.code + " " + error.message);
}
});
});
In iOS Swift app
let message = PFObject(className:"Message")
message["content"] = "Hello World"
message["toId"] = userId
message["fromId"] = PFUser.currentUser()!.objectId!
message["uniqueCode"] = "ITSREALLYUNIQUE"
message.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
if let error = error {
print(error.debugDescription)
// it prints Response Body : {"code":141,"error":"Error: undefined unauthorized"}
}
print("success: \(success)")
}
I think the following issue is similar. I will check it later: https://github.com/ParsePlatform/parse-server/issues/407
@simonbengtsson Yes. You can create another Node.js/Express server and point it to the same database that Parse Server uses. Then you can execute your custom queries and operations. At moment, I am building the message system isolated from Parser Server (but using same database) until this issue is solved.
I tried your code and for me it works, I used the rest api though. Does it work if you use curl instead? Do your ios app have the correct serverURL?
curl -X PUT -H "X-Parse-Application-Id: myAppId" -H "X-Parse-Master-Key: _master_key_" -d '{"content": "Hello World"}' http://localhost: 29257/parse/classes/Message/_objectId_
@simonbengtsson Thanks, but I execute the same curl command that you posted and I received the same error {"code":141,"error":"Error: undefined unauthorized"} .
Yes. My iOS app has the correct server url, because everything works well except if the class operation has a trigger.
This is the code:
let config = ParseClientConfiguration(block: {
(ParseMutableClientConfiguration) -> Void in
ParseMutableClientConfiguration.applicationId = "APP_ID";
ParseMutableClientConfiguration.clientKey = "CLIENT_KEY";
ParseMutableClientConfiguration.server = "https://nameofapp.herokuapp.com/parse";
});
Parse.initializeWithConfiguration(config);
I noted that all tests that were posted here were in localhost. Maybe can it be a Heroku problem ? I'll try to reconfigure the instance focusing more in testing it (both local and remote) and I'll post the results here.