Fetching Google Plus profile url and email - api

If I open someone's Google Plus Profile Page I see contact info and information shared on Google Plus. I looking for similar information on Google API. I'm trying to fetch list of user's contacts with email and google plus profile id, that's all.
Here I can fetch user connections with Google Plus profile url but without email or phone number.
https://people.googleapis.com/v1/people/me/connections
Here I can fetch person contacts with email and phone number (OAuth2) - without Google Plus profile url nor id
https://www.google.com/m8/feeds/contacts/{GOOGLE_ACCOUNT_NAME}%40gmail.com/full?alt=json
But I don't know how to combine this two outputs, to get have Google Plus profile url and contact information.

You are correct. 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.
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);
});
});
Note that this method requires authentication using a token that has been granted the OAuth scope https://www.googleapis.com/auth/plus.login or https://www.googleapis.com/auth/plus.me.
Plus.People.List listPeople = plus.people().list(
"me", "visible");
listPeople.setMaxResults(5L);
PeopleFeed peopleFeed = listPeople.execute();
List<Person> people = peopleFeed.getItems();
// Loop through until we arrive at an empty page
while (people != null) {
for (Person person : people) {
System.out.println(person.getDisplayName());
}
// We will know we are on the last page when the next page token is
// null.
// If this is the case, break.
if (peopleFeed.getNextPageToken() == null) {
break;
}
// Prepare the next page of results
listPeople.setPageToken(peopleFeed.getNextPageToken());
// Execute and process the next page request
peopleFeed = listPeople.execute();
people = peopleFeed.getItems();
}
Here's a related SO ticket which discuss how to fetch user email from Google+ Oauth: How to get user email from google plus oauth

You can use the Google Api to fetch the user profile. For this
Create project in google api console.Configure the credentials client id,client secret. Add your redirect uri.
Authorize the user with OAuth2.0 from your project with scopes https://www.googleapis.com/auth/plus.me , https://www.googleapis.com/auth/plus.login.
Retrieve the response code after authorization.Give POST method to the token endpoint url.
Retrieve the access_token, refresh_token,id_token etc from gooogle plus.
By using the access_token. call GET method to the url "https://www.googleapis.com/plus/v1/people/me/?access_token='{YOUR_ACCESS_TOKEN}'".
You will be given by an json array containing the authorized user profile details like email, name, id etc.

Related

Express REST API with JWT and Routes

I am trying to create an Express API with JWT authentication.
However, I was wondering how to best allow users to only access their own resources.
For example if there is a user with id 1 and each user has a list of books in the database:
The id is already part of the JWT Token but commonly there would be a request to something like /users/1/books to get all of the books belonging to user 1.
Would my routes typically still look like this and I would just check the id in the token is the same the request is made for, or is there any other/simpler way?
Thank you for your help!
You can define, some access rights permissions base on the user role or id.
Example: roles : {root, admin, staff}
Then, in your routes you can have some checking whether this user have the permission to access the functions or you can do in the controller level to check the access rights.
You need to define model relations between User, UserModel. In your case as I understand you need to have the relations between UserModel and BooksModels.
UserModel hasMany BooksModel
When you call findOne() to retrieve specific user's data, you can just define include: 'aliasModelName', to retrieve the users related book data.
With this way, you can only have 1endpoint users/:id to retrieve users data and book data. It depends on what you really want, you can also have an endpoint users/:id/books to get all books that belongs to this user.
Your model definition will then become
BooksModel belongsTo UserModel
If you use hasMany you can get all the results that you need in just one query.
Hope this helps!
When user sends the login credentials, you check database if the email exists, if yes then you check if the password matches. If user successfully signins you create the token.
const token = jwt.sign({ _id: user._id, email: user.email }, "this-is-secret", {
expiresIn: "1h",
});
this token is sent to the browser, whenever user make requests, it manually attachs this token to the req, and sends the request to your server. You check if the token is valid, by using the secret key (in this case "this-is-secret").
const decodedToken = jwt.verify(token, "this-is-secret")
req.userId = decodedToken.userId;
now "userId" is attached to the req object. Now when you fetch the data from database, the items that you are fetching, you write a query that (implementation depends on which database you are using)
book.userId=req.userId

Twitter Ads API error: INSUFFICIENT_USER_AUTHORIZED_PERMISSION. How to solve it?

I am trying to perform a request to the twitter Ads API in my dev environment. I am already registered to get access to this service.
I have received a confirmation e-mail like this:
Your application (ID:12345678) has been approved for the Twitter Ads API program and your organization has been granted a Developer license for Read/Write access. ...
This is why I suppose to have my APP ready to query the Ads API.
Besides that I have information about the APP (tokens and secrets) in the page https://developer.twitter.com/en/apps but I can't find any reference to the account_id, mentioned in the official documentation.
Advertising accounts are registered on ads.twitter.com and identified
in the API by account_id. Advertising accounts link directly to funding
sources and leverage content from one or more Twitter user accounts as
‘promotable users’. Each advertising account can grant permission to
one or more Twitter user accounts. The advertising account, or “current
account,” is represented in nearly every URL executed as an in-line
:account_id parameter.
Following this post I have create the follow code in oder to get access to the Twitter Ads API:
$settings = array(
'oauth_access_token' => env('TWITTER_ACCESS_TOKEN'),
'oauth_access_token_secret' => env('TWITTER_ACCESS_TOKEN_SECRET'),
'consumer_key' => env('TWITTER_CONSUMER_KEY'),
'consumer_secret' => env('TWITTER_CONSUMER_SECRET'),
);
$url = 'https://api.twitter.com/1.1/followers/ids.json';
$getfield = '?screen_name=J7mbo';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchangeService($settings);
$data = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
dd($data);
The previous code is working (I am not querying Ads API. But the next one ( querying the Ads Api) is not working:
$url = 'https://ads-api.twitter.com/5/accounts';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchangeService($settings);
$data = $twitter->buildOauth($url, $requestMethod)->performRequest();
dd($data);
{"errors":[{"code":"INSUFFICIENT_USER_AUTHORIZED_PERMISSION","message":"User 2222222222 is not authorized to make this request. Please have them reauthorize with your client application APPNAme."}],"request":{"params":{}}}
What am I missing?
I have found a solution. I don't know if this is the only one but it works.
We must instal Twurl. Twurl is a curl-like application, tailored specifically for the Twitter API.
Install twurl in your system. $ sudo gem install twurl
Set authorization to twurl acceess your twitter APP. $ twurl authorize --consumer-key xxxxx --consumer-secret xxxxx
That is the output for the prevoius command: Go to https://api.twitter.com/oauth/authorize?oauth_consumer_key=xxxx&oauth_nonce=ffff&oauth_signature=bbb&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1556889574&oauth_token=ddd&oauth_version=1.0 and paste in the supplied PIN
Open the browser copy and paste the provided URL https://api. .... version=1.0
You will be redirected to a page asking to confirm the authorization. Confirm it.
You will receive a message: 'You've granted access to APP_Name! Next, return to APP_Name and enter this PIN to complete the authorization process. PIN = 09010101'.
Just copy the PIN number and paste back in the terminal and hit enter.
You will get a message in the terminal Authorization successful.
Go to yor APP_Name page https://developer.twitter.com/en/apps/123456 and go to Keys and tokens section. You need to regenerate the Access token & access token secret. Hit the button 'regenerate'
Once it is regenerate you can get access to the api trough twurl in your terminal: $ twurl -H "ads-api.twitter.com" "/5/accounts". Please note that today (May-2019) I am using number 5 in "/5/accounts". You must to check your version at your date.
Now you can get access to the Twitter Ads API trough curl in php also.
Create a class TwitterAPIExchangeService (I am in Laravel 5.8). You can get the class in this post.
Use the follow code with your keys:
$settings = array(
'oauth_access_token' => env('TWITTER_ACCESS_TOKEN'),
'oauth_access_token_secret' => env('TWITTER_ACCESS_TOKEN_SECRET'),
'consumer_key' => env('TWITTER_CONSUMER_KEY'),
'consumer_secret' => env('TWITTER_CONSUMER_SECRET'),
);
//Regular Twitter API
$url = 'https://api.twitter.com/1.1/followers/ids.json';
$getfield = '?screen_name=J7mbo';
//Ads Twitter API
//$url = 'https://ads-api.twitter.com/5/accounts';
//$getfield = '';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchangeService($settings);
$data = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
dd($data);
Need to regenerate keys and tokens. after that its work for me

How to identify the current user when redirected from an auth0 rule

My authentication flow is as follows...
User visits my site and clicks login.
They are redirected to mydomain.auth0.com (or something like that), where they are prompted to login using either a username or password or a social provider e.g. Google.
Following the user's login, I run a custom rule in Auth0 to detect if they are a new user. If yes I now want to redirect them to a custom page to collect some additional data. I do this my implementing the following in the rule:
function (user, context, callback) {
context.redirect = {
url: 'http://www.example.com/profile'
};
callback(null, user, context);
}
This redirects the user back to my site adding a ?state=xyz... to the query string.
However, at this point I don't have a token or id token and seemingly no way to identify the user.
The example given at Auth0 talks about using this flow to force a user to update their password on login. However, for this to work there has to be some way to identify the user on the page they are redirected to.
What is the best way to get this working?
Here is a snippet from a Rule that redirects users to a post authentication registration page. Just pasting the section related to altering context.redirect since that is what you are asking about.
var hasPostRegistered = user.app_metadata && user.app_metadata.has_post_registered;
// redirect to consent form if user has not yet consented
if (!hasPostRegistered && context.protocol !== 'redirect-callback') {
var auth0Domain = auth0.baseUrl.match(/([^:]*:\/\/)?([^\/]+\.[^\/]+)/)[2];
var userId = user.user_id;
context.redirect = {
url: configuration.REGISTRATION_FORM_URL +
(configuration.REGISTRATION_FORM_URL.indexOf('?') === -1 ? '?' : '&') +
'auth0_domain=' + encodeURIComponent(auth0Domain) +
'&user_id=' + encodeURIComponent(userId)
};
}
Notice how the user_id is tagged on as a query param.
Note also, you can self-sign a JWT token inside a Rule, and send that to your redirect endpoint, which in turn can be configured to read / verify that JWT Token as a way to secure the redirection.

Disqus - How to pass current logged in user?

I am using Disqus API to fetch details of the logged in user. I am not sure how to pass the current logged in user.
I have both api_key(public) and remote_auth and I am using Jquery ajax to send api request over http.
If I do something like this,
https://disqus.com/api/3.0/users/details.json?api_key=[apikey]
It says "You must either provide a user or authenticate the user." Now I have the loggedin users remote_auth.
FYI: This is how I am creating the remote_auth. Example User Id: 3096795, email = "a#a.com", Name="Test". Now when this user logs in to the website, it logs in to Disqus as well. I can see this user in http://disqus.com/api/sso/users/ with id = 3096795.
I have couple of questions:
1) Can I use jquery ajax to send a authenticated user and get user details? Or this can be done only via Server side? (Java/Php)
2) If I pass ?remote_auth=[remote_auth] as a query string, will it work?
3) if yes, remote_auth value has spaces in between HMAC->SHA1(secret_key, message + ' ' + timestamp) so how can I pass it as query string parameter?
4) If no, then how to pass a user to the listActivity.json endpoint? If I am passing the userid, then it returns me some other user and not the user I created.
The below request returns a different user.
https://disqus.com/api/3.0/users/details.json?api_key=[apikey]&user=3096795
How can I ensure the userid I am passing is unique and not already taken by a different disqus account?
Am I missing something?
Your remote_auth is a form of authentication, just like access_token, so you'll want to pass that in your request as remote_auth=<YOUR_PAYLOAD>.
If you pass "user=" that ID would have to be the Disqus user ID, which isn't the same as your remote_auth ID. Your remote_auth is a form of authentication, just like the access_token. However, keep in mind that we don't return as many details for SSO users as authenticated Disqus users. This is because the details are managed by you, the SSO site owner.
To answer your other questions:
You can use the client-side API to get these details, but we recommend the server-side API + caching the results to avoid bumping into API limits.
URL-encode the payload and this will work
Easier using https://github.com/anthavio/disquo
DisqusApplicationKeys keys = new DisqusApplicationKeys("...api_key...", "...secret_key...", "...access_token...");
DisqusApi disqus = new DisqusApi(keys);
//SSO is available only to premium accounts
SsoAuthData ssoauth = new SsoAuthData("custom-12345-id", "Firstname", "Surname");
//SSO User identity is used to create post
disqus.posts().create(ssoauth, keys.getApiSecret(), threadId, "Hello world " + new Date(), null);

How to get useID/Email of logged in user in Google Contacts API after OauTh Token

I developed a program which works well and I can import data from gmail but. I want to keep track how is the user given permission to manage contacts. But after a hard search I did not get any Idea about the loged in user. My code is as follows.
============================================
var parameters = new OAuth2Parameters
{
ClientId = ConfigurationManager.AppSettings["ClientID"].ToString(),
ClientSecret = ConfigurationManager.AppSettings["ClientSecret"].ToString(),
RedirectUri = ConfigurationManager.AppSettings["RedirectURL"].ToString(),
Scope ="https://www.googleapis.com/auth/userinfo.profile"
};
parameters.AccessCode = Request.QueryString["Code"].ToString();
OAuthUtil.GetAccessToken(parameters);
Session["Token"] = parameters.AccessToken;
==================================
But I dont how to get email of logged in user. Please let me that
Thanks in advance
Request an additionall scope of https://www.googleapis.com/auth/userinfo.email and then you can access the user info as well. There is also a userinfo.profile witch contains other info on the user like name, profile picture, language and so on.
Your code looks like C# but I only have a Python example of using multiple scopes and sharing tokens.
Code: https://code.google.com/p/google-api-oauth-demo/
Article: http://www.hackviking.com/2013/10/python-get-user-info-after-oauth/