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

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/

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

Fetching Google Plus profile url and email

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.

(Google App Script) Can i give access to other users to my private Spreadsheet with oAuth?

i need help for my application "Google App Script".
I am the owner of a Spreadsheet that I use as a DB in my application; this spreadsheet must remain private.
My application is executed as Gadget in Google Site, in this application a user runs the script as himself (not under the owner's identity).
I need that all users who access the application can get some data from the DB Spreadsheet.
How can users get this data, if the Spreadsheet is only accessible to me?
Can I use oAuth?
Sorry for the bad English
Following Zig answer and to illustrate, here is an example of such a contentService webapp, one can call it with this url either in a browser or in urlFetch
The app is deployed as follows : execute as me and anyone can access even anonymous
https://script.google.com/macros/s/AKfycbxfk5YR-JIlhv7HG9R7F-cPxmL0NZRzrdGF4VFGxGivBkYeZY4/exec?&user=chris&row=4&sheet=Sheet1
and here is the demo script
function doGet(e) {
if(e.parameter.user!='serge' && e.parameter.user!='chris' ){return ContentService.createTextOutput("logging error, you are not allowed to see this").setMimeType(ContentService.MimeType.TEXT)};
var sheet = e.parameter.sheet;
var row = Number(e.parameter.row);
Logger.log(sheet+' '+row);
var ss = SpreadsheetApp.openById("0AnqSFd3iikE3dENnemR2LVFMTFM5bDczNGhfSG11LVE");// this sheet is private but anyone can call this app
var sh = ss.getSheetByName(sheet);
var range = sh.getRange(row,1,1,sh.getLastColumn());
var val = Utilities.jsonStringify(range.getValues());
var result = ContentService.createTextOutput(val).setMimeType(ContentService.MimeType.JSON);
return result;
}
No you cant use oauth from the gadget as the user doesnt have read permission.
However you can publish a second script to extract needed data that runs as you with anonymous public access and call that one with urlfetch from the 1st. Slower thou.

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);

Verify user through PayPal GetVerifiedStatus API

I have been trying to get this GetVerifiedStatus API to work but it just doesn't work.
I have tried using a valid email address on
http://www.dev-tool.com/pptester/NVP/CallType.aspx?ServiceID=51&CallTypeID=53
As well as directly and through curl but they all give error of 'Api credentials are incorrect'.
Does anyone know how to do it?
Then I have another question, paypal says that GetVerifiedStatus API takes in email,first name and last name. (as mentioned in )
However there is this guy who says that he verified using email, password and signature successfully... anybody has any idea where do password and signature comes in it from?
Thanks
The link you're referring to is talking about an API username, password and signature.
To use GetVerifiedStatus, you must send email, firstName, lastName and matchCriteria.
See also page 63 of https://www.paypal-biz.com/development/documentation/PP_AdaptiveAccounts.pdf
To use GetVerifiedStatus.php here is what you have to do:
Create an account paypal sandboc
Create a preconfigured account
Click on API and Payment Card Credentials to view your account credentials
Update the following code with the credentials you got from step 3
//PayPal API Credentials
$API_UserName = "sbapi_1287090601_biz_api1.paypal.com"; //TODO
$API_Password = "1287090610"; //TODO
$API_Signature = "ANFgtzcGWolmjcm5vfrf07xVQ6B9AsoDvVryVxEQqezY85hChCfdBMvY"; //TODO
//PAYPAL SANDBOX LOGIN EMAIL
$API_SANDBOX_EMAIL_ADDRESS = "rishaque#paypal.com"; <<<<< THIS IS YOUR LOGIN EMAIL ADDRESS
I hope this help.