Meteor,Access Google contacts of loggedin user - javascript

How to get all contacts of a loggedin user,i added request permission to access google contacts
requestPermissions: {
facebook: ['email', 'user_friends','read_friendlists'],
google:['https://www.google.com/m8/feeds']
},
I don't know how to access contacts,i tried to google it but i'm confused with the results.
Does anyone know how to do this?
can anyone point me to the answer?
I really appreciate any help

I Just used google-contacts atmosphere package and write the following function in server side and it worked for me
var opts= { email: Meteor.user().services.google.email,
consumerKey: "APIKEY",
consumerSecret: "APPSECRET",
token: Meteor.user().services.google.accessToken,
refreshToken: Meteor.user().services.google.refreshToken};
gcontacts = new GoogleContacts(opts);
gcontacts.refreshAccessToken(opts.refreshToken, function (err, accessToken)
{
if(err)
{
console.log ('gcontact.refreshToken, ', err);
return false;
}
else
{
console.log ('gcontact.access token success!');
gcontacts.token = accessToken;
gcontacts.getContacts(function(err, contact)
{
\\here i am able to access all contacts
console.log(contact);
})
}
});
To do this,you need a refreshToken from google,by default meteor will not get it for you.
Add the following code in client side to get the refreshtoken(requestOfflineToken)
Accounts.ui.config({
requestPermissions: {
facebook: ['email', 'user_friends','read_friendlists'],
google:['https://www.google.com/m8/feeds']
},
requestOfflineToken: {
google: true
},
passwordSignupFields: 'USERNAME_AND_EMAIL'
});
NOTE: To work with contacts API you need to enable contacts api in your google console.
Hope it may help someone out there.

Related

Parse-server social login

I am developing application based on Parse-server and I want to offer social login. I found this guide in the documentation http://docs.parseplatform.org/js/guide/#linking-users.
I started to implement the social login by google. I did following steps:
1) I added following lines to the ParseServer settings
var api = new ParseServer({
...
auth:{
google: {}
},
...
});
2) I did the authentication by hello.js on the client side (call user._linkWith function on login)
hello.init({
google: 'My Google id'
});
hello.on('auth.login', function(auth) {
// Call user information, for the given network
hello(auth.network).api('me').then(function(r) {
const user = new Parse.User();
user._linkWith(auth.network, auth.authResponse).then(function(user){
console.log('You are logged in successfully.');
});
});
});
When I debugged it, I found that it fails in _linkWith() function, when provider object is preparing. Object AuthProviders, which should store all providers, is empty. Because of it the statement provider = authProviders['google']; leads to undefined. Invoking provider.authenticate(...); leads to error "Cannot read property 'authenticate' of undefined"
What am I missing or what am I doing wrong?
Thanks for all your answers.
Honza
Did you register the authenticationProvider? You can find examples in our unit tests on how to do so:
https://github.com/parse-community/parse-server/blob/5813fd0bf8350a97d529e5e608e7620b2b65fd0c/spec/AuthenticationAdapters.spec.js#L139
I also got this error and looked at the _linkWith(provider, options) source code. It checks if options has an authData field (which in turn should contain id and credentials). If so, it uses options.authData. Otherwise it falls back on looking up a previously registered authentication provider mentioned in the previous answer.
This is a fragment of the code I'm using:
const authData = {
"id": profile.getId(),
"id_token": id_token
}
const options = {
"authData": authData
}
const user = new Parse.User();
user._linkWith('google', options).then(function(user) {
console.log('Successful user._linkWith(). returned user=' + JSON.stringify(user))
}, function(error) {
console.log('Error linking/creating user: ' + error)
alert('Error linking/creating user: ' + error)
// TODO handle error
})

How to use servicebus topic sessions in azure functionapp using javascript

I have an Azure Functionapp that processes some data and pushes that data into an Azure servicebus topic.
I require sessions to be enabled on my servicebus topic subscription. I cannot seem to find a way to set the session id when using the javascript functionapp API.
Here is a modified extract from my function app:
module.exports = function (context, streamInput) {
context.bindings.outputSbMsg = [];
context.bindings.logMessage = [];
function push(response) {
let message = {
body: CrowdSourceDatum.encode(response).finish()
, customProperties: {
protoType: manifest.Type
, version: manifest.Version
, id: functionId
, rootType: manifest.RootType
}
, brokerProperties: {
SessionId: "1"
}
context.bindings.outputSbMsg.push(message);
}
.......... some magic happens here.
push(crowdSourceDatum);
context.done();
}
But the sessionId does not seem to get set at all. Any idea on how its possible to enable this?
I tested sessionid on my function, I can set the session id property of a message and view it in Service Bus explorer. Here is my sample code.
var connectionString = 'servicebus_connectionstring';
var serviceBusService = azure.createServiceBusService(connectionString);
var message = {
body: '',
customProperties:
{
messagenumber: 0
},
brokerProperties:
{
SessionId: "1"
}
};
message.body= 'This is Message #101';
serviceBusService.sendTopicMessage('testtopic', message, function(error)
{
if (error)
{
console.log(error);
}
});
Here is the test result.
Please make sure you have enabled the portioning and sessions when you created the topic and the subscription.

Youtube API returns account details of a different user

I am using google's API for node.js
https://www.npmjs.com/package/googleapis
I am trying to get an array of all channels which belong to the person
who logged into my website with his google account.
I am using this scope for this matter:
''https://www.googleapis.com/auth/youtube.readonly'
Now here is part of my code:
app.get("/oauthcallback", function(req, res) {
//google redirected us back in here with random token
var code = req.query.code;
oauth2Client.getToken(code, function(err, tokens) { //let's check if the query code is valid.
if (err) { //invalid query code.
console.log(err);
res.send(err);
return;
}
//google now verified that the login was correct.
googleAccountVerified(tokens, res); //now decide what to do with it
});
});
function googleAccountVerified(tokens, res){ //successfully verified.
//user was verified by google, continue.
oauth2Client.setCredentials(tokens); //save tokens to an object
//now ask google for the user's details
//with the verified tokens you got.
youtube.channels.list({
forUsername: true,
part: "snippet",
auth: oauth2Client
}, function (err, response) {
if(err) {
res.send("Something went wrong, can't get your google info");
return;
}
console.log(response.items[0].snippet);
res.send("test");
});
}
Now, in this console.log:
console.log(response.items[0].snippet);
I am getting the same info, no matter what account I am using to log into my website:
{ title: 'True',
description: '',
publishedAt: '2005-10-14T10:09:11.000Z',
thumbnails:
{ default: { url: 'https://i.ytimg.com/i/G9p-zLTq1mO1KAwzN2h0YQ/1.jpg?v=51448e08' },
medium: { url: 'https://i.ytimg.com/i/G9p-zLTq1mO1KAwzN2h0YQ/mq1.jpg?v=51448e08' },
high: { url: 'https://i.ytimg.com/i/G9p-zLTq1mO1KAwzN2h0YQ/hq1.jpg?v=51448e08' } },
localized: { title: 'True', description: '' } }
if I do console.log(response) which is the entire response
I get:
{ kind: 'youtube#channelListResponse',
etag: '"m2yskBQFythfE4irbTIeOgYYfBU/ch97FwhvtkdYcbQGBeya1XtFqyQ"',
pageInfo: { totalResults: 1, resultsPerPage: 5 },
items:
[ { kind: 'youtube#channel',
etag: '"m2yskBQFythfE4irbTIeOgYYfBU/bBTQeJyetWCB7vBdSCu-7VLgZug"',
id: 'UCG9p-zLTq1mO1KAwzN2h0YQ',
snippet: [Object] } ] }
So, two problems here:
1) How do I get an array of owned channels by the logged user,
inside the array I need objects which will represent each channel and basic info like channel name, profile pic.
2) why am I getting the info of some random youtube channel called "True"
Not sure about question one but for question two you get the information for the channel called true because you are asking for it. forUsername: true
I would hope that once you correct this the response may contain more than one channel if the username has more than one.
Just a follow up to the question about basic info.
You dont use Youtube API to get an account's profile information. Instead, try Retrieve Profile Information with G+:
To retrieve profile information for a user, use the people.get API method. To get profile information for the currently authorized user, use the userId value of me.
JavaScript example:
// This sample assumes a client object has been created.
// To learn more about creating a client, check out the starter:
// https://developers.google.com/+/quickstart/javascript
gapi.client.load('plus','v1', function(){
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function(resp) {
console.log('Retrieved profile for:' + resp.displayName);
});
});
Google Sign-in for Websites also enables Getting profile information:
After you have signed in a user with Google using the default scopes, you can access the user's Google ID, name, profile URL, and email address.
To retrieve profile information for a user, use the getBasicProfile() method. For example:
if (auth2.isSignedIn.get()) {
var profile = auth2.currentUser.get().getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Full Name: ' + profile.getName());
console.log('Given Name: ' + profile.getGivenName());
console.log('Family Name: ' + profile.getFamilyName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
}

Twitter authentication in Codebird JS

I am very new to integrating social sites into a website. I somewhat managed to integrate Facebook, but I have no idea how to integrate Twitter.
I want to login through a Twitter account, then get the username and some other data from Twitter. I have a consumer key and consumer secret. I'm not sure how to proceed from here, and my Google searches haven't helped so far.
I am trying with codebird js:
$(function() {
$('#twitter').click(function(e) {
e.preventDefault();
var cb = new Codebird;
cb.setConsumerKey("redacted", "redacted");
cb.__call(
"oauth_requestToken",
{ oauth_callback: "http://127.0.0.1:49479/" },
function (reply, rate, err) {
if (err) {
console.log("error response or timeout exceeded" + err.error);
}
if (reply) {
// stores it
cb.setToken(reply.oauth_token, reply.oauth_token_secret);
// gets the authorize screen URL
cb.__call(
"oauth_authorize",
{},
function (auth_url) {
window.codebird_auth = window.open(auth_url);
}
);
}
}
);
cb.__call(
"account_verifyCredentials",
{},
function(reply) {
console.log(reply);
}
);
})
});
But I get
Your credentials do not allow access to this resource
How can I resolve this and get the user data? I am open to using an alternate Twitter implementation.
You cannot call cb._call( "account_verifyCredentials"... there.
The code only has a request token, NOT an access token, which you will only receive after the user authorizes your app (on the Twitter auth popup).
You are using the "callback URL without PIN" method, as documented on the README. So you'll need to implement that example code on your http://127.0.0.1:49479/ page.
Also, this essentially requires that you store the oauth credentials somewhere. In my example below, I've used localStorage.
$(function () {
$('#twitter').click(function (e) {
e.preventDefault();
var cb = new Codebird;
cb.setConsumerKey("CeDhZjVa0d8W02gWuflPWQmmo", "YO4RI2UoinJ95sonHGnxtYt4XFtlAhIEyt89oJ8ZajClOyZhka");
var oauth_token = localStorage.getItem("oauth_token");
var oauth_token_secret = localStorage.getItem("oauth_token_secret");
if (oauth_token && oauth_token_secret) {
cb.setToken(oauth_token, oauth_token_secret);
} else {
cb.__call(
"oauth_requestToken", {
oauth_callback: "http://127.0.0.1:49479/"
},
function (reply, rate, err) {
if (err) {
console.log("error response or timeout exceeded" + err.error);
}
if (reply) {
console.log("reply", reply)
// stores it
cb.setToken(reply.oauth_token, reply.oauth_token_secret);
// save the token for the redirect (after user authorizes)
// we'll want to compare these values
localStorage.setItem("oauth_token", reply.oauth_token);
localStorage.setItem("oauth_token_secret", reply.oauth_token_secret);
// gets the authorize screen URL
cb.__call(
"oauth_authorize", {},
function (auth_url) {
console.log("auth_url", auth_url);
// JSFiddle doesn't open windows:
// window.open(auth_url);
$("#authorize").attr("href", auth_url);
// after user authorizes, user will be redirected to
// http://127.0.0.1:49479/?oauth_token=[some_token]&oauth_verifier=[some_verifier]
// then follow this section for coding that page:
// https://github.com/jublonet/codebird-js#authenticating-using-a-callback-url-without-pin
});
}
});
}
})
});
Also made a JSFiddle

In Facebook login, how do you see the permissions that the user granted?

As of December 2011, Facebook changed their API and broke everyone's FB.login. The following code will no longer work:
FB.login(
function(response) {
if (response.session) {
console.info('you logged in');
if (response.perms) {
console.info('you granted some permissions');
}
}
}, {
perms: 'publish_stream'
}
);
Instead you have to do this:
FB.login(
function(response) {
if (response.authResponse) {
console.info('you are logged in', response);
}
}, {
scope: 'publish_stream'
}
);
This at least makes login work, but I'm no longer able to see if they accepted my requested permission or not. When I log out the response, it does not contain a "perms" key anymore:
response: {
authResponse {
accessToken: string,
expiresIn: number,
signedRequest: string,
userID: string
},
status
}
it will say connected regardless. you might have to query for the perms.
As far as I know user cannot connect to the application without confirming all the requested permissions.
I admit I may be wrong but as a user and developer I haven't seen it is possible.

Categories

Resources