Google+ Domain API HTTP Error 500 calling activities.insert - google-plus

I'm getting an HTTP 500 error when trying to run the sample code (python) for inserting an activity on behalf of a user. I've set up domain wide delegation and have included all the correct scopes. I've successfully run with domain delegation for creating circles, adding people to circles, reading posts, comments and profiles but for some reason I cannot get the code to work for inserting a post on behalf of a user. Any ideas?
Code and error follow (private info redacted):
import httplib2
import pprint
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
SERVICE_ACCOUNT_EMAIL = 'svc-acct#developer.gserviceaccount.com'
SERVICE_ACCOUNT_PKCS12_FILE_PATH = '/path/privatekey.pem'
USER_EMAIL = 'email#domain.com'
SCOPES = ['https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/plus.stream.read',
'https://www.googleapis.com/auth/plus.stream.write',
'https://www.googleapis.com/auth/plus.circles.read',
'https://www.googleapis.com/auth/plus.circles.write',
'https://www.googleapis.com/auth/plus.profiles.read']
def authenticate():
print 'Authenticate the domain for %s' % USER_EMAIL
f = open(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key,
scope=SCOPES, sub=USER_EMAIL)
http = httplib2.Http()
http = credentials.authorize(http)
return build('plusDomains', 'v1', http=http)
def activitiesInsert(service):
user_id = 'me'
print 'Inserting activity'
result = service.activities().insert(
userId = user_id,
body = {
'object' : {
'originalContent' : 'Happy Monday! #caseofthemondays'
},
'access' : {
'items' : [{
'type' : 'domain'
}],
# Required, this does the domain restriction
'domainRestricted': True
}
}).execute()
print 'result = %s' % pprint.pformat(result)
if __name__ == '__main__':
service = authenticate()
activitiesInsert(service)
python addpost.py
Authenticate the domain for email#domain.com
Inserting activity
Traceback (most recent call last):
File "addpost.py", line 72, in
activitiesInsert(service)
File "addpost.py", line 64, in activitiesInsert
'domainRestricted': True
File "build/bdist.macosx-10.6-intel/egg/oauth2client/util.py", line 132, in
positional_wrapper
File "build/bdist.macosx-10.6-intel/egg/apiclient/http.py",
line 723, in execute
apiclient.errors.httperror
HttpError 500 when requesting https://www.googleapis.com/plusDomains/v1/people/me/activities?alt=json returned ""

Related

pushing SMIME cert to users in Google work space using Google API python

I am in a desperate need to push SMIME certs to more than 300 users in Googleworkspace.
I have tried to follow the API documentation but I am not sure what I am doing wrong, I have a deception error and when I ignore it I get 400 response that the json file is not correct.
I am using a delegated service account to be able to impersonate the users.
I can list lables within thier inbox but i cannot upload the certificate to ther sittings.
I am using the right scope not labels.
from __future__ import print_function
def main():
creds = None
SCOPES = ['https://www.googleapis.com/auth/gmail.labels']
SERVICE_ACCOUNT_FILE = 'D:\G_Mail_Certs\eproject-444444444f.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
try:
delegated_credentials = credentials.with_subject('targetuser#domain.com')
gmail_service = build('gmail', 'v1', credentials=delegated_credentials)
user_id = 'targetuser#domain.com'
smime_info = create_smime_info(cert_filename='D:\Certs\MPS2.pfx', cert_password='ABCD1234')
results = gmail_service.users().settings().sendAs().smimeInfo().\
insert(userId=user_id, sendAsEmail=send_as_email, body=smime_info)\
.execute()
except HttpError as error:
print(f'An error occurred: {error}')
return results
if __name__ == '__main__':
main()
the functionalities.py is
def create_smime_info(cert_filename, cert_password=None):
"""Create an smimeInfo resource for a certificate from file.
Args:
cert_filename: Name of the file containing the S/MIME certificate.
cert_password: Password for the certificate file, or None if the file is not
password-protected.
"""
smime_info = None
try:
with open(cert_filename, 'r') as f:
smime_info = {}
data = f.read().encode('UTF-8')
smime_info['pkcs12'] = base64.urlsafe_b64encode(data)
if cert_password and len(cert_password) > 0:
smime_info['encryptedKeyPassword'] = cert_password
except (OSError, IOError) as error:
print('An error occurred while reading the certificate file: %s' % error)
return smime_info
# [END create_smime_info]
# [START insert_smime_info]
def insert_smime_info(service, user_id, smime_info, send_as_email=None):
"""Upload an S/MIME certificate for the user.
Args:
service: Authorized GMail API service instance.
user_id: User's email address.
smime_info: The smimeInfo resource containing the user's S/MIME certificate.
send_as_email: The "send as" email address, or None if it should be the same
as user_id.
"""
if not send_as_email:
send_as_email = user_id
try:
results = service.users().settings().sendAs().smimeInfo().insert(
userId=user_id, sendAsEmail=send_as_email, body=smime_info).execute()
print('Inserted certificate; id: %s' % results['id'])
return results
except errors.HttpError as error:
print('An error occurred: %s' % error)
return None
# [END insert_smime_info]
thank you
Just in case if anyone needed it, here is what I have done..
I changed the create_smime_info function to run without encoding.
def create_smime_info(cert_filename, cert_password):
"""Create an smimeInfo resource for a certificate from file.
Args:
cert_filename: Name of the file containing the S/MIME certificate.
cert_password: Password for the certificate file, or None if the file is not
password-protected.
Returns : Smime object, including smime information
"""
smime_info = None
try:
with open(cert_filename, 'rb') as cert:
smime_info = {}
data = cert.read()
smime_info['pkcs12'] = base64.urlsafe_b64encode(data).decode()
if cert_password and len(cert_password) > 0:
smime_info['encryptedKeyPassword'] = cert_password
except (OSError, IOError) as error:
print(F'An error occurred while reading the certificate file: {error}')
smime_info = None
return smime_info
Worked fine with me and I was able to attach certs to all domain accounts.

VIPTELA SDWAN API call issue

Need your expert advise on calling a API. 
i was trying to build a script for calling a devices information in Viptela SDWAN. At my home lab script worked as expected, but moment i changed the URL to live office Vmanage hosted on AWS, it gives me error and script was not able to login. however via internet explorer i was able to login into Vmanage GUI.
below is the configuration and error msgs i was getting. any advise will be helpful.
Error's:
Traceback (most recent call last):
File "C:/Users/XXXXXXX/Desktop/New folder (2)/apicallproject.py", line 123, in <module>
my_login()
File "C:/Users/XXXXXXX/Desktop/New folder (2)/apicallproject.py", line 24, in my_login
response = session.post(url=login_url, data=login_credentials, verify=false)
NameError: name 'false' is not defined
Process finished with exit code 1
+++++++++++++++With Verification set to true++++++++++++++++++++++
Traceback (most recent call last):
File "C:/Users/XXXXXXX/Desktop/New folder (2)/apicallproject.py", line 123, in <module>
my_login()
File "C:/Users/XXXXXXXX/Desktop/New folder (2)/apicallproject.py", line 24, in my_login
response = session.post(url=login_url, data=login_credentials, verify=true)
NameError: name 'true' is not defined
Process finished with exit code 1
Below is the python script which is working fine at my home LAB:-
ur = input ("Enter the path to Vmanage :")
name = input("Please enter your user name:")
passw = input("Please enter your password:")
def my_login():
login_url = '%s/j_security_check'%ur
login_credentials = {'j_username': name, 'j_password': passw}
session = requests.session()
response = session.post(url=login_url, data=login_credentials, verify=false)
if b`'<html>'` in response.content:
print('Login Failed')
else:
print('Login Success')
Using True or False should work. Perhaps due to different python version.
I made minor changes to your code and was able to run it in DevNet Sandbox Labs at version 20.4 You can try this code below in your environment.
import requests
import sys
requests.packages.urllib3.disable_warnings()
ur = input("Enter the path to Vmanage :")
name = input("Please enter your user name:")
passw = input("Please enter your password:")
def my_login():
login_url = '%s/j_security_check' % ur
login_credentials = {'j_username': name, 'j_password': passw}
session = requests.session()
response = session.post(url = login_url, data = login_credentials, verify=False)
if b'<html>' in response.content:
print(f"Login Failed, {response.status_code}")
exit(0)
else:
print(f"Login Success, {response.status_code}")
my_login()
Enter the path to Vmanage :https://sandbox-sdwan-2.cisco.com
Please enter your user name:devnetuser
Please enter your password:RG!_Yw919_83
Login Success, 200

Is there a way to authenticate OAUTH2.0 of google API through terminal?

I am fetching google photos from my account using Google Photo API. Now there is a need for me to execute that php file via terminal, but the problem is that I can't authenticate with Google API in doing so. Is there a way to do this, and if yes, then how shall it be done?
Yes, it is possible, you need an interactive login for the first authentication but then you can save the token and refresh it automatically as required.
I have implemented this class in Python to do just that.
from requests.adapters import HTTPAdapter
from requests_oauthlib import OAuth2Session
from pathlib import Path
from urllib3.util.retry import Retry
from typing import List, Optional
from json import load, dump, JSONDecodeError
import logging
log = logging.getLogger(__name__)
# OAuth endpoints given in the Google API documentation
authorization_base_url = "https://accounts.google.com/o/oauth2/v2/auth"
token_uri = "https://www.googleapis.com/oauth2/v4/token"
class Authorize:
def __init__(
self, scope: List[str], token_file: Path,
secrets_file: Path, max_retries: int = 5
):
""" A very simple class to handle Google API authorization flow
for the requests library. Includes saving the token and automatic
token refresh.
Args:
scope: list of the scopes for which permission will be granted
token_file: full path of a file in which the user token will be
placed. After first use the previous token will also be read in from
this file
secrets_file: full path of the client secrets file obtained from
Google Api Console
"""
self.max_retries = max_retries
self.scope: List[str] = scope
self.token_file: Path = token_file
self.session = None
self.token = None
try:
with secrets_file.open('r') as stream:
all_json = load(stream)
secrets = all_json['installed']
self.client_id = secrets['client_id']
self.client_secret = secrets['client_secret']
self.redirect_uri = secrets['redirect_uris'][0]
self.token_uri = secrets['token_uri']
self.extra = {
'client_id': self.client_id,
'client_secret': self.client_secret}
except (JSONDecodeError, IOError):
print('missing or bad secrets file: {}'.format(secrets_file))
exit(1)
def load_token(self) -> Optional[str]:
try:
with self.token_file.open('r') as stream:
token = load(stream)
except (JSONDecodeError, IOError):
return None
return token
def save_token(self, token: str):
with self.token_file.open('w') as stream:
dump(token, stream)
self.token_file.chmod(0o600)
def authorize(self):
""" Initiates OAuth2 authentication and authorization flow
"""
token = self.load_token()
if token:
self.session = OAuth2Session(self.client_id, token=token,
auto_refresh_url=self.token_uri,
auto_refresh_kwargs=self.extra,
token_updater=self.save_token)
else:
self.session = OAuth2Session(self.client_id, scope=self.scope,
redirect_uri=self.redirect_uri,
auto_refresh_url=self.token_uri,
auto_refresh_kwargs=self.extra,
token_updater=self.save_token)
# Redirect user to Google for authorization
authorization_url, _ = self.session.authorization_url(
authorization_base_url,
access_type="offline",
prompt="select_account")
print('Please go here and authorize,', authorization_url)
# Get the authorization verifier code from the callback url
response_code = input('Paste the response token here:')
# Fetch the access token
self.token = self.session.fetch_token(
self.token_uri, client_secret=self.client_secret,
code=response_code)
self.save_token(self.token)
# note we want retries on POST as well, need to review this once we
# start to do methods that write to Google Photos
retries = Retry(total=self.max_retries,
backoff_factor=0.1,
status_forcelist=[500, 502, 503, 504],
method_whitelist=frozenset(['GET', 'POST']),
raise_on_status=False)
self.session.mount('https://', HTTPAdapter(max_retries=retries))

google drive files permission updation

I have a file in my google drive, How can I update the permissions for that file in python.
Since I am very new to programming, please suggest some possible solutions.
import json
import requests
FILE_ID = '###############'
access_token = '##############'
url = 'https://www.googleapis.com/drive/v2/files/'+ FILE_ID +'/permissions'
meta_data = {
"type": "user",
"emailAddress": 'user#gmail.com',
"role": "writer"
}
headers = {'Authorization': 'Bearer ' + access_token}
response = requests.post(url, headers=headers, data=json.dumps(meta_data))
This is what I tried but I am getting "permission type required" error.
I recommend following Googles quickstart then you should be able to use the following code.
from apiclient import errors
# ...
def update_permission(service, file_id, permission_id, new_role):
"""Update a permission's role.
Args:
service: Drive API service instance.
file_id: ID of the file to update permission for.
permission_id: ID of the permission to update.
new_role: The value 'owner', 'writer' or 'reader'.
Returns:
The updated permission if successful, None otherwise.
"""
try:
# First retrieve the permission from the API.
permission = service.permissions().get(
fileId=file_id, permissionId=permission_id).execute()
permission['role'] = new_role
return service.permissions().update(
fileId=file_id, permissionId=permission_id, body=permission).execute()
except errors.HttpError, error:
print 'An error occurred: %s' % error
return None

'FirebaseApplication' object has no attribute 'Authentication'

I'm using the following code to fetch data from Firebase on Raspberry pi but it shows following error. However i'm able to fetch data without authentication.
from firebase.firebase import FirebaseApplication
from firebase.firebase import FirebaseAuthentication
firebase = firebase.FirebaseApplication('https://myapp.firebaseio.com/',
authentication =None)
authentication = firebase.Authentication('secretkey',
'prateekrai266#gmail.com', extra={'id': 123})
firebase.authentication = authentication
print (authentication.extra)
user = authentication.get_user()
print (user.firebase_auth_token)
result = firebase.get('/messages', None)
it shows following error
Traceback (most recent call last):
File "/home/pi/code/dataauth.py", line 7, in authentication =
firebase.Authentication('secretkey', 'prateekrai266#gmail.com',
extra={'id': 123}) AttributeError: 'FirebaseApplication' object has no
attribute 'Authentication'
I'm able to fetch data without authentication i.e. setting rules to true, by following code
from firebase.firebase import FirebaseApplication
firebase = firebase.FirebaseApplication('https://myapp.firebaseio.com/',
None)
result = firebase.get('/messages', None)
I presume you are using python-firebase which is a bit deprecated and not updated for long time. I've tried to fix your problem, found solution for your issue, but problem with authenticating still occurs.
Code:
from firebase.firebase import FirebaseApplication
from firebase.firebase import FirebaseAuthentication
DSN = config['databaseURL'] # 'https://myapp.firebaseio.com/'
SECRET = config['userPass'] # 'secretkey'
EMAIL =config['userEmail'] # 'prateekrai266#gmail.com'
authentication = FirebaseAuthentication(SECRET,EMAIL, True, True)
firebase = FirebaseApplication(DSN, authentication)
firebase.get('/messages', None)
I would suggest to move into pyrebase which is more updated and as I've just checked works.
https://github.com/thisbejim/Pyrebase
Code that works for me:
import pyrebase
config = {
'apiKey': "YYY",
'authDomain': "XXXXXXXX.firebaseapp.com",
'databaseURL': "https://XXXXXXXX.firebaseio.com",
'projectId': "XXXXXXXX",
'storageBucket': "XXXXXXXX.appspot.com",
'messagingSenderId': "ZZZ",
}
firebase = pyrebase.initialize_app(config)
userEmail = 'youremailadresthatyouaddedtofirebasedatabaseauthenticatedusers'
userPass = 'yourpasswordsetupforthisemail'
auth = firebase.auth()
# Log the user in
user = auth.sign_in_with_email_and_password(userEmail, userPass)
# Get a reference to the database service
db = firebase.database()
# data to save
data = {
"name": "Mortimer 'Morty' Smith"
}
# Pass the user's idToken to the push method
results = db.child("test").push(data, user['idToken'])
print results
results = db.child("test").get(user['idToken'])
print results.val()