How to get all files of all users using google drive API - admin

I am a 'domain admin' for a google account and would like to:
Get all of the users in my domain and "for each" user, give another user read-access everyone's files . I can get each user, but right now I do not understand how to get each users documents.
#!/usr/bin/python
import gdata.docs
import gdata.docs.service
from gdata.apps import client
userNameAtGmailCom = 'domainAdmin#someplace.com'
password = 'mypassword'
personToShareWith = "someGuy#gmail.com"
domain = 'someplace.com'
def login(userNameAtGmailCom, password, personToShareWith, domain):
client = gdata.apps.client.AppsClient(domain=domain)
client.ssl = True
client.ClientLogin(email=userNameAtGmailCom, password=password, source='apps')
all_users = client.RetrieveAllUsers()
for user in all_users.entry:
user_name = user.login.user_name
print user_name
password = user.login.password
print password
clientDocs = gdata.docs.service.DocsService()
#password always returns 'none'
#therefore I've commented out the 'bad authentication'
#that would happen if the lines below ran
#clientDocs.ClientLogin(user_name, password)
#documents_feed = clientDocs.GetDocumentListFeed()
#for document_entry in documents_feed.entry:
#print document_entry.title.text
#scope = gdata.docs.Scope(value=personToShareWith, type='user')
#role = gdata.docs.Role(value='reader')
#acl_entry = gdata.docs.DocumentListAclEntry(scope=scope, role=role)
#created_acl_entry = client.Post(acl_entry, document_entry.GetAclLink().href, converter=gdata.docs.DocumentListAclEntryFromString)
login(userNameAtGmailCom, password, personToShareWith, domain)

You should use the Google Drive API and use service accounts to perform Google Apps domain-wide delegation of authority:
https://developers.google.com/drive/delegation

Related

Flask dance example for login with Azure AD

I am trying to implement SSO for one of my applications using flask-login and flask-dance. As a starting point I am using sample code given on Flask Dance website - https://flask-dance.readthedocs.io/en/v1.2.0/quickstarts/sqla-multiuser.html
Only change I did was - I replaced GitHub with my Azure AD credentials
Please find the code below:
import sys
from flask import Flask, redirect, url_for, flash, render_template
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm.exc import NoResultFound
from flask_dance.contrib.github import make_github_blueprint, github
from flask_dance.contrib.azure import make_azure_blueprint, azure
from flask_dance.consumer.storage.sqla import OAuthConsumerMixin, SQLAlchemyStorage
from flask_dance.consumer import oauth_authorized, oauth_error
from flask_login import (
LoginManager, UserMixin, current_user,
login_required, login_user, logout_user
)
# setup Flask application
app = Flask(__name__)
app.secret_key = "XXXXXXXXXXXXXX"
blueprint = make_azure_blueprint(
client_id="XXXXXXXXXXXXXXXXXXXXX",
client_secret="XXXXXXXXXXXXXXXXXXXXXXXX",
tenant="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
)
app.register_blueprint(blueprint, url_prefix="/login")
# setup database models
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///multi.db"
db = SQLAlchemy()
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
# Your User model can include whatever columns you want: Flask-Dance doesn't care.
# Here are a few columns you might find useful, but feel free to modify them
# as your application needs!
username = db.Column(db.String(1028), unique=True)
email = db.Column(db.String(1028), unique=True)
name = db.Column(db.String(1028))
class OAuth(OAuthConsumerMixin, db.Model):
provider_user_id = db.Column(db.String(1028), unique=True)
user_id = db.Column(db.Integer, db.ForeignKey(User.id))
user = db.relationship(User)
# setup login manager
login_manager = LoginManager()
login_manager.login_view = 'azure.login'
#login_manager.user_loader
def load_user(user_id):
#print(User.query.get(int(user_id)))
return User.query.get(int(user_id))
# setup SQLAlchemy backend
blueprint.storage = SQLAlchemyStorage(OAuth, db.session, user=current_user,user_required=False)
# create/login local user on successful OAuth login
#oauth_authorized.connect_via(blueprint)
def azure_logged_in(blueprint, token):
if not token:
#print(token)
flash("Failed to log in with azure.", category="error")
return False
resp = blueprint.session.get("/user")
if not resp.ok:
#print(resp)
msg = "Failed to fetch user info from Azure."
flash(msg, category="error")
return False
azure_info = resp.json()
azure_user_id = str(azure_info["id"])
#print(azure_user_id)
# Find this OAuth token in the database, or create it
query = OAuth.query.filter_by(
provider=blueprint.name,
provider_user_id=azure_user_id,
)
try:
oauth = query.one()
except NoResultFound:
oauth = OAuth(
provider=blueprint.name,
provider_user_id=azure_user_id,
token=token,
)
if oauth.user:
login_user(oauth.user)
flash("Successfully signed in with Azure.")
else:
# Create a new local user account for this user
user = User(
# Remember that `email` can be None, if the user declines
# to publish their email address on GitHub!
email=azure_info["email"],
name=azure_info["name"],
)
# Associate the new local user account with the OAuth token
oauth.user = user
# Save and commit our database models
db.session.add_all([user, oauth])
db.session.commit()
# Log in the new local user account
login_user(user)
flash("Successfully signed in with Azure.")
# Disable Flask-Dance's default behavior for saving the OAuth token
return False
# notify on OAuth provider error
#oauth_error.connect_via(blueprint)
def azure_error(blueprint, error, error_description=None, error_uri=None):
msg = (
"OAuth error from {name}! "
"error={error} description={description} uri={uri}"
).format(
name=blueprint.name,
error=error,
description=error_description,
uri=error_uri,
)
flash(msg, category="error")
#app.route("/logout")
#login_required
def logout():
logout_user()
flash("You have logged out")
return redirect(url_for("index"))
#app.route("/")
def index():
return render_template("home.html")
# hook up extensions to app
db.init_app(app)
login_manager.init_app(app)
if __name__ == "__main__":
if "--setup" in sys.argv:
with app.app_context():
db.create_all()
db.session.commit()
print("Database tables created")
else:
app.run(debug=True,port=5011)
I have also done appropriate changes in HTML file for 'azure.login'.
So after running it as python multi.py --setup database tables are getting created
and after I run python multi.py Oauth dance is actually starting but in the end I am getting error like below:
HTTP Response:
127.0.0.1 - - [28/Oct/2020 10:17:44] "?[32mGET /login/azure/authorized?code=0.<Token>HTTP/1.1?[0m" 302 -
127.0.0.1 - - [28/Oct/2020 10:17:44] "?[37mGET / HTTP/1.1?[0m" 200 -
Am I missing something? Is it a good idea to use Flask Dance and Flask Login to have SSO with Azure AD? Or I should go with MSAL only along with Flask Session?
Kindly give your valuable inputs..
Since you use Azure AD as the Flask dance provider, we need to use Microsoft Graph to get user's information. The URL should be https://graph.microsoft.com/v1.0/me. So please update the code resp = blueprint.session.get("/user") to resp = blueprint.session.get("/v1.0/me") in method azure_logged_in. Besides, please note that the azure ad user's information has different names. We also need to update the code about creating users.
For example
#oauth_authorized.connect_via(blueprint)
def azure_logged_in(blueprint, token):
if not token:
# print(token)
flash("Failed to log in with azure.", category="error")
return False
resp = blueprint.session.get("/v1.0/me")
# azure.get
if not resp.ok:
# print(resp)
msg = "Failed to fetch user info from Azure."
flash(msg, category="error")
return False
azure_info = resp.json()
azure_user_id = str(azure_info["id"])
# print(azure_user_id)
# Find this OAuth token in the database, or create it
query = OAuth.query.filter_by(
provider=blueprint.name,
provider_user_id=azure_user_id,
)
try:
oauth = query.one()
except NoResultFound:
oauth = OAuth(
provider=blueprint.name,
provider_user_id=azure_user_id,
token=token,
)
if oauth.user:
login_user(oauth.user)
flash("Successfully signed in with Azure.")
else:
# Create a new local user account for this user
user = User(
# create user with user information from Microsoft Graph
email=azure_info["mail"],
username=azure_info["displayName"],
name=azure_info["userPrincipalName"]
)
# Associate the new local user account with the OAuth token
oauth.user = user
# Save and commit our database models
db.session.add_all([user, oauth])
db.session.commit()
# Log in the new local user account
login_user(user)
flash("Successfully signed in with Azure.")
# Disable Flask-Dance's default behavior for saving the OAuth token
return False
For more details, please refer to here and here

RPCError: dictionary update sequence element #0 has length 1; 2 is required on python

i wanted to insert new data into porstgresql using odooRPc i am having error like below
RPCError: dictionary update sequence element #0 has length 1; 2 is required
my python script code is :
def POST(self):
data = []
web.header('Access-Control-Allow-Origin', '*')
web.header('Access-Control-Allow-Credentials', 'true')
web.header('Content-Type', 'application/json')
auth = web.input()
print("auth")
print(auth)
name=auth['username']
pwd=auth['password']
city=auth['city']
eml=auth['eml']
mobile=auth['phone']
state_id=auth['state']
country_id=auth['country']
# print(type(auth['country']))
# country_id=auth.get('Country').get('id')
# country_id=auth['country'].get('id')
# print(country_id)
# state_id=auth['state']
# print(state_id)
odoo = odoorpc.ODOO('field.holisticbs.com',port=8069)
odoo.login('field.holisticbs.com','info#holisticbs.com','admin')
# Customer = odoo.execute_kw('res.partner','create',{'name':name,' email':eml,'mobile':mobile,' country_id':country_id,'state_id':state_id})
Customer = odoo.execute_kw('res.partner','create',{'name':name,' email':eml,'mobile':mobile})
print(Customer)
# Users = odoo.env['res.partner']
# user = Users.browse([int(idu)])
# print(user)
# Customer = odoo.execute_kw('res.user','create',{'login':eml,' password':pwd})
return json.dumps(Customer)
I have made my comments as below , kindly request you to find it as below it will help in your case:
Well there are many RPC Library (Python) for connecting with the API of Odoo/OpenERP:
xmlrpclib
odoorpc
erppeek
oerplib
openerplib..
In Your case You have chose the odoorpc.
Here is the code snippet for using it odoorpc:
import odoorpc
import json
domain ='localhost' #the domain
port=8069 #the active port
username = 'username' #the user name
password = 'password' #the user password
dbname = 'database_name' #the database
#Validate the credentials
odoo = odoorpc.ODOO(domain, port=port)
odoo.login(dbname, username, password)
#Login User details
user = odoo.env.user
print(user.name) # user name
print(user.company_id.name) # user company name
#Create a partner
user_data = odoo.execute('res.partner', 'create',
{'name':"PRAKASH",'
email':" prakashsharmacs24#gmail.com",
'mobile':"7859884833"})
print(user_data)
But i have also find you are using the method execute_kw so please use xmlrpclib if you want to use method execute_kw
Here is the code snippet for using it xmlrpclib:
import xmlrpclib
domain ='localhost' #the domain
port=8069 #the active port
username = 'username' #the user name
password = 'password' #the user password
dbname = 'database_name' #the database
#Validate the credentials
url='http://{domain}:{port}'.format(domain=domain,port=port)
login_url='{url}/xmlrpc/2/common'.format(url=url)
sock_common = xmlrpclib.ServerProxy(login_url)
uid = sock_common.login(dbname, username, password)
print sock_common.version()
print uid
models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))
#Validate the access rights
print models.execute_kw(dbname, uid, password,
'res.partner', 'check_access_rights',
['read'], {'raise_exception': False})
#Execute the query
print models.execute_kw(dbname, uid, password,
'res.partner', 'search',
[[['is_company', '=', True], ['customer', '=', True]]])
You can also refer this Link for knowing the difference between the RPC library
I hope this will help you ..

Django Auth is not finding User Account in LDAP

Morning,
I´m implementing Django Auth Ldap in my proyect but it is not working. I checked ldap connection (by Django shell) and returns a search, so I guess python-ldap is working. I used the next:
import ldap
con = ldap.initialize("ldap://hostname")
con.simple_bind_s( "CN=MyName MySurname, CN=Users, DC=CompanyName, DC=local", "MyPassword" )
con.search_s( 'DC=CompanyName, DC=local', ldap.SCOPE_SUBTREE, '(objectclass=person)', ['sn'] )
When I try to authenticate an user by web (using Django-Auth-Ldap), authentication always returns None.
Settings. (LDAP Configuration).
AUTH_LDAP_SERVER_URI = "ldap://hostname"
AUTH_LDAP_BIND_DN = "CN=MyName MySurname, CN=Users, DC=CompanyName, DC=local"
AUTH_LDAP_BIND_PASSWORD = "MyPassword"
AUTH_LDAP_USER_SEARCH = LDAPSearch("CN=Users, DC=CompanyName, DC=local", ldap.SCOPE_SUBTREE, "(uid=%(user)s)")
AUTH_LDAP_CONNECTION_OPTIONS = {
ldap.OPT_REFERRALS: False
}
from django_auth_ldap.backend import LDAPBackend
View.
def Login(request):
usr = "MyUserName"
pwd = "MyPassword"
if request.method == 'POST':
ldap_backend = LDAPBackend()
user = ldap_backend.authenticate(usr, pwd)
print user
print usr, pwd
In my view, I´m passing to the ldap authentication my user and password which I used for login in the domain. Is that correct?
I got the value "CN=MyName MySurname, CN=Users, DC=CompanyName, DC=local" from a command in Directory Active server, kind of: dsquery user
This is the AD Schema:
What Am I Doing wrong?
Thanks guys.
EDITED: The problem is when I define the search throug uid, if I define it as AUTH_LDAP_USER_SEARCH = LDAPSearch("CN=Users, DC=CompanyName, DC=local", ldap.SCOPE_SUBTREE, "(CN=%(user)s)") is working (and, in the view, I must to pass as usr = "MyNameMySurname" instead). How can I Define the search through the username which I used for login it.
Finally... I must to use samAccountName instead of CN. I hope it help you all. Thanks guys.

logging into github with python

I have been up and down these pages looking for how to do this and there are many similar posts but I can't seem to get it to work, so I find myself having to ask specifically how to do this.
I am trying to gather metrics about my software project in git hub. For many of these metrics you can use the API. However, one of the most interesting items are the unique visitors and view count on the github graphs/traffic and unfortunately this info is not located in the Github API. So, to get this I am trying to log into my github account navigate to the site then get the numbers. Located below is my code. I can't seem to get logged into github to do anything however (my url request continues to show a login page rather then the traffic page). I think it probably has something to do with the variables that need to be posted but I'm not sure whats wrong with them.
from requests import session
from bs4 import BeautifulSoup as bs
USER = 'MYID'
PASSWORD = 'MYPASSWORD'
URL1 = 'https://github.com/login'
URL2 = 'https://github.com/MYPROJ/graphs/traffic'
with session() as s:
req = s.get(URL1).text
html = bs(req)
token = html.find("input", {"name": "authenticity_token"}).attrs['value']
com_val = html.find("input", {"name": "commit"}).attrs['value']
login_data = {'login_field': USER,
'password': PASSWORD,
'authenticity_token' : token,
'commit' : com_val}
r1 = s.post(URL1, data = login_data)
r2 = s.get(URL2)
print(r2.url)
print bs(r2.text).find('span', {'class':'num js-uniques uniques'})
Any help is appreciated.
Thanks,
-Jeff
Figured it out.
I was using the wrong address to post my login and username, as well as some other wrong bits.
This is the updated code that worked for me:
from requests import session
from bs4 import BeautifulSoup as bs
USER = 'MyUserName'
PASSWORD = 'Mypassword'
URL1 = 'https://github.com/session'
URL2 = 'https://github.com/MyProj/graphs/traffic-data'
with session() as s:
req = s.get(URL1).text
html = bs(req)
token = html.find("input", {"name": "authenticity_token"}).attrs['value']
com_val = html.find("input", {"name": "commit"}).attrs['value']
login_data = {'login': USER,
'password': PASSWORD,
'commit' : com_val,
'authenticity_token' : token}
r1 = s.post(URL1, data = login_data)
r2 = s.get(URL2)
Cut1 = r2.text.split(',"summary":{"total":',2)
ViewsTot = Cut1[1].split(',"unique":',1)
ViewsUnq = ViewsTot[1].split('}}',1)

How to populate user profile with django-allauth provider information?

I'm using django-allauth for my authentication system. I need that when the user sign in, the profile module get populated with the provider info (in my case facebook).
I'm trying to use the pre_social_login signal, but I just don't know how to retrieve the data from the provider auth
from django.dispatch import receiver
from allauth.socialaccount.signals import pre_social_login
#receiver(pre_social_login)
def populate_profile(sender, **kwargs):
u = UserProfile( >>FACEBOOK_DATA<< )
u.save()
Thanks!!!
The pre_social_login signal is sent after a user successfully
authenticates via a social provider, but before the login is actually
processed. This signal is emitted for social logins, signups and when
connecting additional social accounts to an account.
So it is sent before the signup is fully completed -- therefore this not the proper signal to use.
Instead, I recommend you use allauth.account.signals.user_signed_up, which is emitted for all users, local and social ones.
From within that handler you can inspect whatever SocialAccount is attached to the user. For example, if you want to inspect Google+ specific data, do this:
user.socialaccount_set.filter(provider='google')[0].extra_data
UPDATE: the latest development version makes this a little bit more convenient by passing along a sociallogin parameter that directly contains all related info (social account, token, ...)
Here is a Concrete example of #pennersr solution :
Assumming your profile model has these 3 fields: first_name, email, picture_url
views.py:
#receiver(user_signed_up)
def populate_profile(sociallogin, user, **kwargs):
if sociallogin.account.provider == 'facebook':
user_data = user.socialaccount_set.filter(provider='facebook')[0].extra_data
picture_url = "http://graph.facebook.com/" + sociallogin.account.uid + "/picture?type=large"
email = user_data['email']
first_name = user_data['first_name']
if sociallogin.account.provider == 'linkedin':
user_data = user.socialaccount_set.filter(provider='linkedin')[0].extra_data
picture_url = user_data['picture-urls']['picture-url']
email = user_data['email-address']
first_name = user_data['first-name']
if sociallogin.account.provider == 'twitter':
user_data = user.socialaccount_set.filter(provider='twitter')[0].extra_data
picture_url = user_data['profile_image_url']
picture_url = picture_url.rsplit("_", 1)[0] + "." + picture_url.rsplit(".", 1)[1]
email = user_data['email']
first_name = user_data['name'].split()[0]
user.profile.avatar_url = picture_url
user.profile.email_address = email
user.profile.first_name = first_name
user.profile.save()
If you are confused about those picture_url variable in each provider. Then take a look at the docs:
facebook:
picture_url = "http://graph.facebook.com/" + sociallogin.account.uid + "/picture?type=large" Docs
linkedin:
picture_url = user_data['picture-urls']['picture-url'] Docs
twitter:
picture_url = picture_url.rsplit("_", 1)[0] + "." + picture_url.rsplit(".", 1)[1] Docs And for the rsplit() take a look here
Hope that helps. :)
I am doing in this way and taking picture (field) url and google provider(field) as an example.
socialaccount_obj = SocialAccount.objects.filter(provider='google', user_id=self.user.id)
picture = "not available"
if len(socialaccount_obj):
picture = socialaccount_obj[0].extra_data['picture']
make sure to import : from allauth.socialaccount.models import SocialAccount
There is an easier way to do this.
Just add the following to your settings.py. For example, Linked in...
SOCIALACCOUNT_PROVIDERS = {
'linkedin': {
'SCOPE': [
'r_basicprofile',
'r_emailaddress'
],
'PROFILE_FIELDS': [
'id',
'first-name',
'last-name',
'email-address',
'picture-url',
'public-profile-url',
]
}
The fields are automatically pulled across.