Get userID with the new JS SDK - userid

how would you do something like:
strUserID = FB.getSession().uid;
with the new JS SDK?
simple call to get the users id after logged in?

REF: http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
FB.getLoginStatus(function(response) {
if (response.authResponse) {
// logged in and connected user, someone you know
} else {
// no user session available, someone you dont know
}
});
Response:
{
status: 'connected',
authResponse: {
accessToken: '...',
expiresIn:'...',
signedRequest:'...',
userID:'...'
}
}

Related

Update subscription Braintree and prorateCharges Error ID already taken

Hey everyone so I am trying to update a monthly subscription to another monthly subscription in Braintree and prorate the charges. After reading their documentation I am stumped on how to do this effectively. When I go to update the subscription I get the following error message: 'ID has already been taken.'
router.put("/update-subscription", async (req, res, next) => {
try {
console.log("hit route");
if (!res.locals.user) {
throw { status: 403, message: "Not logged in." };
} else {
const { subscriptionId, selectedPlanName } = req.body;
const oldSubscriptionId = subscriptionId;
const selectedPlanId = selectedPlanName.replace(/\s/g, "_");
const userId = res.locals.user.id;
const [[userData]] = await database.query("call getUserByUserId(?)", [
userId
]);
const { braintreeId } = userData;
const { paymentMethods } = await gateway.customer.find("" + braintreeId);
const { token } = paymentMethods.find(p => p.default);
console.log("oldSubscriptionId", oldSubscriptionId);
console.log("selectedPlanId", selectedPlanId);
const subUpdateResponse = await gateway.subscription.update(
oldSubscriptionId,
{
id: selectedPlanId,
paymentMethodToken: token,
options: {
prorateCharges: true
}
}
);
console.log("subUpdateResponse", subUpdateResponse);
if (subUpdateResponse.success) {
res.send("Successfully updated plan");
} else {
throw { message: "An error occurred." };
}
}
} catch (error) {
next(error);
}
});
Heres the Log
subUpdateResponse ErrorResponse {
errors:
ValidationErrorsCollection {
validationErrors: {},
errorCollections: { subscription: [Object] } },
params:
{ id: 'SILVER_MONTHLY',
paymentMethodToken: 'krs2p5',
options: { prorateCharges: 'true' } },
message: 'ID has already been taken.',
success: false }
{ message: 'An error occurred.' }
I understand that the 'SILVER_MONTHLY' ID is already used I mean I am trying to update from one subscription to the other obviously the one I am trying to update to has already been used. Again all I am trying to do is update from the subscription the user is already on to the subscription the user picked to update to. Any help here would be great. Thanks
Full disclosure, I work at Braintree. If you have any further questions, I recommend contacting Support
You are passing the plan ID in the incorrect parameter. The id parameter can be used for a new subscription ID that you'd like to have. To update to a different plan, you'll need to pass a planId parameter, which represents the plan you'd like to update them to.
I also noticed you are passing a paymentMethodToken parameter. This is to be used only if you're updating the payment method token. If that's what you intended, carry on! Otherwise, you do not need to pass this parameter in your update request.
As an example, if you wanted to update the plan and keep the same payment method token, your request may look something like this:
const subUpdateResponse = await gateway.subscription.update(
oldSubscriptionId,
{
planId: selectedPlanId,
options: {
prorateCharges: true
}
}
);

How to authenticate with a Facebook token?

I'm POST'ing to http://localhost:3030/authentication and trying to retrieve a JWT and create a user model using Facebook oAuth. My client side is React and seperate to the API.
My body:
{
"strategy": "facebook",
"accessToken": "EAALOM2rXQ50BAL5vERqa6YTJzyKZAeG4Yd9ZBPuqHfRmFzOpsQiTHEc1uS1sBaot7V9F7JlufpAWqqJoHIG8RCghLdBIKssKRyQqMLxiHvCPTjVDXqaR1rM4FhEXk55nFU0ZBZBP2KNVOoDNAGUBtJAOKaUdbeszLE0gXxgoF0DWgZBsRfVsZBFRBenQLMZBwZCDPIF606aHrA0CdDrcTRqSbcJWZCSlYIMwZD",
"facebookId": "10155772119707013",
"email": "joshn#hotmail.com.au"
}
But I'm getting a HTML page response saying 'You are not logged in: You are not logged in. Please log in and try again.'
Same issue # https://github.com/feathersjs/authentication-oauth2/issues/22 if anyone has figured out a solution to this.
This is possible with https://github.com/drudge/passport-facebook-token
My solution (inside authentication.js) is to extend a custom Passport strategy:
app.passport.use('facebook-token', new FacebookTokenStrategy({
clientID: process.env.FACEBOOK_CLIENT_ID,
clientSecret: process.env.FACEBOOK_CLIENT_SECRET
}, function (accessToken, refreshToken, profile, done) {
app.service('users').find({
query: {
facebookId: profile.id
}
}).then((userData) => {
if (userData.data.length > 0) {
return done(null, userData.data[0]);
} else {
app.service('users').create({}).then((data) => {
return done(null, data);
});
}
});
}
));

get data from json after successful login to facebook

I'm implement ionic facebook login in my app and I succeed to login but the issue I don't know how to access to data. i want to get the uid,email,displayName and more.
this is my facebook login
loginFacebook() {
let provider = new firebase.auth.FacebookAuthProvider();
firebase.auth().signInWithRedirect(provider).then(() => {
firebase.auth().getRedirectResult().then((userData)=>{
let profileUs = JSON.stringify(userData);
console.log('my json:' +userData);
// i want to get uid,email,displayName
}).catch(function(error){
alert(JSON.stringify(error));
});
})
}
You just need to access userData's attributes:
loginFacebook() {
let provider = new firebase.auth.FacebookAuthProvider();
firebase.auth().signInWithRedirect(provider).then(() => {
firebase.auth().getRedirectResult().then((userData)=>{
let uid = userData.user.uid
let displayName = userData.user.displayName
}).catch(function(error){
alert(JSON.stringify(error));
});
})
}

Twitter search API returns no tweets?

I'm using NodeJS and an npm package called oauth to communicate with Twitter's search API. For some reason however, twitter is returning to me an empty array of statuses without any error... What is even more confusing is the fact that using a tool like Postman with the exact same request and keys returns the list of tweets? It makes no sense! Here is my request:
URL: https://api.twitter.com/1.1/search/tweets.json?count=100&q=hello&since_id=577103514154893312&max_id=577103544903462913
Here is my code:
var twitter_auth = new OAuth(
"https://api.twitter.com/oauth/request_token",
"https://api.twitter.com/oauth/access_token",
config.consumer_key,
config.consumer_secret,
"1.0A",
null,
"HMAC-SHA1"
);
var request = twitter_auth.get(
"https://api.twitter.com/1.1/search/tweets.json" + url,
config.access_token,
config.access_token_secret
);
var chunk = "", message = "", that = this;
request.on("response", function(response){
response.setEncoding("utf8");
response.on("data", function(data){
chunk += data;
try {
message = JSON.parse(chunk);
} catch(e) {
return;
}
console.log(message);
if(message.statuses)
{
for(var i = 0; i < message.statuses.length; i++)
{
var tweet = message.statuses[i];
that.termData[term.name].push(tweet);
}
if(message.search_metadata.next_results)
{
that.openRequests.push(that.createNewSearch(message.search_metadata.next_results, term));
}
else
{
that.termCompleted(term);
}
}
else if(message)
{
console.log("Response does not appear to be valid.");
}
});
response.on("end", function(){
console.log("Search API End");
});
response.on("error", function(err){
console.log("Search API Error", err);
});
});
request.end();
The console.log(message) is returning this:
{
statuses: [],
search_metadata: {
completed_in: 0.007,
max_id: 577103544903462900,
max_id_str: '577103544903462913',
query: 'hello',
refresh_url: '?since_id=577103544903462913&q=hello&include_entities=1',
count: 100,
since_id: 577103514154893300,
since_id_str: '577103514154893312'
}
}
Any ideas what is going on? Why is the statuses array empty in my code but full of tweets in Postman?
This issue was described at twittercommunity.com.
Accordingly answer of user rchoi(Twitter Staff):
"Regarding web vs. API search, we're aware that the two return different results at the moment. We made upgrades to the web search. There is no timeline for those
changes to be brought to other parts of our system."
Try to use
https://dev.twitter.com/rest/reference/get/statuses/mentions_timeline
https://dev.twitter.com/rest/reference/get/statuses/user_timeline
if you get empty result with api search functionality.
Please follow this link
https://twittercommunity.com/t/search-tweets-api-returned-empty-statuses-result-for-some-queries/12257/6

sails.js: how to update model

Forgive my noob question. I'm using angularjs to send a user model (json) with varying fields. It works well with sails.js default PUT. I overrode the PUT, the problem is that I wish to update the model with the received JSON and do some processing on the modified model. Now I can't update the model with
User.update({
id: req.body.id
},{
req.body
}, function(err, users) {
// Error handling
if (err) {
return console.log(err);
// Updated users successfully!
} else {
console.log("Users updated:", users);
}
});
Please help
EDIT:
After knocking my head on the wall for days, problem solved! I know, my code formatting here is not the best..
changed this:
{
req.body
}
to just:
req.body
(without the braces)
full snippet becomes:
User.update({
id: req.body.id
},
req.body
, function(err, users) {
// Error handling
if (err) {
return console.log(err);
// Updated users successfully!
} else {
console.log("Users updated:", users);
}
});
Thanks.
So you figured out your problem, sort of. req.body is already an object. But you really should sanitize it before you put it into your update and then save the object. There's a lot of reasons for this but with Mongo when you get only a partial object you'll replace the object in the collection which, in your example with a user, could be bad. When I send users to the frontend I cull off things I don't want transmitted all over like passwords. The other reason is the golden rule of web application development - never trust the client! I'd start with something like:
var user = User.findOne(req.body.id).done(function(error, user) {
if(error) {
// do something with the error.
}
if(req.body.email) {
// validate whether the email address is valid?
// Then save it to the object.
user.email = req.body.email;
}
// Repeat for each eligible attribute, etc.
user.save(function(error) {
if(error) {
// do something with the error.
} else {
// value saved!
req.send(user);
}
});
});