Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
"""A simple commandline client around the GMail OAuth API."""
# pip install --user --upgrade google-api-python-client oauth2client
from oauth2client import client
from oauth2client import file
from oauth2client import tools
# You have to Create a project on https://console.developers.google.com/,
# create OAuth client ID credentials, download them and put them in
# client_id.json.
clientsecrets = 'client_id.json'
flow = client.flow_from_clientsecrets(clientsecrets,
scope='https://www.googleapis.com/auth/gmail.send',
message=tools.message_if_missing(clientsecrets))
storage = file.Storage('mail.dat')
creds = storage.get()
if creds is None or creds.invalid:
#args = tools.argparser.parse_args(['--noauth_local_webserver'])
args = tools.argparser.parse_args()
creds = tools.run_flow(flow, storage, args)
from googleapiclient.discovery import build
service = build('gmail', 'v1', credentials=creds)
# https://developers.google.com/gmail/api/guides/sending
import base64
from email.mime.text import MIMEText
import argparse
import sys
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--subject')
def main(argv):
# Let the gflags module process the command-line arguments
try:
argv = FLAGS(argv)
except gflags.FlagsError, e:
print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
sys.exit(1)
# Set the logging according to the command-line flag
logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
# If the Credentials don't exist or are invalid run through the native client
# flow. The Storage object will ensure that if successful the good
# Credentials will get written back to a file.
storage = Storage('plus.dat')
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = run(FLOW, storage)
# Create an httplib2.Http object to handle our HTTP requests and authorize it
# with our good Credentials.
http = httplib2.Http()
http = credentials.authorize(http)
service = build('moderator', 'v1', http=http)
try:
# Create a new Moderator series.
series_body = {
def get_service():
"""
Handle oauth's shit (copy-pasta from
http://code.google.com/apis/tasks/v1/using.html)
Yes I do publish a secret key here, apparently it is normal
http://stackoverflow.com/questions/7274554/why-google-native-oauth2-flow-require-client-secret
"""
FLAGS = gflags.FLAGS
FLOW = OAuth2WebServerFlow(
client_id='617841371351.apps.googleusercontent.com',
client_secret='_HVmphe0rqwxqSR8523M6g_g',
scope='https://www.googleapis.com/auth/tasks',
user_agent='michel/0.0.1')
FLAGS.auth_local_webserver = False
storage = Storage(os.path.join(save_data_path("michel"), "oauth.dat"))
credentials = storage.get()
if credentials is None or credentials.invalid == True:
credentials = run(FLOW, storage)
http = httplib2.Http()
http = credentials.authorize(http)
return build(serviceName='tasks', version='v1', http=http)
def test_get_service(scope, service, secret=None):
CLIENT_SECRETS_FILE = get_secrets(PREFIXES, SUFFIXES) if not secret else secret
if not CLIENT_SECRETS_FILE:
return None
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, scopes=scope)
storage = Storage(os.path.join(consts.root, f".{consts.abbrv}-oauth2-{service}.json"))
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = flow.run_local_server(host='localhost',
port=8080,
authorization_prompt_message='Please visit this URL: {url}',
success_message='The auth flow is complete; you may close this window.',
open_browser=True)
storage.put(credentials)
return credentials
def GetApi(self):
"""Does OAuth2 authorization and prepares Google Compute Engine API.
Since access keys may expire at any moment, call the function every time
making API call.
Returns:
Google Client API object for Google Compute Engine.
"""
# First, check local file for credentials.
homedir = os.environ['HOME']
storage = oauth2client.file.Storage(
os.path.join(homedir, '.%s.credentials' % self._name))
credentials = storage.get()
if not credentials or credentials.invalid:
# If local credentials are not valid, do OAuth2 dance.
flow = oauth2client.client.OAuth2WebServerFlow(
self._client_id, self._client_secret, self.COMPUTE_ENGINE_SCOPE)
credentials = oauth2client.tools.run(flow, storage)
# Set up http with the credentials.
authorized_http = credentials.authorize(httplib2.Http())
return apiclient.discovery.build(
'compute', self.COMPUTE_ENGINE_API_VERSION, http=authorized_http)
def auth():
"""Authenticate with Google. Must be done prior to any other commands."""
# Some of these imports take quite a while, so don't do them if the user
# asks for --help or somesuch.
import httplib2
import oauth2client.file
import oauth2client.client
import oauth2client.tools
import googleapiclient.discovery
storage = oauth2client.file.Storage("credentials.dat")
credentials = storage.get()
if not credentials or credentials.invalid:
# HACK: Use the run_flow function to save some trouble, but don't
# actually pass it any of the args from the command line. TODO: Use
# our own code here instead.
flow = oauth2client.client.OAuth2WebServerFlow(client_id=CLIENT_ID,client_secret=CLIENT_SECRET,
scope='https://www.googleapis.com/auth/calendar' + '.readonly' * READ_ONLY, # Don't normally need any read/write access
user_agent='Let Me Know')
import argparse
flags=argparse.Namespace(auth_host_name='localhost', auth_host_port=[8080, 8090], logging_level='ERROR', noauth_local_webserver=False)
credentials = oauth2client.tools.run_flow(flow, storage, flags)
# At this point, we should have viable credentials.
global service
service = googleapiclient.discovery.build("calendar", "v3", http=credentials.authorize(http=httplib2.Http()))
# the Web Server Flow, but it can also handle the flow for native
# applications
# The client_id and client_secret can be found in Google Developers Console
FLOW = OAuth2WebServerFlow(
client_id='',
client_secret='',
scope='https://www.googleapis.com/auth/calendar',
user_agent='Alfred Gcal/0.1')
# To disable the local server feature, uncomment the following line:
# FLAGS.auth_local_webserver = False
# If the Credentials don't exist or are invalid, run through the native client
# flow. The Storage object will ensure that if successful the good
# Credentials will get written back to a file.
storage = Storage('calendar.dat')
credentials = storage.get()
if credentials is None or credentials.invalid == True:
credentials = run(FLOW, storage)
# Create an httplib2.Http object to handle our HTTP requests and authorize it
# with our good Credentials.
http = httplib2.Http()
http = credentials.authorize(http)
# Build a service object for interacting with the API. Visit
# the Google Developers Console
# to get a developerKey for your own application.
service = build(serviceName='calendar', version='v3', http=http,
developerKey='')
def GetCredentials():
with warnings.catch_warnings():
warnings.simplefilter('ignore')
CredentialStore = Storage(S.CredentialFilePath)
Credentials = CredentialStore.get()
if not Credentials or Credentials.invalid:
AuthenticationFlow = client.flow_from_clientsecrets(S.CalendarClientSecretFile, S.CalendarScope)
AuthenticationFlow.user_agent = S.ApplicationName
Credentials = tools.run_flow(AuthenticationFlow, CredentialStore, Flags)
return Credentials
def get_credentials():
# taken from https://developers.google.com/google-apps/calendar/quickstart/python
global credentials
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
print('Creating', credential_dir)
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir, 'pi_remind.json')
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to', credential_path)
return credentials
from googleapiclient import discovery
from tinydb import TinyDB
from core.utility import get_gcloud_creds
from core.insert_entity import insert_entity
db = TinyDB('entities.json')
from oauth2client.file import Storage
storage = Storage('creds.data')
service = discovery.build('pubsub', 'v1', credentials=get_gcloud_creds())
request = service.projects().topics().list(project="projects/goat-sounds")
request = service.projects().subscriptions().list(project="projects/goat-sounds")
request = service.projects().subscriptions().getIamPolicy(resource="projects/goat-sounds/subscriptions/baaaa")
insert_entity("pubsub", ["projects", "topics"], "Topics", "v1", {"project": "projects/" + projectId}, "topics")
insert_entity("pubsub", "subscriptions", "Pub/Sub", "v1", {"project": "projects/" + projectId}, "subscriptions")