Stormpath, how to detect if user signed in with Google account? - express

It was super easy to integrate Google login for this fine tutorial:
https://stormpath.com/blog/build-nodejs-express-stormpath-app
I have to change the profile.jade file, so that givenName and surname are not displayed, if user has logged in with Google account.
The way it is now, if the user tries to change the 2 fields, the form response with error
Oops! We encountered an unexpected error. Please contact support and explain what you were doing at the time this error occurred.
This is to be expected, as those fields must be changed in Google account.
I'm able to access for any account via JSON:
"directory":{"href":"https://api.stormpath.com/v1/directories/49bXXXG8mAtthBTyE8ymdV"},
in my server.js file
req.user.directory
and I can look that up in Stormpath Admin panel, and it is indeed the Google directory. Then I can not display the 2 fields if a user belongs to that directory.
Is there a better way?
- like getting the name of the directory rather than the path?
Any suggestions are appreciate.

Related

How to avoid script authorization prompt when G-Suite user is accessing G-Suite trusted app script?

I wrote an app script which provides a web UI for data entry into a team calendar. I published it using G-Suite super admin account and added it as Trusted App under Security/API Permissions. "Trust domain owned apps" is checked under "Internal App Settings".
When a G-Suite user in our organization tries to access the app, he sees
"The developer of ShiftSchedulingApp, admin#_our_organization_.org, needs your permission to access your data on Google."
Those brave enough to click "Review Permissions" are taken to the next message:
"ShiftSchedulingApp wants to access your Google Account. See, edit, share, and permanently delete all the calendars you can access using Google Calendar"
Of course nobody wants to risk losing all the calendars on their Google Account and this is where it ends.
How do I get rid of this misleading message? It's not Google account, it's their organization account on G-Suite. It's not all their calendars, it's the shared team calendar only. It's adding data, not permanently deleting calendars. It's published by their administrator in their G-Suite, not an unknown 3rd party.
I spent days trying to make this message go away but no luck. App must be executed as an accessing user and not as publishing user because their user ID determines what shifts they can fill on a calendar.
I'd appreciate any hints pointing me the right direction.
I experimented with variations of the two-app approach as suggested.
The app which provides the UI needs to read the calendar to display available shifts - so I can't get away from the user authorization prompt.
Another variation I tried was having one app do everything and run as me, and another do nothing but return Session.getActiveUser(). I tried calling the 2nd one from the 1st one on the client side via XMLHttpRequest. It would be ideal for my needs - but I hit CORS error as apps URL is script.google.com but it actually gets redirected to script.googleusercontent.com. There doesn't seem to be a way to set CORS in Google App Script.
Although I was not able to find a way to avoid prompting users for authorization when executing the app as accessing user, it turns out my reasons for doing that were based on a false premise.
I chose to publish app as accessing user because I thought that's the only way to get accessing user Id - which is true for non-G Suite accounts.
However, when app is published by a G Suite account, the app can get accessing user ids within the same G Suite domain even when it's set to execute as publishing user.
Thanks Niek and TheMaster for your help!
If you just need user ID, why do you ask for all those permissions?
Possible Solutions:
2 web-apps- One running as you and another as user accessing (with only profile) permission. The second one will be the actual web interface and POST necessary information to the first one with privileges. OR
Implement your own web-app Google-sign in1
Use the least permissive2 scope3

How to properly setup google analytics report api v4? [duplicate]

I'm creating an script, based on Google Analytics step-by-step guide from this page:
https://developers.google.com/analytics/resources/tutorials/hello-analytics-api
Authorization is done without problems, until it tries to access data. The return code is 403, and error message is:
User does not have any Google Analytics account
This message has no sense: my account has google analytics data, tracking multiple websites, and I can access it from web browser without problem. I've allowed Analytics API through Google APIs console, and API access is giving me right data.
I had this problem too. I fixed it by adding the email address for my service account to the Google Analytics profile I wanted it to access.
I got the email address (something like xxxxxx#developer.gserviceaccount.com) for the service account by looking under the "API Access" tab in the Google APIs console.
Then, I followed Google's instructions for adding an email address to an Analytics profile. Now everything's working as expected.
Good luck!
Just add you given email (format of 71667655853644-o653rrdkq5hthsgo0otbpojoo#developer.gserviceaccount.com)
to User Managers:
Wish it helps you
I was facing the same issue. It got resolved by adding the email id of the service account user(your account#yourwebsite-dev.iam.gserviceaccount.com), to the users in your Analytics account under-
Analytics-Home Page ->Admin(left pane) -> User Management -> add (click on plus sign on right side of the menu) -> Add new User -> Add the email id in enter email addresses.
Now, this will solve the issue.
It is mentioned in a comment above but if you add the email address under the User Management for your account, it won't work. You have to click on the User Management under the view part of the screen.
This message we get when no permission granted to client_email, in the google alalytics, client_email is you got from the JSON file. to grant permission to client_email you're using in your App, Head over to Google Analytics site and click "Admin (setting icon)"
you'll get menu list right, there click on "View User Management"
There you'll see "+" icon, and "add user",
once you click on that, you need to add client_email in the "email address field" and save it, you should be good to go!
Go to https://console.cloud.google.com/apis/credentials
Copy email address in "Service Account".
Open Google Analytics, add email above as a new user.
You will also get this error if you have never logged in with the google account youre trying to authenticate with.
I was getting the 403 error until I changed the permissions of the email account from inside Google Analytics from 'Read & Analyze' to something else, saved it, and then changed the permissions back to 'Read & Analyze' and it worked.
Just in case if that doesn't work, Try to open your JSON file which you have downloaded and Search for client_email and copy that email address and add it to the View File
Click On
Analytics-Home Page ->Admin(left pane) -> User Management -> add (click on plus sign on right side of the menu) -> Add new User -> Add the client_email address which you copied.
If that still doesn't work
Analytics-Homepage-> Admin ->Views->User Management(Click on add(+) symbol, add this ccopied client_email address and give permissions and save it.
I was hitting the 403 error. These steps got me around it. To be clear, I was trying to get Google's sample "HelloAnalytics.php" working with OAuth (sans user interaction, suitable for cron job etc).
After enabling the Analytics API, I created a new "Service Account" under APIs & Auth/Credentials; and saved the .p12 key pair. I then went into the Analytics user management console, and added that Service User's email address.
.p12 authorization using the PHP API works if I check off only "Read & Analyze" only in the permissions list. If I add "Manage Users" and/or "Edit", I get the 403. Hope this is helpful, I was grinding on this for a couple of hours...
I had this problem too, and I found that the problem was that I had asked for too many permissions. The Developer Console says to ask for both http://www.googleapis.com/auth/analytics and http://www.googleapis.com/auth/analytics.readonly permissions. This did not work when I was also using the sub claim. A sub claim instructs Google to issue an access token that operates on behalf of another user — in my case the Google account that owns the service account. I removed the analytics permission and stuck with analytics.readonly with the sub claim:
{
"iss":"123123123123123-xxxxxxxxxxxxxxxxxxxxxxxx#developer.gserviceaccount.com",
"sub":"me.example#gmail.com"
"scope":"http://www.googleapis.com/auth/analytics",
...
}
The Bearer token issued allows me to make (at least some) Google Analytics queries to profiles that are owned by completely different Google accounts, but that have been shared (read-only) with my gmail user (me.example#gmail.com).
I managed to fix this by making sure that the
client = Google::APIClient.new(:application_name => 'X',:application_version => '1')
application name variable 'X above was the ACCOUNT name on the GA dashboard, not the PROPERTY name, which in my case was the actual url of the site I want to access.
Confusing, but thankfully fixed (with no thanks to Google!)
The problem happens since we dont provide a "sub" argument. Unless we provide this, the call happens on behalf of that long service account email.
So just provide a sub argument, with an email which you already have given access in the report and things should work well!
I got the same error, since I didn't sign in the google analytics. So I had resolved it by signing in the analytics account.
Instead of using a service account, you can sidestep the need for adding a adding new user permissions (as per the top answers in this thread) by using OAuth client ID credentials.
Go to the API credentials dashboard and click "Create credentials" -> "OAuth client ID". Afterwards you should get a client ID and a client secret that you'll need to authenticate the API.
Now you can use OAuth2WebServerFlow to authenticate on a per-use basis. Here is a python3 example:
from apiclient.discovery import build
from oauth2client.client import OAuth2WebServerFlow
# TODO: Fill these in...
CLIENT_ID = ''
CLIENT_SECRET = ''
VIEW_ID = ''
flow = OAuth2WebServerFlow(
CLIENT_ID, CLIENT_SECRET,
'https://www.googleapis.com/auth/analytics.readonly',
redirect_uri='urn:ietf:wg:oauth:2.0:oob'
)
authorize_url = flow.step1_get_authorize_url()
print('Receive code from:\n%s\n' % authorize_url)
code = input('Enter code here:').strip()
credentials = flow.step2_exchange(code)
api = build('analyticsreporting', 'v4', credentials=credentials)
body={
'reportRequests': [{
'viewId': VIEW_ID,
'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
'metrics': [{'expression': 'ga:sessions'}],
'dimensions': [{'name': 'ga:country'}]
}]
}
data = api.reports().batchGet(body=body).execute()

Weibo error 20112 when attempting to access a user's post

I'm attempting to get a user's Weibo post with 2/statuses/show. I'm able to get posts made by my own account fine, but when I try to get another user's post I get the error:
{"error":"Permission Denied!","error_code":20112,"request":"/2/statuses/show.json"}
The Weibo docs say (via google translate):
20112: As the author privacy settings, you do not have permission to view this microblogging
Does this mean the author of the post needs to update their permissions to allow the developer account access?
I also encounter this issue. However, you can still access the post using its user_id and mid (in base62). For instance, you cannot get this post from the API (its id is 10031139424) but you can still see it from your webbrowser.
An alternative is to get the post from its mobile url. Then, you can get its json which is contained in the variable render_data from the body of the html.
Any posts can be setted to be unvisible but for microblogger himself or trusted groups.
So privacy settings lead to your problem.

Replace "via Graph API Explorer" label by my application name

I am quite new in Facebook application development. I was playing the all day with "how to post a message on the wall of a page?". I finally succeeded but each message got "via Graph API Explorer". I tried to find how to change it to my application name without success. I tried to see if I could force the value of application in the api command but it did not take it into account. Maybe I miss something :( If someone can help, that would be great!
I am still quite confused. Let me try to explain what I want to do: I would like to automatically publish on a page (as the page) some event that are defined on a website (in a kind of agenda). What I miss, I think, is how everything is working together on Facebook side:
1. the login process: as the application will run in a cron, this should not display a login dialog box.
2. the access token: application or page one?
3. the permissions: from my understanding, I need manage_pages (and publish_stream) but not clear how this should be set.
Thx for any clarification and maybe a clear example :o)
You need the user to authorise your own App using one of the Login flows and grant you one of the publishing Permissions -
If it says 'via Graph API Explorer' on the posts your app makes you're using the access token you retrieved when you were testing the API using the Graph API Explorer tool, not one produced by your own app
OK I think I have finally found the way to do it. I needed a page access code and not an application access code. The token must be generated outside the application as a long live one.
Get a code using:
https://www.facebook.com/dialog/oauth?client_id={app_id}&redirect_uri={my_url}&scope=manage_pages,publish_stream
app_id is your application ID
my_url is your application URL
scope is the permission you want to be granted
In the redirected URL, you will have a code parameter. Copy it.
Generate the user access code using:
https://graph.facebook.com/oauth/access_token?client_id={app_id}&redirect_uri={my_url}&client_secret={app_secret}&code={code}
app_secret is your application secret key
code is the code from step 1
You will get as output the user access token. This one is a short live one.
convert the short live to a long live user access token using:
https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id={app_id}&client_secret={app_secret}&fb_exchange_token={short live access token}
Replace the "short live access token" by the one you got on step 2
You will get as output the infinite user access token.
Get the page access token (this one will be infinite access token as
the user access token is now an infinite access token too):
https://graph.facebook.com/me/accounts?access_token={infinite user access token}
Replace the "infinite user access token" with the value you got on step 3.
This command will list all the pages you administer. The output contains the page access token you need in field "access_token". You can so use this token in any API command in your application.
The best of the best is to do all those steps via a server side program (PHP for me) as the application secret key should remain "secret".

Analytics Google API Error 403: "User does not have any Google Analytics Account"

I'm creating an script, based on Google Analytics step-by-step guide from this page:
https://developers.google.com/analytics/resources/tutorials/hello-analytics-api
Authorization is done without problems, until it tries to access data. The return code is 403, and error message is:
User does not have any Google Analytics account
This message has no sense: my account has google analytics data, tracking multiple websites, and I can access it from web browser without problem. I've allowed Analytics API through Google APIs console, and API access is giving me right data.
I had this problem too. I fixed it by adding the email address for my service account to the Google Analytics profile I wanted it to access.
I got the email address (something like xxxxxx#developer.gserviceaccount.com) for the service account by looking under the "API Access" tab in the Google APIs console.
Then, I followed Google's instructions for adding an email address to an Analytics profile. Now everything's working as expected.
Good luck!
Just add you given email (format of 71667655853644-o653rrdkq5hthsgo0otbpojoo#developer.gserviceaccount.com)
to User Managers:
Wish it helps you
I was facing the same issue. It got resolved by adding the email id of the service account user(your account#yourwebsite-dev.iam.gserviceaccount.com), to the users in your Analytics account under-
Analytics-Home Page ->Admin(left pane) -> User Management -> add (click on plus sign on right side of the menu) -> Add new User -> Add the email id in enter email addresses.
Now, this will solve the issue.
It is mentioned in a comment above but if you add the email address under the User Management for your account, it won't work. You have to click on the User Management under the view part of the screen.
This message we get when no permission granted to client_email, in the google alalytics, client_email is you got from the JSON file. to grant permission to client_email you're using in your App, Head over to Google Analytics site and click "Admin (setting icon)"
you'll get menu list right, there click on "View User Management"
There you'll see "+" icon, and "add user",
once you click on that, you need to add client_email in the "email address field" and save it, you should be good to go!
Go to https://console.cloud.google.com/apis/credentials
Copy email address in "Service Account".
Open Google Analytics, add email above as a new user.
You will also get this error if you have never logged in with the google account youre trying to authenticate with.
I was getting the 403 error until I changed the permissions of the email account from inside Google Analytics from 'Read & Analyze' to something else, saved it, and then changed the permissions back to 'Read & Analyze' and it worked.
Just in case if that doesn't work, Try to open your JSON file which you have downloaded and Search for client_email and copy that email address and add it to the View File
Click On
Analytics-Home Page ->Admin(left pane) -> User Management -> add (click on plus sign on right side of the menu) -> Add new User -> Add the client_email address which you copied.
If that still doesn't work
Analytics-Homepage-> Admin ->Views->User Management(Click on add(+) symbol, add this ccopied client_email address and give permissions and save it.
I was hitting the 403 error. These steps got me around it. To be clear, I was trying to get Google's sample "HelloAnalytics.php" working with OAuth (sans user interaction, suitable for cron job etc).
After enabling the Analytics API, I created a new "Service Account" under APIs & Auth/Credentials; and saved the .p12 key pair. I then went into the Analytics user management console, and added that Service User's email address.
.p12 authorization using the PHP API works if I check off only "Read & Analyze" only in the permissions list. If I add "Manage Users" and/or "Edit", I get the 403. Hope this is helpful, I was grinding on this for a couple of hours...
I had this problem too, and I found that the problem was that I had asked for too many permissions. The Developer Console says to ask for both http://www.googleapis.com/auth/analytics and http://www.googleapis.com/auth/analytics.readonly permissions. This did not work when I was also using the sub claim. A sub claim instructs Google to issue an access token that operates on behalf of another user — in my case the Google account that owns the service account. I removed the analytics permission and stuck with analytics.readonly with the sub claim:
{
"iss":"123123123123123-xxxxxxxxxxxxxxxxxxxxxxxx#developer.gserviceaccount.com",
"sub":"me.example#gmail.com"
"scope":"http://www.googleapis.com/auth/analytics",
...
}
The Bearer token issued allows me to make (at least some) Google Analytics queries to profiles that are owned by completely different Google accounts, but that have been shared (read-only) with my gmail user (me.example#gmail.com).
I managed to fix this by making sure that the
client = Google::APIClient.new(:application_name => 'X',:application_version => '1')
application name variable 'X above was the ACCOUNT name on the GA dashboard, not the PROPERTY name, which in my case was the actual url of the site I want to access.
Confusing, but thankfully fixed (with no thanks to Google!)
The problem happens since we dont provide a "sub" argument. Unless we provide this, the call happens on behalf of that long service account email.
So just provide a sub argument, with an email which you already have given access in the report and things should work well!
I got the same error, since I didn't sign in the google analytics. So I had resolved it by signing in the analytics account.
Instead of using a service account, you can sidestep the need for adding a adding new user permissions (as per the top answers in this thread) by using OAuth client ID credentials.
Go to the API credentials dashboard and click "Create credentials" -> "OAuth client ID". Afterwards you should get a client ID and a client secret that you'll need to authenticate the API.
Now you can use OAuth2WebServerFlow to authenticate on a per-use basis. Here is a python3 example:
from apiclient.discovery import build
from oauth2client.client import OAuth2WebServerFlow
# TODO: Fill these in...
CLIENT_ID = ''
CLIENT_SECRET = ''
VIEW_ID = ''
flow = OAuth2WebServerFlow(
CLIENT_ID, CLIENT_SECRET,
'https://www.googleapis.com/auth/analytics.readonly',
redirect_uri='urn:ietf:wg:oauth:2.0:oob'
)
authorize_url = flow.step1_get_authorize_url()
print('Receive code from:\n%s\n' % authorize_url)
code = input('Enter code here:').strip()
credentials = flow.step2_exchange(code)
api = build('analyticsreporting', 'v4', credentials=credentials)
body={
'reportRequests': [{
'viewId': VIEW_ID,
'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
'metrics': [{'expression': 'ga:sessions'}],
'dimensions': [{'name': 'ga:country'}]
}]
}
data = api.reports().batchGet(body=body).execute()