Parse Cloud Code Error - 'Master Key is Required'? - javascript

Whenever I try to run this snippet of cloud code, I receive an error stating that:
Error generating response. ParseError {
code: 141, message: 'Push failed to send with error: master key is required'}
I've tried to follow some of the other solutions on the site such as using Parse.Cloud.useMasterKey() & useMasterKey: true but I haven't found success with any of these commands (possibly due to me using them incorrectly?).
Parse.Cloud.define("sendPushToUser", function(request, response) {
var senderUser = request.user;
var recipientUserId = request.params.recipientId;
var message = request.params.message;
var recipientUser = new Parse.User();
recipientUser.id = recipientUserId;
var pushQuery = new Parse.Query(Parse.Installation);
pushQuery.equalTo("user", recipientUser);
Parse.Push.send({
where: pushQuery,
data: {
alert: message
}
}).then(function() {
response.success("Push was sent successfully.")
}, function(error) {
response.error("Push failed to send with error: " + error.message);
});
});
Swift function:
func testPush() {
PFCloud.callFunction(inBackground: "sendPushToUser", withParameters: ["recipientId": PFUser.current()?.objectId!, "message" : "Test notification"]) { (success, error) in
if error != nil {
print("error occurred")
}else {
print("Sent successfully")
}
}
}

As Gellert Lee suggested
Did you configure your masterKey in your index.js? masterKey : process.env.MASTER_KEY ||'your masterkey'

Related

Back4App: Parse / JS error "Unhandled Promise Rejection: SecurityError: The operation is insecure."

when I try to create a new User with JavaScript and Parse in Back4App.io I receive the following error:
Unhandled Promise Rejection: SecurityError: The operation is insecure.
I use the following code:
Parse.initialize("APP_ID", "JS_KEY"); //PASTE HERE YOUR Back4App APPLICATION ID AND YOUR JavaScript KEY
Parse.serverURL = "https://parseapi.back4app.com/";
var user = new Parse.User();
user.save({
username: 'Taki Test',
email: 'sample#email.com',
password: '123456'
}, {
success: function(response) {
alert('New object create with success! ObjectId: ' + response.id + `, ` + user.get('username'));
},
error: function(response, error) {
alert('Error: ' + error.message);
}
})
It seems that you didn't insert your master key in your initialization code, and that was the reason you're facing this trouble.
I tested your code with master key and it worked for me.
Also, on the "API Reference" available in the Dashboard, on "User API" > Signing Up, there's a simple code that you only need to run and it will create an user too, here it is:
Parse.serverURL = 'https://parseapi.back4app.com';
Parse.initialize('appId', 'jskey', 'masterkey');
const user = new Parse.User()
user.set('username', 'A string');
user.set('email', 'email#email.com');
user.set('password', '123456');
user.signUp().then((user) => {
if (typeof document !== 'undefined') document.write(`User signed up: ${JSON.stringify(user)}`);
console.log('User signed up', user);
}).catch(error => {
if (typeof document !== 'undefined') document.write(`Error while signing up user: ${JSON.stringify(error)}`);
console.error('Error while signing up user', error);
});

TypeError: Cannot read property 'userId' - sendbird

i am trying to create a channel between 2 sendbird users using group channel. So far my implementation is
<script type="text/javascript">
function chatInit(){
var sb = new SendBird({
appId: 'my app id'
});
sb.connect('test user','access token of user', function(user, error) {
console.log(error);
});
var userIds = ['another user'];
var name ="name of channel";
sb.GroupChannel.createChannelWithUserIds(userIds, true, name ,'', '', function(channel, error) {
if (error) {
console.error(error);
return;
}
});
}
</script>
and i get following error on console
SendBird.min.js:6 Uncaught TypeError: Cannot read property 'userId' of null
at Function.GroupChannel.createChannelWithUserIds
am i missing something, please guide me through the process.
any and all help will be appreciated.
The reason why you get that error response is because the connect has not run to completion as at the time the code
sb.GroupChannel.createChannelWithUserIds()
is run.
You need to add that add that block of code inside the callback function of sb.connect() like so:
function chatInit(){
var sb = new SendBird({
appId: 'my app id'
});
var userIds = ['another user'];
sb.connect('test user','access token of user', function(user, error) {
console.log(error);
if(user){
var name ="name of channel";
sb.GroupChannel.createChannelWithUserIds(userIds, true, name ,'', '', function(channel, error) {
if (error) {
console.error(error);
return;
}
});
}
}
}

ParseError: 'bad or missing username'

So I have some cloud code I am trying to write to like a post.
My database is setup that users have a likedPosts array, which has object id's of all the posts that the user liked. Users also have a column coins, that should get incremented when users like their posts.
The post object has a likes column which is an integer that gets incremented with each like, and the post object also has a posterId column, which is the object id of the user that posted it.
Here is my function right now (I am not very good at javascript and cloud code, so if there is something horribly wrong, I'm sorry)
Parse.Cloud.define("likePost", function(request, response) {
Parse.Cloud.useMasterKey();
var senderId = request.params.senderId;
var postId = request.params.postId;
var post = new Parse.Object ({objectId: postId});
var posterId = post.posterId
var poster = new Parse.User ({objectId: posterId});
var sender = new Parse.User ({objectId: senderId});
sender.add("likedPosts", postId);
poster.increment("coins");
post.increment("likes");
poster.save(null, {useMasterKey:true, success:
function(poster) {
console.log("Successfully saved poster");
}, error: function(poster, error) {
console.error("Error saving poster: " + error.message);
response.error(error);
}
});
post.save(null,{useMasterKey:true, success:
function(post) {
console.log("Successfully saved post");
}, error: function(post, error) {
console.error("Error saving post: " + error.message);
response.error(error);
}
});
sender.save(null, {useMasterKey:true, success:
function(sender) {
console.log("Successfully saved sender");
}, error: function(sender, error) {
console.error("Error saving sender: " + error.message);
response.error(error);
}
});
response.success();
});
I call the function from swift like so:
PFCloud.callFunction(inBackground: "likePost", withParameters: ["senderId" : PFUser.current()!.objectId!, " postId": postObject!.objectId!], block: { (result, error) in
if (error != nil) {
print(error!)
} else {
print("success liking")
}
})
In my logs, however, I get the following error:
2017-06-21T21:47:59.499Z - Failed running cloud function likePost for user R4d8Zrcdhw with:
Input: {"senderId":"R4d8Zrcdhw"," postId":"XXbu55PdpR"}
Error: {"code":141,"message":{"code":200,"message":"bad or missing username"}}
2017-06-21T21:47:59.492Z - bad or missing username
My guess is that the request is missing a header to define the content-type. I've seen Parse return the "bad or missing username" error via the Parse REST API if the Swift URLSession was using an incorrect content-type header.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
or
Parse.Cloud.httpRequest({
url: 'http://www.example.com/',
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
})

Logout from site cause error: 400 - Bad Request

I am using vibed.org framework. When I am processing logout function, I am getting strange error.
Here is my App.d code:
void main()
{
auto router = new URLRouter;
router.any("/checkAuthorization", &checkAuthorization);
router.any("/login", &login);
router.any("/logout", &logout);
// ..
}
...
void logout(HTTPServerRequest req, HTTPServerResponse res)
{
logInfo("Logout section");
Json request = req.json;
Json answerJSON = Json.emptyObject;
if (req.session) // if user have active session
{
res.terminateSession();
answerJSON["status"] = "success";
answerJSON["isAuthorized"] = false;
res.writeJsonBody(answerJSON);
logInfo(answerJSON.toString);
logInfo("User %s logout", request["username"]); //
}
else
{
answerJSON["status"] = "fail"; // user do not have active session?
logInfo("User do not have active session");
}
}
And Vue.JS code:
function logout()
{
var loginData = new Object();
//data that we take from user input
loginData["username"] = this.username; // username more then enough
console.log("Logout username -> " + loginData["username"]);
this.$http.post('http://127.0.0.1:8080/logout', loginData["username"]).then(function (response) {
console.log("server response: ", response.data)
if(response.data["isAuthorized"] == false)
{
console.log("Logout from site success");
App.topMenuView = 'guestmenu' //Change current view!
userLoginNotification("Goodbye, " + loginData["username"], "User Logout"); // notificate user
}
});
}
But I am getting in Chrome console error:
Uncaught (in promise) Object {request: Object, data: "400 - Bad Request Bad Request Internal error information: std.json.JSONException#C:\vibe-d-0.7.27-alpha.1\source\vibe\data\json.d(1100): (0): Error: Expected 'true', got 'test'. ---------------- 0x0044ABF0 in pure #safe bool std.exception.enforceEx!(std.json.JSONException).enforceEx!(bool).enforceEx(bool, lazy immutable(char)[], immutable(char)[], uint) core.thread.Fiber.run()", status: 400, statusText: "Bad Request", ok: false}
And I can't understand what's wrong. It's look like it's issue on server side, because logInfo("Logout section"); is unreachable.
Your're sending string as loginData["username"] instead of {username:loginData["username"]} василий

Parse.com http response is not returned, and status is not defined

I am facing 2 issues with writing a background job in parse
Here is my code
Parse.Cloud.job("createSilentUsers",function(request,response){
// Set up to modify user data
Parse.Cloud.useMasterKey();
//get all the users from backupusers table where isbiscootactivated = 0 and issnsactivated=0
// Query for all users
var query = new Parse.Query("biscootusers");
query.equalTo("isbiscootactivated",0);
query.equalTo("issnsactivated",0);
query.first({
success: function(result) {
// Successfully retrieved the object.
var objUser = result;
console.log(result.attributes.deviceid);
console.log(result.attributes.imei);
console.log(result.attributes.appname);
console.log(result.attributes.appid);
console.log(result.attributes.appversion);
//check if the deviceid and imei set is already a biscoot activated user
var promise = Parse.Promise.as();
promise = promise.then(function() {
console.log("we are inside the prmise");
return Parse.Cloud.httpRequest({
method: 'POST',
url: 'http://<our server name>/1.0/PartnerActivation/isDeviceExists',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'},
body: {
imei: result.attributes.imei,
deviceid: result.attributes.deviceid,
appname: result.attributes.appname,
appid: result.attributes.appid,
appversion: result.attributes.appversion}
}).then(function(httpResponse)
{
console.log("Response of isdeviceactivated is " + httpResponse.text);
if(httpResponse.text == 'true' || httpResponse.text="True")
{
console.log("The user is already activated");
objUser.set("isbiscootactivated",1);
objUser.save();
}
else
{
//do the biscoot activation here
console.log("its not activated, lets do the biscootusers activation");
}
},
function(error) {
console.log("error occurred during isDeviceExists api as " + error);
});
});
console.log("nothing seems to have happened");
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
}
}).then(function() {
// Set the job's success status
status.success("All the users been set to the db successfully");
}, function(error) {
// Set the job's error status
status.error("Uh oh, something went wrong.");
});
});
The Issues I have are
In the logs I frequently see this error
Ran job createSilentUsers with:
Input: {}
Failed with: ReferenceError: status is not defined
at main.js:74:9
at r (Parse.js:2:4981)
at Parse.js:2:4531
at Array.forEach (native)
at Object.E.each.E.forEach [as _arrayEach] (Parse.js:1:666)
at n.extend.resolve (Parse.js:2:4482)
at null. (Parse.js:2:5061)
at r (Parse.js:2:4981)
at n.extend.then (Parse.js:2:5327)
at r (Parse.js:2:5035)
The http request just doesn't seem to work, while it always does if I test it from some http REST client.
Just change the "response" to "status" on the funcion header.
Parse.Cloud.job("createSilentUsers",function(request,response){
to this
Parse.Cloud.job("createSilentUsers",function(request,status){

Categories

Resources