Parse Javascript Platform Change Password Error - parse-platform

I defined a cloud codeļ¼š
Parse.Cloud.define("updateUser", async (request) => {
const query = new Parse.Query("User");
query.get(request.params.id, {useMasterKey:true})
.then(function(user) {
user.set("username", request.params.username);
user.set("password", request.params.password);
user.set("gender", request.params.gender);
return user.save(null, {useMasterKey:true});
}).catch(function(error) {
console.error("Got an error " + error.code + " : " + error.message);
});
});
Return has been changed successfully.
But, using the new password to log in on the mobile app, the password is incorrect.
{"code":101, "stack": "Error": Invalide username/password}

I think you need to return the first promise. Also try to use setUsername and setPassword. It would be something like this:
Parse.Cloud.define("updateUser", async (request) => {
const query = new Parse.Query("User");
return query.get(request.params.id, {useMasterKey:true})
.then(function(user) {
user.setUsername(request.params.username);
user.setPassword(request.params.password);
user.set("gender", request.params.gender);
return user.save(null, {useMasterKey:true});
}).catch(function(error) {
console.error("Got an error " + error.code + " : " + error.message);
});
});

Related

Parse server query object is returning no results

I am having issues with querying the parse server. I have created a class called Tickets and a single row via the Dashboard. When I use curl, I can query and get the row. However, when I try to do it in JavaScript from an HTML page, I get zero results.
I call the getTickets() function from myLogin, which is called via a button click. The final console.log() call in getTickets() prints "Results: " and nothing else.
BTW, the getTickets() function is modeled on examples in the Parse documentation.
Thanks in advance for your help.
Here is my code:
Parse.initialize("-REDACTED-", "");
Parse.serverURL = "-REDACTED-";
function myLogin(uname, psw) {
var uname = document.getElementById("uname").value;
var psw = document.getElementById("psw").value;
const user = Parse.User.logIn(uname, psw);
var cUser = Parse.User.current();
if (cUser) {
console.log(
"Hey! The login worked!" + " Username: " + cUser.get("username")
);
getTickets();
} else {
alert("Womp, womp. The login failed.");
}
}
async function getTickets() {
const Ticket = Parse.Object.extend("Ticket");
const query = new Parse.Query(Ticket);
const res = await query.find();
console.log("Results: " + res);
}
The curl call returns the following, if that's useful:
{"results":[{"objectId":"RuFPxSjigL","user":{"__type":"Pointer","className":"_User","objectId":"uGwwN99EX9"},"createdAt":"2020-01-15T20:47:45.116Z","updatedAt":"2020-01-15T20:48:05.203Z","event":{"__type":"Pointer","className":"Event","objectId":"BdGQSPhK0J"}}]}%
There are minor things I'd change:
Parse.initialize("imAppId", "");
Parse.serverURL = "https://www.immedia.co/parse/";
async function imLogin(uname, psw) {
const uname = document.getElementById("uname").value;
const psw = document.getElementById("psw").value;
let user;
try {
user = await Parse.User.logIn(uname, psw);
} catch (err) {
alert("Login failed: username or password are not valid: ", err);
return; // if log in fails, you can't access the user's tickets
}
let tix;
try {
tix = await getTickets();
alert("Successfully retrieved " + tix.length + " tickets.");
} catch (err) {
console.error("Error getting tickets: ", err);
return;
}
for (const obj of tix) {
console.log(
"ticket.id: " + obj.id + " with user.id " + obj.get("user")
);
}
}
async function getTickets() {
const Ticket = Parse.Object.extend("Ticket");
const query = new Parse.Query(Ticket);
return await query.find();
}
You can convert the for loop to a for-of loop. I'd not catch an error in getTickets, but in the log in function. And if log in or get tickets fails, return after logging the error, as there's nothing more to do.
I found the answer. I didn't understand that the Parse.Query.find() returns an array. The console.log() call in getTickets(), indicated that res was undefined and I thought that nothing was being returned. I have updated my code to behave better. I am new to JavaScript, I would appreciate any suggestions to improve the code or the style.
Parse.initialize("imAppId", "");
Parse.serverURL = "https://www.immedia.co/parse/";
async function imLogin(uname, psw) {
var uname = document.getElementById("uname").value;
var psw = document.getElementById("psw").value;
var user;
try {
user = await Parse.User.logIn(uname, psw);
} catch (err) {
alert("Login failed: username or password are not valid: ", err);
}
const tix = await getTickets();
for (let i = 0; i < tix.length; i++) {
var obj = tix[i];
console.log(
"ticket.id: " + obj.id + " with user.id " + obj.get("user")
);
}
async function getTickets() {
const Ticket = Parse.Object.extend("Ticket");
const query = new Parse.Query(Ticket);
var tix = [];
try {
tix = await query.find();
alert("Successfully retrieved " + tix.length + " tickets.");
} catch (err) {
console.error("Error getting tickets: ", err);
}
return tix;
}

Parse cloud code afterSave gets triggered twice

I have a aftersave on Parse cloud code. I have made changes to the table once but the aftersave hook triggers twice
1st Update (Actual update)
Input: {"object":{"addedBy":"tt","albumTitle":"ggh","approved":true,
"createdAt":"2015-12-14T03:07:27.253Z","image":
{"__type":"File","name":"tfss-e26ec608-5a0b-46a2-91db-33590139c4b3-
newImage.jpg","url":"http://files.parsetfss.com/0accbdba-e3f2-493d-
ac70-1c6bccc367b9/tfss-e26ec608-5a0b-46a2-91db-33590139c4b3-
newImage.jpg"},"objectId":"p4pLO70gQY","updatedAt":"2015-12-
14T03:07:37.733Z"}}
2nd Update (Shouldn't happen)
Input: {"object":{"addedBy":"tt","albumTitle":"ggh","approved":true,
"createdAt":"2015-12-14T03:07:27.253Z","image":
{"__type":"File","name":"tfss-e26ec608-5a0b-46a2-91db-33590139c4b3-
newImage.jpg","url":"http://files.parsetfss.com/0accbdba-e3f2-493d-
ac70-1c6bccc367b9/tfss-e26ec608-5a0b-46a2-91db-33590139c4b3-
newImage.jpg"},"objectId":"p4pLO70gQY","updatedAt":"2015-12-
14T03:07:38.038Z"}}
The only difference between the two updates is the updatedAt time. Will aftersave be triggered even if the update time changes?
How can I avoid the second aftersave execution?
Here is my cloud code :
Parse.Cloud.afterSave("Photos", function (request) {
var albumNameA = "";
var publicUser = "";
var albumOwner = "";
var photoUniqueId = "";
var isApproved = "";
albumNameA = request.object.get("albumTitle");
publicUser = request.object.get("addedBy");
photoUniqueId = request.object.id;
isApproved = request.object.get("approved");
if (request.object.get("createdAt").getTime() == request.object.get("updatedAt").getTime()) {
var getAlbumOwner = new Parse.Object.extend("Albums");
var q3 = new Parse.Query(getAlbumOwner);
q3.equalTo("title", albumNameA);
q3.first({
success: function (results) {
console.log("Checking for Creator name " + results.get("creatorName"));
albumOwner = results.get("creatorName");
console.log("Uploading a Photo Final " + albumNameA + "-by-" + publicUser + "--ownedby--" + albumOwner);
console.log("Uploading a Photo" + albumNameA + "-by-" + publicUser + "--" + photoUniqueId + "--" + isApproved);
var install = new Parse.Object.extend("Installation");
var q2 = new Parse.Query(install);
q2.equalTo("privacy", privateUserNo);
q2.equalTo("username", albumOwner);
q2.find({
success: function (results) {
if (!isApproved) {
Parse.Push.send({
where: q2, // Set our Installation query
data: {
alert: "New Photo uploaded by " + publicUser + " ,waiting for approval"
}
}, {
success: function () {
// Push was successful
console.log("Push success");
},
error: function (error) {
// Handle error
console.log("Push error");
}
})
}
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
} else if (!(request.object.get("createdAt").getTime() == request.object.get("updatedAt").getTime())) {
console.log("all case scenarios");
var getAlbumOwner1 = new Parse.Object.extend("Albums");
var q6 = new Parse.Query(getAlbumOwner1);
q6.equalTo("title", albumNameA);
q6.first({
success: function (results) {
albumOwner = results.get("creatorName");
var sendApproval = new Parse.Object.extend("Photos");
var q4 = new Parse.Query(sendApproval);
q4.descending("updatedAt");
q4.first({
success: function (results) {
var objectIDNeeded = results.id;
var isChanged = results.get("approved");
var currentUpdateTime = results.get("updatedTime");
console.log("Your Photo, " + publicUser + " ,has been approved by " + albumOwner);
var install = new Parse.Object.extend("Installation");
var q5 = new Parse.Query(install);
q5.equalTo("privacy", privateUserNo);
q5.equalTo("username", publicUser);
q5.find({
success: function (results) {
Parse.Push.send({
where: q5, // Set our Installation query
data: {
alert: "Your Photo has been approved by " + albumOwner
}
}, {
success: function () {
// Push was successful
console.log("Push success");
},
error: function (error) {
// Handle error
console.log("Push error");
}
})
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
}
});

how to open a url from the barcode scanner in phonegap build

i'am using the Barcode Scanner for phonegap build, How would i retrieve the QR Codes URL data and display the webpage into a Iframe or div
$(document).ready(function(e) {
$("#scanner_mode").click(function() {
cordova.plugins.barcodeScanner.scan(
function (result) {
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled);
},
function (error) {
alert("Scanning failed: " + error);
}
);
});
});
Right i have tried this but its not working, so how would i get the src of a iframe to load result.text url
$(document).ready(function(e) {
$("#scanner_mode").click(function() {
cordova.plugins.barcodeScanner.scan(
function (result) {
document.getElementById("frame").src = result.text;
},
function (error) {
alert("Scanning failed: " + error);
}
);
});
});
yep so its working :)
$(document).ready(function(e) {
$("#scanner_mode").click(function() {
cordova.plugins.barcodeScanner.scan(
function (result) {
document.getElementById("frame").src = result.text;
},
function (error) {
alert("Scanning failed: " + error);
}
);
});
});
that works :)

Error: 101 object not found for update

I've got the follwing parse.com cloud code
Parse.Cloud.afterSave("Action", function (request) {
var BookStatus = Parse.Object.extend("BookStatus");
var Book = Parse.Object.extend("Book");
var book = new Book();
var actionType = request.object.get("actionTypePointer").id;
var bookId = request.object.get("bookPointer").id;
var queryBook = new Parse.Query("Book");
var newBookStatus;
queryBook.get(bookId,{
success: function (gottenBook) {
newBookStatus = "idOfTheBookStatus";
book.id = bookId;
book.set("bookStatus", new BookStatus({id: newBookStatus}));
gottenBook.set("bookStatus", new BookStatus({id: newBookStatus}));
//OPTION 1
gottenBook.save(null,{
success: function(data) {
console.log("Bookstatus updated1");
},
error: function (data,error) {
// error is a Parse.Error with an error code and description.
console.log("Error: " + error.code + " " + error.message);
}
});
//OPTION 2
book.save(null,{
success: function(data) {
console.log("Bookstatus updated2");
},
error: function (data,error) {
// error is a Parse.Error with an error code and description.
console.log("Error: " + error.code + " " + error.message);
}
});
},
error: function (object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and description.
console.log("Error: " + error.code + " " + error.message);
}
});
OPTION1
I try to save the queried book after setting the bookStatus to the returned book.
OPTION2
I try to save the new book object after setting the book.Id
book.id = bookId;
book.set("bookStatus", new BookStatus({id: newBookStatus}));
However with any of the 2 options I end up getting in the parse.com logs:
Error: 101 object not found for update
Error: 101 object not found for update
Any idea of what I am doing wrong?
Thanks in advance!
--EDIT
New implementation with fetch:
Parse.Cloud.afterSave("Action", function (request) {
var BookStatus = Parse.Object.extend("BookStatus");
var Book = Parse.Object.extend("Book");
var book = new Book();
var actionType = request.object.get("actionTypePointer").id;
var bookId = request.object.get("bookPointer").id;
book.id = bookId;
console.log("before fetch book.id" + book.id);
var newBookStatus;
book.fetch({
success: function (book) {
newBookStatus = "XMFkXS9NVv";
book.set("bookStatus", new BookStatus({id: newBookStatus}));
console.log("book" + book);
console.log("book.id" + book.id);
console.log("book.isValid()" + book.isValid());
book.save(null,{
success: function(data) {
console.log("Book Status updated to:" +newBookStatus);
},
error: function (data,error) {
// error is a Parse.Error with an error code and description.
console.log("Error: " + error.code + " " + error.message);
}
});
},
error: function (object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and description.
console.log("Error: " + error.code + " " + error.message);
}
});
});
With result:
Input: {"place":{"__type":"GeoPoint","latitude":41.354643806134625,"longitude":2.121594674804572},"bookLocationDescription":"sad","bookPointer":{"__type":"Pointer","className":"Book","objectId":"kWcALge4az"},"actionTypePointer":{"__type":"Pointer","className":"ActionType","objectId":"kJC954w9iO"},"userPointer":{"__type":"Pointer","className":"_User","objectId":"6xpiAHX9Ju"},"createdAt":"2013-05-16T13:59:33.810Z","updatedAt":"2013-05-16T13:59:33.810Z","objectId":"PwlXhKL51l","ACL":{"6xpiAHX9Ju":{"read":true,"write":true},"*":{"read":true}}}
Result: Success
I2013-05-15T20:52:19.170Z] before fetch book.idc1iKxw3NLD
I2013-05-15T20:52:19.273Z] book[object Object]
I2013-05-15T20:52:19.273Z] book.idc1iKxw3NLD
I2013-05-15T20:52:19.273Z] book.isValid()true
I2013-05-15T20:52:19.325Z] Error: 101 object not found for update
Your afterSave hook is overwriting the fetched Book's object id. Even if you're setting the same object id on it, the object now thinks it's dirty and it's no longer a valid reference.
Avoid this by using the book returned by get() and not updating it's id:
Parse.Cloud.afterSave("Action", function (request) {
var BookStatus = Parse.Object.extend("BookStatus");
var Book = Parse.Object.extend("Book");
var book = new Book();
var actionType = request.object.get("actionTypePointer").id;
var bookId = request.object.get("bookPointer").id;
var queryBook = new Parse.Query("Book");
var newBookStatus;
queryBook.get(bookId,{
success: function (book) {
newBookStatus = "idOfTheBookStatus";
book.set("bookStatus", new BookStatus({id: newBookStatus}));
book.save(null,{
success: function(data) {
console.log("Bookstatus updated1");
},
error: function (data,error) {
// error is a Parse.Error with an error code and description.
console.log("Error: " + error.code + " " + error.message);
}
});
},
error: function (object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and description.
console.log("Error: " + error.code + " " + error.message);
}
});
});
Since you already know the id for this book, instead of using a query, you can create a pointer and fetch it directly.
Final afterSave hook:
Parse.Cloud.afterSave("Action", function (request) {
var BookStatus = Parse.Object.extend("BookStatus");
var Book = Parse.Object.extend("Book");
var book = new Book();
var actionType = request.object.get("actionTypePointer").id;
var bookId = request.object.get("bookPointer").id;
book.id = bookId;
var newBookStatus;
book.fetch({
success: function (book) {
newBookStatus = "idOfTheBookStatus";
book.set("bookStatus", new BookStatus({id: newBookStatus}));
book.save(null,{
success: function(data) {
console.log("Bookstatus updated1");
},
error: function (data,error) {
// error is a Parse.Error with an error code and description.
console.log("Error: " + error.code + " " + error.message);
}
});
},
error: function (object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and description.
console.log("Error: " + error.code + " " + error.message);
}
});
});
Here's how I did it after some running around
ParseCrashReporting.enable(this);
// Enable Local Datastore.
Parse.enableLocalDatastore(this);
// Add your initialization code here
Parse.initialize(this, "*******", "******");
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
ParseACL.setDefaultACL(defaultACL, true);
// save the installation
ParseInstallation.getCurrentInstallation().saveInBackground();
More info on the issue in my blog post here:
http://aprogrammersday.blogspot.com/2015/02/fix-parse-101-error-object-not-found.html
Whilst looking for this error I found this thread the most useful. I wanted to add that object not found for get can also essentially mean foreign key reference not found.
The not found for get error can be incredibly unhelpful; for me it wasn't even giving a line number where the error was occurring, the error message is very vague and I could not find reference to the phrase in any of the documentation.
If you are getting this error, you will find a lot of reference to permissions issues, but if you are already using the master key then you need to find the object that is being referenced by a foreign key on your selected object.

MVC 3 & Uploadify - how to show custom error message?

After uploading a file, before I save it on the disk, I'm doing some validation.
If something fails, I want to show my custom error message to the user.
I've found something sililar here Uploadify: show error message from HTTP response
How to do this in MVC 3 ?
Tony,
Taken straight from ab mvc3 app that I'm working on right now:
<script type="text/javascript">
function initupLoadify() {
$("#fileInput").uploadify({
uploader: '#Url.Content("~/scripts/swf/uploadify.swf")',
script: '#Url.Action("Upload", "Home")',
cancelImg: '#Url.Content("~/Content/cancel.png")',
auto: true,
sizeLimit: 5500000,
fileDataName: 'fileData',
//scriptData: { 'propertyId': $("#PropertyID").val() },
buttonText: 'Add Schedule',
wmode: 'transparent',
//buttonImg: '#Url.Content("~/Content/button.png")', // make nice gradient image for button
onComplete: function (event, queueId, fileObj, response) {
$("#msg").html(response);
// do something
setTimeout(2000, window.location = '#Url.Action("Index")' + '?id=' + response);
return true;
},
onCancel: function (evt, queueId, fileObj, data) {
$("#msg").html("<br />Operation cancelled");
return true;
},
onOpen: function (evt, queueId, fileObj) {
$("#msg").html("<br />Upload in progress");
return true;
},
onError: function (event, queueId, fileObj, errorObj) {
$("#msg").html(fileObj.name + " was not uploaded ");
if (errorObj.status == 404)
$("#msg").html("Could not find upload script. Use a path relative to: " + "<?= getcwd() ?>");
else if (errorObj.type === "HTTP")
$("#msg").html("error " + errorObj.type + ": " + errorObj.status);
else if (errorObj.type === "File Size")
$("#msg").html(fileObj.name + " " + errorObj.type + " Limit: " + errorObj.info / 1000 + " KB");
else
$("#msg").html("error " + errorObj.type + ": " + errorObj.text);
}
});
};
</script>
hope this helps
Here is an MVC 3 example.
If you're using versions 3.0+ use onUploadComplete instead of onComplete (realize their parameters differ).

Resources