Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def send_mail_message(subject, content):
this_dir = Path(__file__).parent
store = file.Storage("credentials.json")
credentials = store.get()
if not credentials or credentials.invalid:
client_secret_json = json.loads((this_dir / "client_secret.json").read_text())
client_secret_json["installed"]["client_secret"] = os.environ["TOX_DEV_GOOGLE_SECRET"]
with tempfile.NamedTemporaryFile(mode="w+t") as temp_filename:
json.dump(client_secret_json, temp_filename)
temp_filename.flush()
flow = client.flow_from_clientsecrets(
filename=temp_filename.name, scope="https://www.googleapis.com/auth/gmail.send"
)
credentials = tools.run_flow(flow, store)
service = discovery.build("gmail", "v1", http=credentials.authorize(httplib2.Http()))
message = MIMEMultipart("alternative")
message["Subject"] = subject
message["From"] = "toxdevorg@gmail.com"
recipients = ["testing-in-python@lists.idyll.org", "tox-dev@python.org"]
message["To"] = ", ".join(recipients)
message.attach(MIMEText(content, "plain"))
raw_message_no_attachment = base64.urlsafe_b64encode(message.as_bytes())
raw_message_no_attachment = raw_message_no_attachment.decode()
body = {"raw": raw_message_no_attachment}
message_sent = service.users().messages().send(userId="me", body=body).execute()
message_id = message_sent["id"]
print(f"\tMessage sent with id: {message_id}")
def get_http_client():
"""Uses project credentials in CLIENT_ID_FILE along with requested OAuth2
scopes for authorization, and caches API tokens in TOKEN_STORE_FILE.
"""
store = file.Storage(TOKEN_STORE_FILE)
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets(CLIENT_ID_FILE, SCOPES)
creds = tools.run_flow(flow, store)
return creds.authorize(Http())
credential_dir = os.path.join(os.getcwd(), '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'gmail-quickstart.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
flags = argparse.Namespace(auth_host_name='localhost',
auth_host_port=[8080, 8090],
logging_level='ERROR',
noauth_local_webserver=False)
credentials = tools.run_flow(flow, store, flags)
print 'Storing credentials to ' + credential_path
return credentials
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir, 'sheets.googleapis.com-python-quickstart.json')
store = 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
credentials = tools.run_flow(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def get_authenticated_service(args):
flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=YOUTUBE_READ_WRITE_SSL_SCOPE,
message=MISSING_CLIENT_SECRETS_MESSAGE)
storage = Storage("%s-oauth2.json" % sys.argv[0])
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = run_flow(flow, storage, args)
# Trusted testers can download this discovery document from the developers page
# and it should be in the same directory with the code.
with open("youtube-v3-api-captions.json", "r", encoding="utf8") as f:
doc = f.read()
return build_from_document(doc, http=credentials.authorize(httplib2.Http()))
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
with self.AUTHENTICATION_LOCK:
log.info('Starting authentication for %s', self.target)
store = oauth2client.file.Storage(self.credentials_path)
credentials = store.get()
if not credentials or credentials.invalid:
log.info("No valid login. Starting OAUTH flow.")
flow = oauth2client.client.flow_from_clientsecrets(self.client_secret_path, self.SCOPES)
flow.user_agent = self.APPLICATION_NAME
flags = oauth2client.tools.argparser.parse_args([])
credentials = oauth2client.tools.run_flow(flow, store, flags)
log.info('Storing credentials to %r', self.credentials_path)
return credentials
def __init__(self, flags):
self.__flags = flags
# Perform OAuth 2.0 authorization.
project_dir = os.path.join(
os.getenv('HOME'), 'cloud', 'projects', flags.project)
client_secrets = os.path.join(project_dir, 'client_secrets.json')
oauth2_storage = os.path.join(project_dir, 'oauth2.dat')
flow = flow_from_clientsecrets(client_secrets, scope=GCE_SCOPE)
storage = Storage(oauth2_storage)
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = run_flow(flow, storage, flags)
self.http = credentials.authorize(httplib2.Http())
self.compute = build('compute', API_VERSION)
Credentials, the obtained credential.
"""
global descAgent
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
print "checking for cached credentials"
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,'mycroft-googlecalendar-skill.json')
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
descAgent = ""
if not credentials or credentials.invalid:
credentials = tools.run_flow(OAuth2WebServerFlow(client_id=CID,client_secret=CIS,scope=SCOPES,user_agent=APPLICATION_NAME),store)
else:
logger.info('Loaded credentials from ~ .credentials')
with open(credential_path) as credential_file:
data = json.load(credential_file)
descAgent = data['user_agent']
return credentials
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
store = Storage(CLIENT_CREDENTIALS_FILE)
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 ' + CLIENT_CREDENTIALS_FILE)
return credentials
'client_secrets.json')
# Set up a Flow object to be used if we need to authenticate.
flow = client.flow_from_clientsecrets(
client_secrets,
scope=API_SCOPES,
message=tools.message_if_missing(client_secrets))
# Prepare credentials, and authorize HTTP object with them.
# If the credentials don't exist or are invalid run through the installed
# client flow. The Storage object will ensure that if successful the good
# credentials will get written back to a file.
storage = oauthFile.Storage(CREDENTIAL_STORE_FILE)
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = tools.run_flow(flow, storage, flags)
http = credentials.authorize(http=httplib2.Http())
# Construct and return a service object via the discovery service.
return discovery.build(API_NAME, API_VERSION, http=http)