def authenticate():
global service
global http_auth
global calendar
try:
# read credentials
credentials = ServiceAccountCredentials.from_json_keyfile_name(CREDENTIAL_FILE_PATH, scopes)
# authorize and get the calendar service
http_auth = credentials.authorize(Http())
service = discovery.build('calendar', 'v3', http=http_auth)
calendar = service.calendars().get(calendarId=CALENDAR_ID).execute()
except:
logging.getLogger('BoilerLogger').error('failed to authenticate to google calendar service, will retry...')
init()
# get calendar events in a window sorted by start time
python类from_json_keyfile_name()的实例源码
def on_message(self, message, command, arguments):
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name(GOOGLE_API, scope)
gc = gspread.authorize(credentials)
sheet = gc.open_by_url(GSHEET_URL)
worksheet = sheet.get_worksheet(0)
if arguments == False:
await self.coach.forward_message(message.channel, "No command switches provided.")
elif len(arguments) == 1:
if arguments[0].upper() == "TEAMS":
teams_output = ''
teams = worksheet.col_values(1)
for name in teams:
if len(name) > 1:
if name in teams_output or name == worksheet.acell('A1').value:
print(name)
pass
else:
teams_output += "{}\n".format(name)
await self.coach.forward_message(message.channel, teams_output)
else:
await self.coach.forward_message(message.channel, 'Could not work with argument **{}**'.format(arguments[0]))
def build_service(self):
"""
Build service for connect to google fusiontables.
"""
logger.info('Build service for connect to google fusiontables server.')
try:
credentials = ServiceAccountCredentials.from_json_keyfile_name(
self.PATH_TO_KEY,
scopes=['https://www.googleapis.com/auth/fusiontables']
)
http_auth = credentials.authorize(Http())
except IOError:
raise IncorrectAccessFilePathException(
"Access key path '{0}' is incorrect.".format(
self.PATH_TO_KEY
)
)
self.SERVICE = build('fusiontables', 'v2', http=http_auth)
def get_credentials_http(self):
if not os.path.isfile(self.settings[GOOGLE_CREDENTIALS_PARAM]):
print('''Google API credentials file {} not found.
Get it on https://console.developers.google.com/start/api?id=calendar'''.format(
self.settings[GOOGLE_CREDENTIALS_PARAM]
))
return None
try:
credentials = ServiceAccountCredentials.from_json_keyfile_name(
self.settings[GOOGLE_CREDENTIALS_PARAM],
[
'https://www.googleapis.com/auth/calendar'
]
)
except Exception as e:
print('''Cannot login to Google API - check your credential file {}.
You can get new one from https://console.developers.google.com/start/api?id=calendar'''.format(
self.settings[GOOGLE_CREDENTIALS_PARAM]
))
return None
return credentials.authorize(httplib2.Http())
def populate_spreadsheet():
"""Prerequisite: database is filled"""
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('metrictool-f16ab8f08d89.json', scope)
conn = gspread.authorize(credentials)
worksheet = conn.open("Metrics").sheet1
worksheet.update_acell('A1', 'AUTHORS')
worksheet.update_acell('B1', 'TITLES')
worksheet.update_acell('C1', 'POST DATES')
worksheet.update_acell('D1', 'VIEWS')
worksheet.update_acell('E1', 'TAGS')
worksheet.update_acell('F1', 'URL')
row_index = 3 #1: header, 2: white space
for row in Post.select().order_by(-Post.post_date):
cell_list = worksheet.range('A%s:F%s' % (row_index, row_index))
cell_values = [row.author, row.title, row.post_date, row.views, row.tags, row.url]
for i in range(len(cell_values)):
cell_list[i].value = cell_values[i]
row_index += 1
worksheet.update_cells(cell_list)
def Service_Account_Credential():
"""
Utilizes the Service Account Credential flow to instantiate an authorized credentials
object for calling the Google API
"""
logging.debug('DEBUG: SAC_FLOW: Attemping to load settings file from %s' % settings.servicekeyfile)
keyfile = settings.servicekeyfile
logging.debug('DEBUG: SAC_FLOW: Finished loading Service Account Keyfile: using %s' % keyfile )
logging.debug('DEBUG: SAC_FLOW: Loading scopes from settings file')
scopes = settings.scopes
logging.debug('DEBUG: SAC_FLOW: Finished loading scopes from settings file')
logging.debug('DEBUG: SAC_FLOW: Initializing credential from oauth2client.service_account')
credentials = ServiceAccountCredentials.from_json_keyfile_name(keyfile,
scopes=scopes)
logging.debug('DEBUG: SAC_FLOW: Delegating credentials from settings')
delegated_credentials = credentials.create_delegated(settings.delegated_email)
logging.debug('DEBUG: SAC_FLOW:Initializing authorized, delegated credentials object')
http = delegated_credentials.authorize(httplib2.Http())
return http
def _googleauth(key_file=None, scopes=[], user_agent=None):
"""
Google http_auth helper.
If key_file is not specified, default credentials will be used.
If scopes is specified (and key_file), will be used instead of DEFAULT_SCOPES
:param key_file: path to key file to use. Default is None
:type key_file: ``str``
:param scopes: scopes to set. Default is DEFAUL_SCOPES
:type scopes: ``list``
:param user_agent: User Agent string to use in requests. Default is None.
:type http_auth: ``str`` or None
:return: HTTPLib2 authorized client.
:rtype: :class: `HTTPLib2`
"""
if key_file:
if not scopes:
scopes = DEFAULT_SCOPES
creds = ServiceAccountCredentials.from_json_keyfile_name(key_file,
scopes=scopes)
else:
creds = GoogleCredentials.get_application_default()
http = Http()
if user_agent:
http = set_user_agent(http, user_agent)
http_auth = creds.authorize(http)
return http_auth
def generate_jwt(args):
"""Generates a signed JSON Web Token using a service account. Based on https://cloud.google.com/endpoints/docs/service-to-service-auth"""
# Make sure the service account has "Service Account Token Creator" permissions in Google IAM
credentials = ServiceAccountCredentials.from_json_keyfile_name(
args.service_account_file).create_scoped(['https://www.googleapis.com/auth/cloud-platform'])
service = googleapiclient.discovery.build(
serviceName='iam', version='v1', credentials=credentials)
now = int(time.time())
header_json = json.dumps({
"typ": "JWT",
"alg": "RS256"})
payload_json = json.dumps({
'iat': now,
"exp": now + 3600,
'iss': args.issuer if args.issuer else credentials.service_account_email,
"target_audience": 'https://' + args.aud,
"aud": "https://www.googleapis.com/oauth2/v4/token"
})
header_and_payload = '{}.{}'.format(
base64.urlsafe_b64encode(header_json),
base64.urlsafe_b64encode(payload_json))
slist = service.projects().serviceAccounts().signBlob(
name="projects/-/serviceAccounts/" + credentials.service_account_email,
body={'bytesToSign': base64.b64encode(header_and_payload)})
res = slist.execute()
signature = base64.urlsafe_b64encode(
base64.decodestring(res['signature']))
signed_jwt = '{}.{}'.format(header_and_payload, signature)
return signed_jwt
def main(args):
"""Generates a signed JSON Web Token using a Google API Service Account."""
credentials = ServiceAccountCredentials.from_json_keyfile_name(
args.service_account_file)
now = int(time.time())
payload = {
"exp": now + credentials.MAX_TOKEN_LIFETIME_SECS,
"iat": now,
"aud": args.aud,
}
if args.email:
payload["email"] = args.email
if args.groupId:
payload["groupId"] = args.groupId
if args.issuer:
payload["iss"] = args.issuer
payload["sub"] = args.issuer
else:
payload["iss"] = credentials.service_account_email
payload["sub"] = credentials.service_account_email
signed_jwt = oauth2client.crypt.make_signed_jwt(
credentials._signer, payload, key_id=credentials._private_key_id)
return signed_jwt
def make_access_token(secret_token_json):
"""Construct an access token from service account token."""
logging.info("Constructing an access token with scope " + _GOOGLE_API_SCOPE)
credentials = ServiceAccountCredentials.from_json_keyfile_name(
secret_token_json,
scopes=[_GOOGLE_API_SCOPE])
logging.info("Service account email: " + credentials.service_account_email)
token = credentials.get_access_token().access_token
return token
def _load_via_api(sheet_id, sheet_auth_file):
credentials = ServiceAccountCredentials.from_json_keyfile_name(sheet_auth_file, ['https://spreadsheets.google.com/feeds'])
sheetapi = gspread.authorize(credentials)
worksheet = sheetapi.open_by_key(sheet_id).get_worksheet(0)
csv = worksheet.export(format='csv')
return parse_csv(csv.decode("utf-8"))
def fetch(self, **kwargs):
''' Fetches an email using the Gmail API users.messages.get()
method. It leverages the IsThisLegit service account to impersonate
the user in order to retrieve the email by message ID. This prevents
users from having to manually accept the OAuth permission dialog before
reporting phishing emails.
Expected kwargs:
userId - The userID who reported the email
messageId - The Gmail message ID to fetch
'''
userId = kwargs.get('userId')
messageId = kwargs.get('messageId')
scopes = ['https://www.googleapis.com/auth/gmail.readonly']
credentials = ServiceAccountCredentials.from_json_keyfile_name(
config['gae']['service_account_key'], scopes=scopes)
delegated_credentials = credentials.create_delegated(userId)
http_auth = delegated_credentials.authorize(Http())
service = build('gmail', 'v1', http=http_auth)
response = service.users().messages().get(
userId=userId, id=messageId, format='raw').execute()
if not response or 'raw' not in response:
raise EmailFetchError('Error fetching email: User {}, thread {}'.
format(userId, messageId))
message = base64.urlsafe_b64decode(str(response['raw']))
return message
def __init__(self, options):
scope = 'https://www.googleapis.com/auth/androidpublisher'
key = options.google_api_key
credentials = ServiceAccountCredentials.from_json_keyfile_name(
key,
scopes=[scope])
http = httplib2.Http()
http = credentials.authorize(http)
self.service = build('androidpublisher', 'v2', http=http)
self.packageName = options.package_name
self.edit_id = None
def __init__(self, account_json):
scopes = ['https://www.googleapis.com/auth/ndev.clouddns.readwrite']
credentials = ServiceAccountCredentials.from_json_keyfile_name(account_json, scopes)
self.dns = discovery.build('dns', 'v1', credentials=credentials, cache_discovery=False)
with open(account_json) as account:
self.project_id = json.load(account)['project_id']
def _get_access_token():
"""Retrieve a valid access token that can be used to authorize requests.
:return: Access token.
"""
credentials = ServiceAccountCredentials.from_json_keyfile_name(
'service-account.json', FCM_SCOPE)
access_token_info = credentials.get_access_token()
return access_token_info.access_token
# [END retrieve_access_token]
def get_worksheet(self, key, sheet):
date = datetime.date.today()
days_until_saturday = 5 - date.weekday()
next_saturday = date + datetime.timedelta(days_until_saturday)
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name(key, scope)
gc = gspread.authorize(credentials)
sheet_name = 'Guildwar %s' % next_saturday.strftime('%m-%d-%Y')
return gc.open(sheet_name)
def run(self, search):
"""Entry point for the search. Iterate over VM's records."""
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient import discovery
import glob
import json
import shutil
scopes = ['https://www.googleapis.com/auth/compute.readonly']
for filename in glob.glob(self.tmp_dir + '/*.json'):
with open(filename) as data_file:
data = json.load(data_file)
project_id = data["project_id"]
credentials = ServiceAccountCredentials.from_json_keyfile_name(
filename, scopes=scopes)
compute = discovery.build('compute', 'v1', credentials=credentials)
zones = compute.zones()
request = zones.list(project=project_id)
filter = 'name eq {}.*'.format(search)
while request is not None:
response = request.execute()
for zone in response['items']:
instances = compute.instances().list(
project=project_id, zone=zone['name'],
filter=filter).execute()
for instance in instances.get('items', []):
yield {
'Name': instance['name'],
'Zone': zone['name'],
'Project': project_id,
'Type': instance['machineType'].rsplit('/', 1)[-1]
}
request = zones.list_next(previous_request=request,
previous_response=response)
shutil.rmtree(self.tmp_dir)
def __init__(self, config):
self.api_key = config["apiKey"]
self.auth_domain = config["authDomain"]
self.database_url = config["databaseURL"]
self.storage_bucket = config["storageBucket"]
self.credentials = None
self.requests = requests.Session()
if config.get("serviceAccount"):
scopes = [
'https://www.googleapis.com/auth/firebase.database',
'https://www.googleapis.com/auth/userinfo.email',
"https://www.googleapis.com/auth/cloud-platform"
]
service_account_type = type(config["serviceAccount"])
if service_account_type is str:
self.credentials = ServiceAccountCredentials.from_json_keyfile_name(config["serviceAccount"], scopes)
if service_account_type is dict:
self.credentials = ServiceAccountCredentials.from_json_keyfile_dict(config["serviceAccount"], scopes)
if is_appengine_sandbox():
# Fix error in standard GAE environment
# is releated to https://github.com/kennethreitz/requests/issues/3187
# ProtocolError('Connection aborted.', error(13, 'Permission denied'))
adapter = appengine.AppEngineAdapter(max_retries=3)
else:
adapter = requests.adapters.HTTPAdapter(max_retries=3)
for scheme in ('http://', 'https://'):
self.requests.mount(scheme, adapter)
def __init__(self, credential_path, spreadsheet_name):
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name(credential_path, scope)
self.gc = gspread.authorize(credentials)
logging.info('Sheet service client authorized, credential path: %s' % credential_path)
self.spreadsheet = self.gc.open(spreadsheet_name)
pass
def _populate_google_calendar_http_handler(path_to_key_file: str):
"""Returns an authorized http handler instance for building the services.
It takes an path to the service account key file.
"""
credentials = ServiceAccountCredentials.from_json_keyfile_name(
path_to_key_file, scopes=API_SCOPES)
http_auth = credentials.authorize(Http())
return http_auth
def get_access_token(ga_key_filepath):
# from https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/
# Defines a method to get an access token from the credentials object.
# The access token is automatically refreshed if it has expired.
# The scope for the OAuth2 request.
SCOPE = 'https://www.googleapis.com/auth/analytics.readonly'
# Construct a credentials objects from the key data and OAuth2 scope.
_credentials = ServiceAccountCredentials.from_json_keyfile_name(
ga_key_filepath, SCOPE)
return _credentials.get_access_token().access_token
def _open_doc(url):
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name(settings.GOOGLE_SERVICE_ACCOUNT_KEYFILE_PATH, scope)
gc = gspread.authorize(credentials)
try:
return gc.open_by_url(url)
except gspread.SpreadsheetNotFound:
raise SpreadsheetNotFound
def __init__(self):
cred = ServiceAccountCredentials.from_json_keyfile_name(
self.SERVICE_SECRET_FILE,
self.scope)
http = cred.authorize(httplib2.Http())
self._client = build(self.service, self.version, http=http)
def login_open_sheet(oauth_key_file, spreadsheet):
"""Connect to Google Docs spreadsheet and return the first worksheet."""
try:
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name(oauth_key_file, scope)
gc = gspread.authorize(credentials)
worksheet = gc.open(spreadsheet).sheet1
return worksheet
except Exception as ex:
print('Unable to login and get spreadsheet. Check OAuth credentials, spreadsheet name, and make sure spreadsheet is shared to the client_email address in the OAuth .json file!')
print('Google sheet login failed with error:', ex)
sys.exit(1)
def create_google_sheet(sheetname):
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('confs/google_sheets.json', scope)
gc = gspread.authorize(credentials)
wks = gc.create(sheetname).sheet1
return wks
def get_access():
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('confs/google_sheets.json', scope)
gc = gspread.authorize(credentials)
return gc
def run(dss_url, key_file):
scopes = ['https://www.googleapis.com/auth/userinfo.email']
credentials = ServiceAccountCredentials.from_json_keyfile_name(key_file, scopes)
h = credentials.authorize(Http())
response, content = h.request(dss_url, 'GET')
print(content)
def run(dss_url, key_file):
scopes = ['https://www.googleapis.com/auth/userinfo.email']
credentials = ServiceAccountCredentials.from_json_keyfile_name(key_file, scopes)
h = credentials.authorize(Http())
response, content = h.request(dss_url, 'DELETE')
print(content)
def make_request(js, dss_url, key_file):
scopes = ['https://www.googleapis.com/auth/userinfo.email']
credentials = ServiceAccountCredentials.from_json_keyfile_name(key_file, scopes)
h = credentials.authorize(Http())
headers = {'Content-type': 'application/json'}
response, content = h.request(dss_url, 'PUT', body=json.dumps(js), headers=headers)
print(content)
def __init__(self, ldb, config = False):
super(GoogleStorage, self).__init__(ldb, config)
if not config:
# okay .. not in config (ask_config() method)
# load credentials and authenticate
self.scopes = ['https://www.googleapis.com/auth/devstorage.read_write']
self.credentials = ServiceAccountCredentials.from_json_keyfile_name(
self.ldb.sm_gs_json_creds_file,
scopes=self.scopes)
self.service = discovery.build('storage', 'v1', credentials=self.credentials)