def test_load_by_filename(self): try: clientsecrets.loadfile(os.path.join(__file__, '..', 'afilethatisntthere.json')) self.fail('should fail to load a missing client_secrets file.') except clientsecrets.InvalidClientSecretsError, e: self.assertTrue(str(e).startswith('File'))
def test_validation(self): try: clientsecrets.loadfile(INVALID_FILE, cache=self.cache_mock) self.fail('Expected InvalidClientSecretsError to be raised ' 'while loading %s' % INVALID_FILE) except clientsecrets.InvalidClientSecretsError: pass
def __init__(self, filename, scope, message=None, cache=None, **kwargs): """Constructor Args: filename: string, File name of client secrets. scope: string or iterable of strings, scope(s) of the credentials being requested. message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. The message may contain HTML and will be presented on the web interface for any method that uses the decorator. cache: An optional cache service client that implements get() and set() methods. See clientsecrets.loadfile() for details. **kwargs: dict, Keyword arguments are passed along as kwargs to the OAuth2WebServerFlow constructor. """ client_type, client_info = clientsecrets.loadfile(filename, cache=cache) if client_type not in (clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED): raise InvalidClientSecretsError("OAuth2Decorator doesn't support this OAuth 2.0 flow.") constructor_kwargs = dict(kwargs) constructor_kwargs.update( {"auth_uri": client_info["auth_uri"], "token_uri": client_info["token_uri"], "message": message} ) revoke_uri = client_info.get("revoke_uri") if revoke_uri is not None: constructor_kwargs["revoke_uri"] = revoke_uri super(OAuth2DecoratorFromClientSecrets, self).__init__( client_info["client_id"], client_info["client_secret"], scope, **constructor_kwargs ) if message is not None: self._message = message else: self._message = "Please configure your application for OAuth 2.0."
def __init__(self, filename, scope, message=None, cache=None): """Constructor Args: filename: string, File name of client secrets. scope: string or iterable of strings, scope(s) of the credentials being requested. message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. The message may contain HTML and will be presented on the web interface for any method that uses the decorator. cache: An optional cache service client that implements get() and set() methods. See clientsecrets.loadfile() for details. """ client_type, client_info = clientsecrets.loadfile(filename, cache=cache) if client_type not in [ clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]: raise InvalidClientSecretsError( 'OAuth2Decorator doesn\'t support this OAuth 2.0 flow.') constructor_kwargs = { 'auth_uri': client_info['auth_uri'], 'token_uri': client_info['token_uri'], 'message': message, } revoke_uri = client_info.get('revoke_uri') if revoke_uri is not None: constructor_kwargs['revoke_uri'] = revoke_uri super(OAuth2DecoratorFromClientSecrets, self).__init__( client_info['client_id'], client_info['client_secret'], scope, **constructor_kwargs) if message is not None: self._message = message else: self._message = 'Please configure your application for OAuth 2.0.'
def test_cache_hit(self): self.cache_mock.cache[NONEXISTENT_FILE] = {"web": "secret info"} client_type, client_info = clientsecrets.loadfile(NONEXISTENT_FILE, cache=self.cache_mock) self.assertEqual("web", client_type) self.assertEqual("secret info", client_info) # make sure we didn't do any set() RPCs self.assertEqual(None, self.cache_mock.last_set_ns)
def _load_client_secrets(self, filename): """Loads client secrets from the given filename.""" client_type, client_info = clientsecrets.loadfile(filename) if client_type != clientsecrets.TYPE_WEB: raise ValueError("The flow specified in {0} is not supported.".format(client_type)) self.client_id = client_info["client_id"] self.client_secret = client_info["client_secret"]
def test_cache_hit(self): self.cache_mock.cache[NONEXISTENT_FILE] = {'web': 'secret info'} client_type, client_info = clientsecrets.loadfile( NONEXISTENT_FILE, cache=self.cache_mock) self.assertEquals('web', client_type) self.assertEquals('secret info', client_info) # make sure we didn't do any set() RPCs self.assertEqual(None, self.cache_mock.last_set_ns)
def _load_client_secrets(filename): """Loads client secrets from the given filename.""" client_type, client_info = clientsecrets.loadfile(filename) if client_type != clientsecrets.TYPE_WEB: raise ValueError( 'The flow specified in {} is not supported, only the WEB flow ' 'type is supported.'.format(client_type)) return client_info['client_id'], client_info['client_secret']
def _load_client_secrets(self, filename): """Loads client secrets from the given filename.""" client_type, client_info = clientsecrets.loadfile(filename) if client_type != clientsecrets.TYPE_WEB: raise ValueError( 'The flow specified in %s is not supported.' % client_type) self.client_id = client_info['client_id'] self.client_secret = client_info['client_secret']
def test_cache_miss(self): client_type, client_info = clientsecrets.loadfile(VALID_FILE, cache=self.cache_mock) self.assertEqual("web", client_type) self.assertEqual("foo_client_secret", client_info["client_secret"]) cached = self.cache_mock.cache[VALID_FILE] self.assertEqual({client_type: client_info}, cached) # make sure we're using non-empty namespace ns = self.cache_mock.last_set_ns self.assertTrue(bool(ns)) # make sure they're equal self.assertEqual(ns, self.cache_mock.last_get_ns)
def test_cache_miss(self): client_type, client_info = clientsecrets.loadfile( VALID_FILE, cache=self.cache_mock) self.assertEquals('web', client_type) self.assertEquals('foo_client_secret', client_info['client_secret']) cached = self.cache_mock.cache[VALID_FILE] self.assertEquals({client_type: client_info}, cached) # make sure we're using non-empty namespace ns = self.cache_mock.last_set_ns self.assertTrue(bool(ns)) # make sure they're equal self.assertEquals(ns, self.cache_mock.last_get_ns)
def credentials_from_client_secrets_and_token(filename, refresh_token): """Create a OAuth2Credentials from a client-secrets file and AuthData record. """ client_type, client_info = clientsecrets.loadfile(filename) if client_type in [clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]: return oa2client.OAuth2Credentials( None, client_info['client_id'], client_info['client_secret'], refresh_token, None, # token_expiry 'https://accounts.google.com/o/oauth2/token', # token_uri None) # user_agent else: raise oa2client.UnknownClientSecretsFlowError('This OAuth 2.0 flow is unsupported: "{}"'.format(client_type))
def requestToken(): logging.debug('requesting new access token') xxxx, clientInfo = loadfile(CLIENT_SECRETS) flow = OAuth2WebServerFlow( client_id = clientInfo['client_id'], client_secret = clientInfo['client_secret'], scope = 'https://www.googleapis.com/auth/calendar.readonly', user_agent = 'calendrial/0.0', access_type = 'offline' ) callback = self.request.relative_url('/oauth2callback') authorizeUrl = flow.step1_get_authorize_url(callback) memcache.set(user.user_id(), pickle.dumps(flow)) memcache.set(user.user_id() + "_url", redirectUrl) self.redirect(authorizeUrl)
def test_io_file_cache(self): with io.open(VALID_FILE, 'r') as f: client_type, client_info = clientsecrets.loadfile( f, cache=self.cache_mock) self.assertEquals('web', client_type) self.assertEquals('foo_client_secret', client_info['client_secret']) cached = self.cache_mock.cache[VALID_FILE] self.assertEquals({client_type: client_info}, cached) # make sure we're using non-empty namespace ns = self.cache_mock.last_set_ns self.assertTrue(bool(ns)) # make sure they're equal self.assertEquals(ns, self.cache_mock.last_get_ns)
def from_file(filename, cache=None, redirect_uri=None, _sandbox=False): """Create a ClientSecrets from a clientsecrets JSON file. Very closely resembles oauth2client.client.flow_from_clientsecrets(). """ _client_type, client_info = \ clientsecrets.loadfile(filename, cache=cache) constructor_kwargs = { 'redirect_uri': redirect_uri, 'auth_uri': client_info['auth_uri'], 'token_uri': client_info['token_uri'], '_sandbox': _sandbox, } return ClientSecrets(client_info['client_id'], client_info['client_secret'], **constructor_kwargs)
def _load_client_secrets(filename): """Loads client secrets from the given filename. Args: filename: The name of the file containing the JSON secret key. Returns: A 2-tuple, the first item containing the client id, and the second item containing a client secret. """ client_type, client_info = clientsecrets.loadfile(filename) if client_type != clientsecrets.TYPE_WEB: raise ValueError( 'The flow specified in {} is not supported, only the WEB flow ' 'type is supported.'.format(client_type)) return client_info['client_id'], client_info['client_secret']
def _create_flow(request, scopes, return_url=None): """Creates flow object. Args: request: Django request object. scopes: YouTube request oauth2 scopes. return_url: Url to return to after flow object is created. Returns: oauth2 flow object that is stored in the session. """ #Loading client secrets from .json file, client_type has no current use _client_type, client_info = loadfile(settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON) #Generate CSRF token and store it in the session csrf_token = hashlib.sha256(os.urandom(1024)).hexdigest() request.session[_CSRF_KEY] = csrf_token state = json.dumps({ 'csrf_token': csrf_token, 'return_url': return_url, }) #Initialize flow object with client_info flow = OAuth2WebServerFlow( client_id=client_info['client_id'], client_secret=client_info['client_secret'], scope=scopes, state=state, redirect_uri=request.build_absolute_uri(reverse('core:authcallback')) ) flow_key = _FLOW_KEY.format(csrf_token) request.session[flow_key] = jsonpickle.encode(flow) return flow
def test_validation(self): with self.assertRaises(clientsecrets.InvalidClientSecretsError): clientsecrets.loadfile(INVALID_FILE, cache=self.cache_mock)
def get_secrets(): client_type, client_info = clientsecrets.loadfile(CLIENT_SECRET_FILE) return client_info
def test_without_cache(self): # this also ensures loadfile() is backward compatible client_type, client_info = clientsecrets.loadfile(VALID_FILE) self.assertEqual('web', client_type) self.assertEqual('foo_client_secret', client_info['client_secret'])
def test_io_file(self): with io.open(VALID_FILE, 'r') as f: client_type, client_info = clientsecrets.loadfile(f) self.assertEquals('web', client_type) self.assertEquals('foo_client_secret', client_info['client_secret'])
To make this sample run you will need to populate the client_secrets.json file found at: </p> <p> <code>%s</code>. </p> <p>with information found on the <a href="https://code.google.com/apis/console">APIs Console</a>. </p> """ % CLIENT_SECRETS client_secret = memcache.get(CLIENT_SECRETS, namespace=CLIENT_SECRETS_NAMESPACE) if client_secret is None: if os.path.exists(CLIENT_SECRETS): client_type, client_info = clientsecrets.loadfile(CLIENT_SECRETS, memcache) client_secret = OAuth2ClientSecret( key_name = "site", client_type = client_type, auth_uri = client_info.get('auth_uri'), client_id = client_info.get('client_id'), client_secret = client_info.get('client_secret'), token_uri = client_info.get('token_uri'), redirect_uris = client_info.get('redirect_uris'), auth_provider_x509_cert_url = client_info.get('auth_provider_x509_cert_url'), client_email = client_info.get('client_email'), client_x509_cert_url = client_info.get('client_x509_cert_url'), javascript_origins = client_info.get('javascript_origins'), revoke_uri = client_info.get('revoke_uri') ) memcache.set(CLIENT_SECRETS, client_secret, namespace=CLIENT_SECRETS_NAMESPACE)
def gd_upload(local_image_path, client_secrets_path, RSNAME): ### Open the spreadsheet on GoogleDocs for editing scope = 'https://spreadsheets.google.com/feeds https://docs.google.com/feeds' from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive import gspread # python wrapper for manipulating online spreadsheet #more manual approach for authenticating gspread with OAuth2 from oauth2client import client from oauth2client import clientsecrets print('made it here..') # authenticate with google for gspread (the tougher one..) # TODO: figure out how to authenticate once and share with both wrappers cs_path = client_secrets_path + '/client_secrets.json' client_type, client_info = clientsecrets.loadfile(cs_path) flow = client.flow_from_clientsecrets(cs_path, scope, redirect_uri=client_info['redirect_uris'][0]) # auth_uri is a URL which will give you an authorization key # PyDrive somehow opens the brower and retrieves the key without manual # copy-pasta, TODO: review PyDrive code to figure out that magic auth_uri = flow.step1_get_authorize_url() print("Copy-paste-visit the following URL in your web browser:\n") print(auth_uri) # the 'code' argument is the key returned by the web browser gd_code = raw_input("enter code produced in web browser") credentials = flow.step2_exchange(gd_code) gc = gspread.authorize(credentials) #authorized connection to google sheets wks = gc.open(RSNAME) #open the remote spreadsheet secret_table = wks.worksheet('secret') #open the sheet in the worksheet we # need, which will be called with 'secret_table.somecommand' to modify ### Open GoogleDrive for uploading of the source images ### Collect filenames containing what we need for each field of the table import fnmatch import os # unfortunately listdir() doesn't support wildcards, so this.. # replace with regular expressions? orig_images = [] messages = [] locations = [] comments = [] likes = [] for file in os.listdir(local_image_path): if fnmatch.fnmatch(file, '*_crop.png'): orig_images = orig_images + [file] elif fnmatch.fnmatch(file, 'ocr*.png'): messages = messages + [file] elif fnmatch.fnmatch(file, '*_2.png'): locations = locations + [file] elif fnmatch.fnmatch(file, '*_3.png'): comments = comments + [file] elif fnmatch.fnmatch(file, '*_4.png'): likes = likes + [file] print 'orig_images:', orig_images print 'messages:', messages print 'locations', locations print 'comments:', comments print 'likes:', likes return
def test_without_cache(self): # this also ensures loadfile() is backward compatible client_type, client_info = clientsecrets.loadfile(VALID_FILE) self.assertEquals('web', client_type) self.assertEquals('foo_client_secret', client_info['client_secret'])
import application.settings as settings def jinja2_date_filter(date, fmt=None): if fmt: return date.strftime(fmt) else: return date.strftime('%Y-%m') # oauth # Set deadline of urlfetch in order to prevent 5 second timeout urlfetch.set_default_fetch_deadline(45) # Load client secrets from 'client_secrets.json' file. client_type, client_info = loadfile(settings.CLIENT_SECRETS) FLOW = flow_from_clientsecrets( settings.CLIENT_SECRETS, scope=['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/devstorage.read_write'], redirect_uri=client_info['redirect_uris'][0], ) FLOW.params.update({'access_type': 'offline'}) FLOW.params.update({'approval_prompt': 'force'}) class BaseRequestHandler(webapp2.RequestHandler): def dispatch(self): """Get a session store for this request.""" self.session_store = sessions.get_store(request=self.request) try: # Dispatch the request.
from google.appengine.api import urlfetch from google.appengine.runtime.apiproxy_errors import DeadlineExceededError from oauth2client.client import AccessTokenRefreshError from oauth2client.client import flow_from_clientsecrets from oauth2client.client import FlowExchangeError from oauth2client.clientsecrets import loadfile from push import StopChannel from push import WatchChange from push import WatchFile # Set deadline of urlfetch in order to prevent 5 second timeout urlfetch.set_default_fetch_deadline(45) # Load client secrets from 'client_secrets.json' file. CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json') client_type, client_info = loadfile(CLIENT_SECRETS) FLOW = flow_from_clientsecrets( CLIENT_SECRETS, scope=('https://www.googleapis.com/auth/drive ' 'https://www.googleapis.com/auth/userinfo.profile'), redirect_uri=client_info['redirect_uris'][0], ) FLOW.params.update({'access_type': 'offline'}) FLOW.params.update({'approval_prompt': 'force'}) # Load Jinja2 template environment. JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.FileSystemLoader( os.path.join(os.path.dirname(__file__), 'templates')), extensions=['jinja2.ext.autoescape'])
else: return date.strftime('%Y-%m') # Build a service object for interacting with the API. api = 'cheerspoint' version = 'v1' discovery_url = '%s/discovery/v1/apis/%s/%s/rest' % (settings.API_ROOT, api, version) # oauth # Set deadline of urlfetch in order to prevent 5 second timeout urlfetch.set_default_fetch_deadline(45) # Load client secrets from 'client_secrets.json' file. client_type, client_info = loadfile(settings.CLIENT_SECRETS) FLOW = flow_from_clientsecrets( settings.CLIENT_SECRETS, scope=[ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/devstorage.read_write' ], redirect_uri=client_info['redirect_uris'][0], ) FLOW.params.update({'access_type': 'offline'}) FLOW.params.update({'approval_prompt': 'force'}) class BaseRequestHandler(webapp2.RequestHandler): def dispatch(self): """Get a session store for this request."""
from google.appengine.api import urlfetch from google.appengine.runtime.apiproxy_errors import DeadlineExceededError from oauth2client.client import AccessTokenRefreshError from oauth2client.client import flow_from_clientsecrets from oauth2client.client import FlowExchangeError from oauth2client.clientsecrets import loadfile from push import StopChannel from push import WatchChange from push import WatchFile # Set deadline of urlfetch in order to prevent 5 second timeout urlfetch.set_default_fetch_deadline(45) # Load client secrets from 'client_secrets.json' file. CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json') client_type, client_info = loadfile(CLIENT_SECRETS) FLOW = flow_from_clientsecrets( CLIENT_SECRETS, scope=('https://www.googleapis.com/auth/drive ' 'https://www.googleapis.com/auth/userinfo.profile'), redirect_uri=client_info['redirect_uris'][0],) FLOW.params.update({'access_type': 'offline'}) FLOW.params.update({'approval_prompt': 'force'}) # Load Jinja2 template environment. JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')), extensions=['jinja2.ext.autoescape'])