Parse query not returning - parse-platform

I am trying to do a little script on Cloud Code that sends an email whenever an object of type Reservas is created. This email needs to contain the information about the user that created this object. I know that using a related field would be better, but this option is not possible at the moment.
What I thought of doing is a query using the email from the Reservas object and the email property from the user but I can't seem to get to the line console.log("--> Usuario encontrado")
Here's what I tried to do:
Parse.Cloud.afterSave("Reservas", function(request) {
var assunto = "Reserva App Criada - ";
var conteudo = "Reserva App CRIADA\n"
try {
query = new Parse.Query(Parse.User);
query.equalTo("email", request.object.get("email"));
query.find({
sucess: function(usuario) {
console.log("--> Usuario encontrado")
mandarEmail(conteudo, assunto, request, usuario)
}, error: function(error) {
console.log("--> Usuario não encontrado")
emailErro(request, error);
}
})
} catch(err) {
console.log("--> Erro:" + err);
}
});

It was just a silly typo. I wrote sucess instead of success

Related

Parse On Buddy Logout User

I am migrating an application from parse.com to buddy.com. One of the caveats of the migration was that Parse.User.current() is no longer available on buddy.com, instead you have to get the user and session token from the request itself: https://github.com/ParsePlatform/Parse-Server/wiki/Compatibility-with-Hosted-Parse#no-current-user
The application I am migrating has a logoutUser method that I am attempting to migrate:
Parse.Cloud.define("logoutUser", function(request, response) {
Parse.User.logOut().then(
function onSuccess(result){
response.success(result);
},
function onError(error) {
response.error(error);
}
)
});
now I am attempting to do this in the new style, but am receiving an error. (NOTE: This is cloud code not a nodejs environment)
{
"code":"500",
"error":"Error: There is no current user user on a node.js server environment."
}
New implementation:
function logoutUser(request, response) {
var user = request.user;
var sessionToken = user.getSessionToken();
Parse.User.logOut({ sessionToken }).then(
function onSuccess(result){
response.success(result);
},
function onError(error) {
response.error(error);
}
)
}
Parse.Cloud.define("logoutUser", function(request, response) {
logoutUser(request, response);
});
Suggestions on how to correctly log out users in the Parse on Buddy cloud code?
You could fetch user's session or sessions and delete it / them:
var query = new Parse.Query("_Session");
query.descending('createdAt');
query.equalTo('user', {__type:"Pointer", className:"_User", objectId:"idhere"});
query.first({
useMasterKey: true
}).then(function(session) {
var sessions = [];
sessions.push(session);
Parse.Object.destroyAll(sessions);
}, function (err) {
console.log("Internal error " + err);
});
OR for more tokens you could use find instead of first like:
var query = new Parse.Query("_Session");
query.equalTo('user', {__type:"Pointer", className:"_User", objectId:"idhere"});
query.find({
useMasterKey: true
}).then(function(sessions) {
Parse.Object.destroyAll(sessions);
}, function (err) {
console.log("Internal error " + err);
});
The above will mostly delete or tokens related to the given user. If you wish to delete only tokens used for login, and not for signup or upgrade, then you could put into your query:
query.equalTo('createdWith', { action: 'login', authProvider: 'password'});
As far as i know, deleting a user's last used for login token, then he is logged-out.
To add to the above, if you pass up the user's session key to the Cloud Code function via the X-Parse-Session-Token header, you can use the populated request.user object in the session query directly, instead of the user's ID.

Session token empty for parse cloud code user query

I have written the following query to query a user with a given email and once found, return the session key.
Upon executing it returns an empty response.
I double checked that the user session entry actually exists and is linked to the user I am querying.
var query = new Parse.Query(Parse.User);
var email = request.params.email;
query.equalTo("email",email);
query.first({
success: function(user) {
Parse.Cloud.useMasterKey();
response.success(user.getSessionToken());
},
error: function(user, error) {
response.error(error);
},
useMasterKey: true
});
Ok, since you are using parse.com and not parse-server you need to write
the following line of code:
Parse.Cloud.useMasterKey();
in the first line because you tell cloud code that you want to use master key before you are executing any request to the server. Also it's better to use Promises (according to the best practices)
so at the end your code should look like this:
For running on parse.com
// in parse.com - it's the first thing that you do
Parse.Cloud.useMasterKey();
var query = new Parse.Query(Parse.User);
var email = request.params.email;
query.equalTo("email", email);
query.first().then(function(user) {
response.success(user.getSessionToken());
}, function(error) {
response.error(error);
});
For parse-server
in parse-server you use useMasterKey and send it to the function.
Parse.Cloud.useMasterKey(); will not work here.
// in parse-server - you send useMasterKey to the function
var query = new Parse.Query(Parse.User);
var email = request.params.email;
query.equalTo("email", email);
query.first({
useMasterKey: true
}).then(function(user) {
response.success(user.getSessionToken());
}, function(error) {
response.error(error);
});

Parse for javascript - "error 209 invalid session token" when signing up a new user

I wrote a simple function in an angularJS application for signing up new users:
$scope.registerUser = function(username, password) {
var user = new Parse.User();
user.set("username", username);
user.set("email", username);
user.set("password", password);
user.signUp(null, {
success: function(result) {
console.log(result);
$scope.registerUserSuccess = true;
$scope.registerUserError = false;
$scope.registerUserSuccessMessage = "You have successfully registered!";
$scope.$apply();
$timeout(function(){
$state.go("user");
}, 1000);
},
error: function(user, error) {
$scope.registerUserError = true;
$scope.registerUserSuccess = false;
$scope.registerUserErrorMessage = "Error: [" + error.code + "] " + error.message;
$scope.$apply();
}
});
Initially it worked fine, but when I deleted all the users directly through Parse.com, I can't sign up new users using this function anymore. Each time I get error 209 invalid session token. Here's a screenshot of my Parse database:
I've googled the error message and the solution is always to log out the current user. However, if no users exist this isn't an action I can possibly take.
So I would not only like to fix this problem, but also know how to prevent it in the future so my application can be used safely.
Edit: I created a user directly in Parse.com, wrote a function to log in that user, but got the same error. I am completely stuck until this session issue is resolved.
delete all your session tokens, and anything else Parse related really, from local storage:
if needed turn off legacy session tokens, and follow migration tutorial from scratch:
I encountered this same error when building apps with react native using back4app. to clear anything Parse related, from local storage:
add
import { AsyncStorage } from "react-native";
in to the page and Use
AsyncStorage.clear();
See Example Below:
import { AsyncStorage } from "react-native";
import Parse from "parse/react-native";
// Initialize Parse SDK
Parse.setAsyncStorage(AsyncStorage);
Parse.serverURL = "https://parseapi.back4app.com"; // This is your Server URL
Parse.initialize(
"APPLICATION_ID_HERE", // This is your Application ID
"JAVASCRIPT_KEY_HERE" // This is your Javascript key
);
.........
_handleSignup = () => {
// Pass the username, email and password to Signup function
const user = new Parse.User();
user.set("username", "username);
user.set("email", "email");
user.set("password", "password");
user.signUp().then(user => {
AsyncStorage.clear();
if (condition) {
Alert.alert(
"Successful!",
"Signin Successful! Log in to your account.",
[
{
text: "Proceed",
onPress: () => {
//in this example, i navigated back to my login screen
this.props.navigation.navigate("LoginScreen");
}
}
],
{ cancelable: false }
);
}
})
.catch(error => {
Alert.alert("" +error);
});
};

Parse Cloud Code retrieving a user with objectId

I am trying to get the user object from objectId. I know the objectId is valid. But I can get this simple query to work. What is wrong with it? user is still undefined after the query.
var getUserObject = function(userId){
Parse.Cloud.useMasterKey();
var user;
var userQuery = new Parse.Query(Parse.User);
userQuery.equalTo("objectId", userId);
userQuery.first({
success: function(userRetrieved){
console.log('UserRetrieved is :' + userRetrieved.get("firstName"));
user = userRetrieved;
}
});
console.log('\nUser is: '+ user+'\n');
return user;
};
Quick cloud code example using promises. I've got some documentation in there I hope you can follow. If you need more help let me know.
Parse.Cloud.define("getUserId", function(request, response)
{
//Example where an objectId is passed to a cloud function.
var id = request.params.objectId;
//When getUser(id) is called a promise is returned. Notice the .then this means that once the promise is fulfilled it will continue. See getUser() function below.
getUser(id).then
(
//When the promise is fulfilled function(user) fires, and now we have our USER!
function(user)
{
response.success(user);
}
,
function(error)
{
response.error(error);
}
);
});
function getUser(userId)
{
Parse.Cloud.useMasterKey();
var userQuery = new Parse.Query(Parse.User);
userQuery.equalTo("objectId", userId);
//Here you aren't directly returning a user, but you are returning a function that will sometime in the future return a user. This is considered a promise.
return userQuery.first
({
success: function(userRetrieved)
{
//When the success method fires and you return userRetrieved you fulfill the above promise, and the userRetrieved continues up the chain.
return userRetrieved;
},
error: function(error)
{
return error;
}
});
};
The problem with this is that Parse queries are asynchronous. That means that it will return user (null) before the query has time to execute. Whatever you want to do with the user needs to be put inside of the success. Hopefully my explanation helps you understand why it's undefined.
Look into Promises. It's a nicer way of calling something after you get the result from the first query.

Parse - afterSave and accessing request object?

I send a request to parse that includes a Comment object that has a pointer to a User named "from".
In afterSave I need to read this and I'm having all kinds of problems. beforeSave works just fine, but I want to execute this code in afterSave;
Parse.Cloud.afterSave("Comment", function(request) {
var userQuery = new Parse.Query("User");
userQuery.get(request.object.get("from").id, {
success: function(user) {
},
error : function(error) {
console.error("errrrrrrrr" + error);
}
});
});
Here is the log I'm seeing on parse
errrrrrrrrr [object Object]
EDIT:
I also tried
var userQuery = new Parse.Query("_User");
Seems like I had to call useMasterKey, since I was fetching a user data.
I'm not entirely sure about this though so I'll keep this question open.
Parse.Cloud.useMasterKey();
Have you tried this?
var userQuery = new Parse.Query(Parse.User);
Try to fetch the pointer directly:
var fromUserPointer = request.object.get("from");
fromUserPointer.fetch().then(function(fetchedFromUser){
},function(error){
});
Slightly different approach.
This assumes that you have the comment object available right there, or at least its id.
Instead of querying the User collection, how about this:
var commentQuery = new Parse.Query("Comment");
commentQuery.include("from");
commentQuery.get(<commentId>, {
success: function (comment)
{
var user = comment.get("from"); // Here you have the user object linked to the comment :)
},
error: function (error)
{
console.log("ERROR: ");
console.log(error);
}
});

Resources