Accessing google domain users email data with XOAUTH2 - ruby-on-rails

I'm trying to access our students gmail data from our google apps for domains with xoauth2.
I've been around the block with this one, googles documentation is very poorly organised, and there is still alot of old docs that don't work any more that you are directed to, so it's been alot of fun.
I've basically got the following code to work using googles oauth2client in python using a service account that I created that has domain delegation enabled.
from oauth2client.client import SignedJwtAssertionCredentials
client_email = 'serviceaccount#developer.gserviceaccount.com'
with open("testserviceaccount.p12") as f:
private_key = f.read()
credentials = SignedJwtAssertionCredentials(client_email, private_key,
'https://www.googleapis.com/auth/gmail.readonly', sub='student email address')
from httplib2 import Http
http_auth = credentials.authorize(Http())
from apiclient.discovery import build
service = build('gmail', 'v1', http=http_auth )
messages = service.users().messages().list(userId='student email address').execute()
print messages
The app I need this to work in is in ruby on rails however, so I'm looking for any tips or help on what to use in Ruby on Rails to achieve the same effect.
Any help or tips greatly appreciated.

Related

Use Tweepy to extract Twitter follower information (API incompatibility issues)?

I was following this tutorial, https://towardsdatascience.com/how-to-download-twitter-friends-or-followers-for-free-b9d5ac23812, which was written in 2021. It should've worked fine, however, they have to 'fix' the things that just work.
Specifically, running this line
for fid in Cursor(api.followers_ids, screen_name=screen_name, count=5000).items():
ids.append(fid)
gives the error:
"tweepy.error.TweepError: [{'message': 'You currently have Essential access which includes access to Twitter API v2 endpoints only. If you need access to this endpoint, you’ll need to apply for Elevated access via the Developer Portal. You can learn more here: https://developer.twitter.com/en/docs/twitter-api/getting-started/about-twitter-api#v2-access-leve', 'code': 453}]"
I could have pulled the data in five minutes. Now debugging this already cost one hour+ because they just break the things that work. Is there anyway to make this old code snippet work? The application to use API 1.1 takes weeks, and I don't have time to watch their bad documents of how to migrate from API 1.1 to 2.0 and then the documents of migrating from Tweepy 3.9.0 to 4.0.0. Five minutes' task would just become half a day. Thanks in advance for any help.
First of all, have you at least tried to apply for the Elevated access?
It can take some time, it's true, but it can also be instantaneous.
The other solution would be to use the Twitter API V2.
You don't need any tutorial, just read the documentation:
Here for the authentication ;
Here for the retrieval of the followers ;
Here for the pagination.
And you should get something like that:
import tweepy
client = tweepy.Client("Bearer Token here")
paginator = tweepy.Paginator(
client.get_users_followers,
id=..., # ID only, no screename
max_results=1000
).flatten()
for follower in paginator:
print(follower.id)
Finally, even if I understand your frustration (and developing Twitter applications can be very frustrating), I think that you should try to keep it out your SO questions. Good luck!

How to connect to JIRA api with 2fa enabled by organization?

I use self hosted Jira and I'm currently trying to connect to the Jira api using a python script (and the requests library) having 2fa enabled by my organization. I'm not an admin of the project and after creating a personal access token and using it as a Bearer token I only got so far to get a response from the server telling me to put in the OTP to proceed.
I was thinking whether I could possibly pass the OTP as part of the authorization header when making the request to the api but couldn't find any useful hints on how to do that. I have also been looking into OAuth tokens but from my understanding I'm unable to create one since I don't have the option to create an application link within Jira (since I'm not an admin).
Does anyone have an idea on how I could manage to establish the connection to the api?
Any help would be appreciated!!
Cheers,
Liz
Hey #Liz try this project for inspiration - https://github.com/dren79/JiraScripting_public
I built it out on the below examples from the API documentation.
#This code sample uses the 'requests' library:
#http://docs.python-requests.org
import requests
from requests.auth import HTTPBasicAuth
import json
url = "https://your-domain.atlassian.net/rest/api/3/issue/{issueIdOrKey}"
auth = HTTPBasicAuth("email#example.com", "<api_token>")
headers = {
"Accept": "application/json"
}
response = requests.request(
"GET",
url,
headers=headers,
auth=auth
)
print(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ")))

How to make a a google sheets spreadsheet available to gspread

I'm working through the documentation to gspread (http://gspread.readthedocs.io/en/latest/oauth2.html ), and have been able to get the introductory code block working:
import gspread
gc = gspread.authorize(credentials)
However when I run the following script :
import gspread
from oauth2client.service_account import ServiceAccountCredentials
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('My Project-******97.json', scope)
gc = gspread.authorize(credentials)
wks = gc.open("rules_test_1.csv").sheet1
I get:
gspread.exceptions.SpreadsheetNotFound
How can I get access to this sheet?
OK, you're making a common mistake. If you search for "service account [google-drive-sdk]" in StackOverflow, you'll find many people asking the same question.
Basically a Service Account IS NOT your Google account, which is why your file isn't found. The authors of gspread should have explained that in their example code. You have two options:-
Share your spreadsheet, or the folder it's in, with the Service Account user. This is the easiest approach since all you need to do is make the share from GDrive and then your existing code will work. The downside is it can be clunky to keep sharing files. My suggestion would be to make a dedicated folder called say "shared with my service account" and make all files children of that folder. Remember that files can have multiple parents, so you can still preserve your folder structure. See the answer to How do I search sub-folders and sub-sub-folders in Google Drive? for a refresher on how Drive folders work.
Replace the Service Account auth with Standard Account auth. This requires some minor changes to your code. The result will be that your app is talking directly to your Drive Account, without having a Service Account acting as a proxy. Thus it's more elegant provided the security implications are acceptable. You will be using a stored Refresh Token. Some information on how to do this is at How do I authorise an app (web or installed) without user intervention? (canonical ?)
Neither way is right or wrong. It depends on your specific requirements.

gspread/OAuth2: authenticated default gmail account (used early in ClientLogin)

I have been using gspread (authenticated via ClientLogin) for a last year. Now I would like to use OAuth2. I've followed tutorial from gspread site: http://gspread.readthedocs.org/en/latest/oauth2.html
The problem is that this method creates new "Email address" (in console.developers.google) which doesn't have an access to spreadsheets - all spreadsheets should be shared again. This is really difficult if you have 1000+ spreadsheets.
The question is: how to authenticated with OAuth2 my default gmail account (that I've been using to access via ClientLogin)?
Thank you!
EDIT:
I've followed this tutorial: http://www.indjango.com/access-google-sheets-in-python-using-gspread/
But I modified code from point 1.2: http://www.indjango.com/access-google-sheets-in-python-using-gspread/#comment-2026863410
Result - some spreadsheets are available, some not and I have no idea why (same entries in access list)...
It seems that code from EDIT works. Thus, this is working solution:
I've followed this tutorial: http://www.indjango.com/access-google-sheets-in-python-using-gspread/
But I modified code from point 1.2: http://www.indjango.com/access-google-sheets-in-python-using-gspread/#comment-2026863410
The only problem is that Google Sheets API returns only 500 results (thus, if using gspread when you have more spreadsheets that are not among results -> gspread raises SpreadsheetNotFound).

How can I download all the emails from gmail acount to my local machine

I am newbie on ruby on rails and gems...If any one help me to figure out that any gems or script that downloads all the emails from gmail to my local machine
I heard about ruby 'net/imap'
but using it I am not able to fetch or authenticate
imap = Net::IMAP.new('mail.google.com')
imap.authenticate('LOGIN', 'bmonal125', 'aaaa')
Please suggest me ...
I need any kind of technical suggestion to overcome it
Thanks in advance
Have a look at http://rubydoc.info/gems/gmail, there are detailed examples on how to authenticate and retrieve messages.
If the authentication does not work, it is quite possible that your IMAP access is not configured in gmail. Have a look at support.google.com/mail/troubleshooter/1668960?hl=en#ts=1665018 on how to enable it

Resources