how can get the gender and date birthday, using the facebook api? - facebook

(I am using IONIC with the plugin cordova-plugin-facebook4) With this code:
facebookConnectPlugin.api('/me?fields=email,name,gender,picture&access_token=' + authResponse.accessToken, ["public_profile"], function (response) {
I am getting this response:
{"email":"xxxxx#hotmail.com","name":"xxxx Molina","picture":{"data":{"height":50,"is_silhouette":false,"url":"https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=2076928542548945&height=50&width=50&ext=1539748506&hash=AeRdIrWpWFtDY_k8","width":50}},"id":"2076928542548xxx"}
how can get the gender and date birthday of the actual user?

Try this,
facebookConnectPlugin.api("<user-id>/?fields=id,email,gender,birthday",["public_profile","user_birthday"],
function onSuccess (result) {
console.log("Result: ", result);
/* logs:
{
"id": "000000123456789",
"email": "myemail#example.com"
}
*/
}, function onError (error) {
console.error("Failed: ", error);
}
);

Related

Sails js find() finding non-existing users

I'm trying to build a simple server in SailsJS and encountered a problem: I send a POST request to the service in Sails, and I always get a 200 response, even when there's no matching user in the on-disk DB.
My model:
module.exports = {
attributes: {
name: { type: "string" },
lastName: { type: "string" }
}
};
My routes file:
module.exports.routes = {
'post /authTest' : 'UserController.testingAuth'
};
My controller:
module.exports = {
testingAuth : function(req, res) {
var temp = req.param("name");
sails.log(temp);
User.find({ name: 'testing123' }).exec(function(err, user) {
if (err) {
sails.log("inside err block");
return res.serverError(err);
}
sails.log("skipped err block");
return res.json(user);
})
}
};
The way I call the service:
var testUser = { name: 'notMyName', lastName: 'myLastName' };
$http.post("http://localhost:1337/authTest", testUser);
Then on the SailsJS console I see:
debug: notMyName
debug: skipped err block
My local DB has just the following though (localDiskDb.db in .tmp):
{
"data": {
"passport": [],
"user": [
{
"name": "myName",
"lastName": "myLastName",
"createdAt": "2017-11-18T17:26:13.609Z",
"updatedAt": "2017-11-18T17:26:13.609Z",
"id": 1
}
]
},
// some schema stuff, irrelevant here
}
Can someone see anything wrong here? The service receives the posted request object fine, searches for a user that is not in the DB, but finds one anyway?
Check this out:
User.find({ name: 'testing123' }).exec(function(err, user) {
if (err) {
sails.log("inside err block");
return res.serverError(err);
}
sails.log("skipped err block");
return res.json(user);
})
to
User.findOne({ name: 'testing123' }).exec(function(err, user) {
if (err) {
sails.log("inside err block");
return res.serverError(err);
} else if(user){
// user found here
return res.json(user);
} else {
//no user found
return res.json(null);
}
})
If you want to stick with find():
User.find({ name: 'testing123' }).exec(function(err, users) {
if (err) {
sails.log("inside err block");
return res.serverError(err);
} else if(users.length == 0) {
//users is empty array of results
return res.json(users)
} else {
//users is array of N records with criteria 'testing123' in field 'name'
return res.json(users);
}
})

Share an image with react-native-fbsdk?

I'm trying to share an image to Facebook in React Native through the react-native-fbsdk package.
I have the following, copied almost completely from the docs, but I can't figure out how to format the imageUrl, I keep getting errors saying the SharingContent is invalid.
What am I doing wrong here?
const sharePhotoContent = {
contentType: 'photo',
photos: [
{
imageUrl: "./local/image/path.png",
userGenerated: false,
caption: "Hello World"
}
]
};
ShareDialog.canShow(sharePhotoContent).then(
function(canShow) {
if (canShow) {
return ShareDialog.show(sharePhotoContent);
}
}
).then(
function(result) {
if (result.isCancelled) {
AlertIOS.alert('Share cancelled');
} else {
AlertIOS.alert('Share success with postId: ' + result.postId);
}
},
function(error) {
AlertIOS.alert('Share fail with error: ' + error);
}
);
You can use the react-native-image-picker https://github.com/marcshilling/react-native-image-picker to get the uri of the image and use it create a SharePhotoContent.
Also note that you need to have the facebook app installed in order to share an image.
This is working fine for me
shareLinkWithShareDialog() {
let shareLinkContent = {
contentType: 'link',
contentUrl: 'https://www.facebook.com/images/fb_icon_325x325.png',
contentDescription: 'Facebook sharing is easy!'
}
ShareDialog.canShow(shareLinkContent).then((canShow) => {
if (canShow) return ShareDialog.show(shareLinkContent);
}
).then((result) => {
if (result.isCancelled) {
alert('Share cancelled');
} else {
alert('Share success with postId: ' + result.postId);
}
},
function(error) {
alert('Share fail with error: ' + error);
}
);
}

how to post few images with message on facebook

I'm interested to create a post on my page or my feed with few images from my album and some text which will contain some message and some link / handle ( to facebook friend or page )
For now i've tried to create an album, add few images to it but i don't have almost no control of what th description is going to be.
FB.login(function () {
FB.api("/me/accounts", function (response) {
FB.api(
"/usetoken/albums",
"POST",
{
"name": "My Album",
"message": "Some Message",
"access_token": response.data[0].access_token
},
function (response) {
debugger;
if (response && !response.error) {
debugger;
/* handle the result */
}
}
);
});
}, { scope: 'publish_actions,user_photos,manage_pages' });
function post_image() {
FB.api(
"/albumid/photos",
"POST",
{
"url": "imageurl",
"access_token": access_token
},
function (response) {
if (response && !response.error) {
debugger;
/* handle the result */
}
}
);
}
If you really want to publish rich content, you should use Notes.
When you create an album, it will be shown as a status of your page/profile. The status message of that status will be the album description. So you can insert your message into the album description, and you should be ok.

SailsJS: set the status code on an error coming from lifecycle callbacks

I am using the lifecycle callbacks to validate user authorization to change specific attributes.
beforeUpdate: function (valuesToUpdate, cb) {
//details of how authorized is getting set have been omitted
if(!authorized) return cb("Unauthorized!");
cb();
}
When the user is not authorized I receive a 400 Bad Request error
{
msg: "Unauthorized!"
}
I'd like to return a 403 Forbidden. Is there anyway in SailsJS to control the error returned more precisely?
Update: I am using sails v0.10.5
You need to send an instance of WLValidationError to be sent as validation error
//in api/models/User.js
function validationError(invalidAttributes, status, message) {
var WLValidationError = require('../../node_modules/sails/node_modules/waterline/lib/waterline/error/WLValidationError.js');
return new WLValidationError({
invalidAttributes: invalidAttributes,
status: status,
message: message
}
);
}
var User = {
attributes: {
//...
},
ownValidate:: function (values, update, cb) {
//example of not allowed param on update
//if it is an update then do not allow email param
if (update && values.email) {
return cb(validationError({
email: [
{
message: 'Email is not allowed for updates.'
}
]
}, 403 /*status*/));
}
sails.models['user'].findOne(values.email).exec(function (err, user) {
if (err) return cb(err);
if (user) {
return cb(validationError({
email: [
{
value: values.email,
rule: 'E_UNIQUE'
/* unique validation message is left for the default one here */
}
]
}, 409));
}
});
},
beforeCreate: function (values, cb) {
return sails.models['user'].ownValidate(values, false, cb);
},
beforeUpdate: function (values, cb) {
return sails.models['user'].ownValidate(values, true, cb);
}
}
For more info check this

Facebook login scope email doesn't work

I have implement facebook login on my website and I ask for email permission.
In SOME cases, I can't get the email address... But with some facebook accounts, it works...
Here my code :
FB.api('/me', function(response) {
console.log(response);
$.ajax({
type: "POST",
data: response,
url: $('.facebookConnectUrl').text(),
success: function (data, text) {
if (data == 1) {
if (redirectPageAfterLogin === undefined) {
location.reload();
} else if (redirectPageAfterLogin == 'add') {
window.location.replace($('.header .li_sell a').attr('href'));
}
$.fancybox.close();
} else {
$('.waitForConnexion').hide();
$('.errorConnexionFB').show();
$('.errorFacebookRegister').click();
}
// $(document).css('cursor','default');
},
error: function (request, status, error) {
// alert(error);
}
});
// console.log(response);
});
Console.log give me that :
birthday: "03/23/1990"
first_name: "Mathieu"
gender: "male"
id: "100004609354200"
last_name: "XXXX"
link: "https://www.facebook.com/xxxxxxxxx"
locale: "fr_FR"
name: "Mathieu XXXX"
timezone: 1
updated_time: "2012-10-28T12:10:39+0000"
username: "xxxxxx"
In Facebook application details (in french) :
Cette application a besoin de (this app need)
Vos infos de base (your basics informations)
Votre adresse électronique (xxxxx#yahoo.fr) (your email address)
Votre anniversaire (your birthdate)