Parse fetching User inside of hook not working - javascript

i am using this
var USER = Parse.Object.extend("_User");
var query = new Parse.Query(USER);
query.get(request.user.id, {
success: function(results) {
console.log(results);
// results has the list of users with a hometown team with a winning record
},
error : function(error){
console.error(error);
}
to fetch the user making the request. (In this case it's a after save hook)
For any reason "results" just containing:
ParseObjectSubclass { className: '_User', _objCount: 2, id: 'zW3o9c2wbY' }
But i need access to other fields of this user - how can i do so?
Best, Nico

see query documentation the include method is what you are looking for.
Fyi, here's how I would write it:
new Parse.Query(Parse.User)
.include('ptrFieldIWantReturned')
// master key shouldn't be needed, but I can't be sure of your config.
.get(request.user.id, { useMasterKey: true })
.then(
user => console.log('got: ' + user.id),
error => console.error('uh-oh: ' + error.message)
);

Related

MemberOf in Graph Me api azure AD

I am trying to get the member groups of the user to whom user belongs using azure graph api but it is not returning memberof in the api. I am using auth0 for the authentication.
Here is the java script code which I am using.
function(accessToken, ctx, cb) {
const jwt = require('jsonwebtoken#7.1.9');
console.log('azure - retrieve user profile');
// Retrieve the profile from Azure
request.get(
'https://graph.microsoft.com/v1.0/me?$select=id,mail,givenName,surname,userPrincipalName,otherMails,department,memberOf', {
headers: {
'Authorization': 'Bearer ' + accessToken,
},
json: true
},
function(e, r, profile) {
if (e) {
console.log('azure - error while retrieving user profile:');
console.log(e);
return cb(e)
}
if (r.statusCode !== 200) {
console.log('azure - error while retrieving user profile: ' + r.statusCode);
return cb(new Error('StatusCode: ' + r.statusCode));
}
console.log('azure - retrieved user profile.');
// Get the tenant id from the access token
let decodedToken = jwt.decode(accessToken);
let auth0Profile = {
user_id: profile.id,
given_name: profile.givenName,
family_name: profile.surname,
email: profile.mail || profile.otherMails[0] || profile.userPrincipalName,
email_verified: true,
name: profile.givenName + ' ' + profile.surname,
tenant_id: decodedToken.tid,
identification_value: decodedToken.tid,
user_principal_name: profile.userPrincipalName,
user_department: profile.department,
user_member: profile.memberOf
};
cb(null, auth0Profile);
}
);
}
I have added scope (User.Read Directory.Read.All) in Auth0 for the api call.
Can some one let me know why I am not getting memberOf?
If you want to get member groups of the user, along with multiple attributes, the query will not return the expected results.
I tried checking the same query in Microsoft Graph Explorer.
'https://graph.microsoft.com/v1.0/me?$select=id,mail,givenName,surname,userPrincipalName,otherMails,department,memberOf'
Even
for that, except memberOf, all objects displayed:
For getting memberOf, you have to query separately like below:
https://graph.microsoft.com/v1.0/me/memberOf
So, for the workaround, you can make use of the above query by giving it separately without querying with other attributes.
Also please make sure to add GroupMember.Read.All permissions in the scope as mentioned in this Microsoft Doc.
Please find below links if they are helpful: Ref1, Ref2

Parse Cloud Code - Add To Array

Tried loads of different variations with my cloud code and I can't get it to work. Basically I've got a push notification function, and in this function I want to add an object to a PFUser's array, but you can't use a master key in Xcode so here's what I have:
Parse.Cloud.define("iOSPush", function (request, response) {
console.log("Inside iOSPush");
var data = request.params.data;
var not_class = request.params.not_class;
var not_objectid = request.params.not_objectid;
var not_date = request.params.not_date;
var userid = request.params.userid;
var recipientUser = new Parse.Query(Parse.User);
recipientUser.equalTo("objectId", userid);
// set installation query:
var pushQuery = new Parse.Query(Parse.Installation);
pushQuery.equalTo('deviceType', 'ios');
pushQuery.matchesQuery('user', recipientUser);
pushQuery.find({ useMasterKey: true }).then(function(object) {
response.success(object);
console.log("pushQuery got " + object.length);
}, function(error) {
response.error(error);
console.error("pushQuery find failed. error = " + error.message);
});
// send push notification query:
Parse.Push.send({
where: pushQuery,
data: data
}, { useMasterKey: true }).then(function() {
console.log("### push sent!");
// create notification:
var notification = {
"title": not_class,
"body": request.params.data.alert,
"class": not_class,
"objectId": not_objectid,
"date": not_date
};
// get notifications:
var tmp_notifications = recipientUser.get("notifications");
// add notification:
tmp_notifications.push(notification);
// update with notifications:
recipientUser.set("notifications", tmp_notifications);
recipientUser.save();
}, function(error) {
console.error("### push error" + error.message);
});
response.success('success. end of iospush');
});
The Xcode cloud function I have provides the correct information, the function gets to the end.. just the function is not setting the notifications for some reason
I ended up figuring out the answer to this post myself. The reason this didn't work is because I needed to first fetch the user object in a separate query, then save it using the master key. I also found out that there's a function for appending data onto an existing array without having to create another one (parseObject.add()):
var userQ = new Parse.Query(Parse.User);
userQ.get(userid, {
success: function(theuser) {
console.log("### got userrrrrrrrrr!");
theuser.add("notifications", n_object);
theuser.save(null, {useMasterKey:true});
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
This set of code was executed just before:
response.success('success. end of iospush');

Parse Server Cloud Code Update User

I am attempting to update a parse user field and the function stops in the middle of it:
Parse.Cloud.define("modifyAdminStatus", function(request, response) {
var userQuery = new Parse.Query(Parse.User);
var isAdmin = request.params.adminStatus;
console.log("isAdmin:" + isAdmin);
userQuery.equalTo("username", request.params.username);
userQuery.find({ useMasterKey: true,
success: function(user) {
console.log(user.length);
console.log("Got User")
console.log(user);
user.set("isAdmin", isAdmin);
console.log("Set Status");
user.save(null, {useMasterKey: true,
success: function(user) {
response.success();
},
error: function(error) {
response.error(error.message);
}
});
},
error: function(error) {
response.error(error.message);
}
});
});
I dont get any syntax errors, when i run the code i get:
1
Got User
[ ParseUser { _objCount: 2, className: '_User', id: '2vigcitsl6' } ]
in my console. However, it seems to stop the code after i attempt to set the admin status. I have tried running it using useMasterKey but that didnt do anything so maybe I'm missing something and where the useMasterKey should go?
The answer is:
query.find({
... code here
});
Returns an array, using query.first (or selecting one object from the array) instead will get one object and allow you to set things on it.
When you're trying to save the user, parse expects two parameters. The first should be an object containing any changes, and the second should be the save options.
So in your case, simply change your save to user.save (null, {useMasterKey:true, success...})
The way you have it now would create a column on Parse.User entitled useMasterKey, if permissions allow.

How to prevent current user get notified?

I'm making an app that allows user to like and comment on other user post. I'm using Parse as my backend. I'm able to notified user everytime their post liked or commented. However if current user like or comment on their own post this current user still notified. How can I prevent this?
Here is the js code that I use:
Parse.Cloud.afterSave('Likes', function(request) {
// read pointer async
request.object.get("likedPost").fetch().then(function(like){
// 'post' is the commentedPost object here
var liker = like.get('createdBy');
// proceed with the rest of your code - unchanged
var query = new Parse.Query(Parse.Installation);
query.equalTo('jooveUser', liker);
Parse.Push.send({
where: query, // Set our Installation query.
data: {
alert: message = request.user.get('username') + ' liked your post',
badge: "Increment",
sound: "facebook_pop.mp3",
t : "l",
lid : request.object.id,
pid: request.object.get('likedPostId'),
lu : request.user.get('username'),
ca : request.object.createdAt,
pf : request.user.get('profilePicture')
}
}, {
success: function() {
console.log("push sent")
},
error: function(err) {
console.log("push not sent");
}
});
});
});
If I understand the context of where this code is correctly,
I recommend checking
if request.user.get("username") != Parse.CurrentUser.get("username")
Before sending out the push notification
Where is your cloud function being called from? If you're calling it from your ios code, then before you call the cloud code function, just prelude it with something like this:
if (PFUser.currentUser?.valueForKey("userName") as! String) != (parseUser.valueForKey("userName") as! String)

Parse Cloud Code: Delete All Objects After Query

Scenario
I have an app that allows users to create an account, but also allows the user's the ability to delete their account. Upon deletion of their account I have a Cloud Code function that will delete all of the "Post"s the user has made. The cloud code I am using is...
//Delete all User's posts
Parse.Cloud.define("deletePosts", function(request, response) {
var userID = request.params.userID;
var query = new Parse.Query(Parse.Post);
query.equalTo("postedByID", userID);
query.find().then(function (users) {
//What do I do HERE to delete the posts?
users.save().then(function(user) {
response.success(user);
}, function(error) {
response.error(error)
});
}, function (error) {
response.error(error);
});
});
Question
Once I have the query made for all of the user's posts, how do I then delete them? (see: //What do I do HERE?)
You could use
Parse.Object.destroyAll(users); // As per your code – what you call users here are actually posts
See: http://parseplatform.org/Parse-SDK-JS/api/classes/Parse.Object.html#methods_destroyAll
Also, consider using Parse.Cloud.afterDelete on Parse.User (if that is what you mean by "deleting account") to do cleanups such as these.
Oh, and just to be complete, you don't need the save() routine after destroyAll()
Updates in-line below below your "What do I do HERE..." comment:
NOTES:
You don't need to call the save() method, so I took that out.
This, of course, is merely a matter of personal preference, but you may want to choose a parameter name that makes a little more sense than "users", since you're really not querying users, but rather Posts (that just happen to be related to a user).
Parse.Cloud.define("deletePosts", function(request, response) {
var userID = request.params.userID;
var query = new Parse.Query(Parse.Post);
query.equalTo("postedByID", userID);
query.find().then(function (users) {
//What do I do HERE to delete the posts?
users.forEach(function(user) {
user.destroy({
success: function() {
// SUCCESS CODE HERE, IF YOU WANT
},
error: function() {
// ERROR CODE HERE, IF YOU WANT
}
});
});
}, function (error) {
response.error(error);
});
});

Categories

Resources