def test_decorator_from_unfilled_client_secrets_aware(self): MESSAGE = 'File is missing' try: decorator = OAuth2DecoratorFromClientSecrets( datafile('unfilled_client_secrets.json'), scope=['foo_scope', 'bar_scope'], message=MESSAGE) except InvalidClientSecretsError: pass
def test_decorator_from_cached_client_secrets(self): cache_mock = CacheMock() load_and_cache('client_secrets.json', 'secret', cache_mock) decorator = OAuth2DecoratorFromClientSecrets( # filename, scope, message=None, cache=None 'secret', '', cache=cache_mock) self.assertFalse(decorator._in_error)
def test_decorator_from_client_secrets_not_logged_in_aware(self): decorator = OAuth2DecoratorFromClientSecrets( datafile('client_secrets.json'), scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage') self.decorator = decorator self._finish_setup(decorator, user_mock=UserNotLoggedInMock) # An initial request to an oauth_aware decorated path should be a # redirect to login. response = self.app.get('/bar_path/2012/03') self.assertTrue(response.status.startswith('302')) self.assertTrue('Login' in str(response))
def test_decorator_from_client_secrets(self): decorator = OAuth2DecoratorFromClientSecrets( datafile('client_secrets.json'), scope=['foo_scope', 'bar_scope']) self._finish_setup(decorator, user_mock=UserMock) self.assertFalse(decorator._in_error) self.decorator = decorator self.test_required() http = self.decorator.http() self.assertEquals('foo_access_token', http.request.credentials.access_token) # revoke_uri is not required self.assertEqual(self.decorator._revoke_uri, 'https://accounts.google.com/o/oauth2/revoke') self.assertEqual(self.decorator._revoke_uri, self.decorator.credentials.revoke_uri)
def test_decorator_from_client_secrets_with_optional_settings(self): # Test that the decorator works with the absense of a revoke_uri in # the client secrets. loadfile_patch = mock.patch( 'oauth2client.contrib.appengine.clientsecrets.loadfile') with loadfile_patch as loadfile_mock: loadfile_mock.return_value = ( TYPE_WEB, { "client_id": "foo_client_id", "client_secret": "foo_client_secret", "redirect_uris": [], "auth_uri": "https://accounts.google.com/o/oauth2/v2/auth", "token_uri": "https://www.googleapis.com/oauth2/v4/token", # No revoke URI }) decorator = OAuth2DecoratorFromClientSecrets( 'doesntmatter.json', scope=['foo_scope', 'bar_scope']) self.assertEqual(decorator._revoke_uri, GOOGLE_REVOKE_URI) # This is never set, but it's consistent with other tests. self.assertFalse(decorator._in_error)
def test_decorator_from_client_secrets_kwargs(self): decorator = OAuth2DecoratorFromClientSecrets( datafile('client_secrets.json'), scope=['foo_scope', 'bar_scope'], approval_prompt='force') self.assertTrue('approval_prompt' in decorator._kwargs)
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Setup for OAuth2. """ import os from oauth2client.contrib.appengine import CredentialsModel from oauth2client.contrib.appengine import OAuth2DecoratorFromClientSecrets from oauth2client.contrib.appengine import StorageByKeyName CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json') YOUTUBE_READ_WRITE_SCOPE = 'https://www.googleapis.com/auth/youtube' decorator = OAuth2DecoratorFromClientSecrets(CLIENT_SECRETS, YOUTUBE_READ_WRITE_SCOPE) def _CreateStorage(key_name): return StorageByKeyName( model=CredentialsModel, key_name=key_name, # Use user_id. property_name='credentials') def AddCredentialsToStorage(key_name, credentials): _CreateStorage(key_name).put(credentials) def GetCredentialsFromStorage(key_name): return _CreateStorage(key_name).get()
""" Google Calendar utilities. """ import os.path from googleapiclient.discovery import build from oauth2client import file, client, tools from httplib2 import Http from dateutil.parser import parse from oauth2client.contrib.appengine import OAuth2DecoratorFromClientSecrets, CredentialsProperty, StorageByKeyName oauth_decorator = OAuth2DecoratorFromClientSecrets( os.path.join(os.path.dirname(__file__), "gcal_credentials.json"), "https://www.googleapis.com/auth/calendar") service = build("calendar", "v3") INCLUDE = ["*****@*****.**", "MIT classes", "MIT regulars"] def fetch_all_calendar_events(timeMin=None, timeMax=None, calendars=None, preferred_timezones=None, query=None): http = oauth_decorator.http() # fetch all calendars calendar_names = calendars calendars = service.calendarList().list(maxResults=250).execute(http=http) calendarIDs = [
import webapp2 import httplib2 import os from apiclient import discovery from oauth2client.contrib.appengine import OAuth2DecoratorFromClientSecrets SCOPES = 'https://www.googleapis.com/auth/drive.readonly' CLIENT_SECRET = 'client_secret.json' MAX_RESULTS=50 decorator=OAuth2DecoratorFromClientSecrets(os.path.join(os.path.dirname(__file__),CLIENT_SECRET),SCOPES) service = discovery.build('drive', 'v2') class MainPage(webapp2.RequestHandler): @decorator.oauth_required def get(self): self.response.headers['Content-Type']='text/plain' if decorator.has_credentials(): results=service.files().list(maxResults=MAX_RESULTS).execute(decorator.http()) files=results.get('items') if not files: self.response.write('no files found') else: self.response.write('Files: \n') for file in files: self.response.write(file['title'].encode('ascii','ignore').decode('ascii')+'\n') app=webapp2.WSGIApplication([('/',MainPage),(decorator.callback_path,decorator.callback_handler()),], debug=True)
import logging import os from oauth2client.contrib.appengine import OAuth2DecoratorFromClientSecrets if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'): # Production logging.info('Using production oauth credentials') secrets_filename = 'secrets/oauth.json' else: # Dev logging.info('Using dev oauth credentials') secrets_filename = 'secrets/dev_oauth.json' decorator = OAuth2DecoratorFromClientSecrets( filename=os.path.join(os.path.dirname(__file__), secrets_filename), scope=[ 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/contacts', 'https://www.googleapis.com/auth/calendar' ])
from oauth2client.client import Error import api.actions as actions from api.fileupload import FileUpload, FileDelete logger = logging.getLogger() client_scopes = ['profile', 'email', 'https://www.googleapis.com/auth/plus.me'] # client_scopes = ['https://www.googleapis.com/auth/tasks'] client_keyfile = 'private/auth/keys/MapAppClientKeys.json' types_file_key = 'types' client_decorator = OAuth2DecoratorFromClientSecrets( client_keyfile, client_scopes, 'Secrets file is missing or invalid.') def _boolean(str): if str and str.lower() == 'true': return True else: return False def ospath(path): return os.path.join(os.path.dirname(__file__), path) def _http_auth(): if client_decorator.has_credentials():
For more information, see README.md. """ import json import os import googleapiclient.discovery from oauth2client.contrib.appengine import OAuth2DecoratorFromClientSecrets import webapp2 # The project id whose datasets you'd like to list PROJECTID = '<your-project-id>' # Create the method decorator for oauth. decorator = OAuth2DecoratorFromClientSecrets( os.path.join(os.path.dirname(__file__), 'client_secrets.json'), scope='https://www.googleapis.com/auth/bigquery') # Create the bigquery api client service = googleapiclient.discovery.build('bigquery', 'v2') class MainPage(webapp2.RequestHandler): # oauth_required ensures that the user goes through the OAuth2 # authorization flow before reaching this handler. @decorator.oauth_required def get(self): # This is an httplib2.Http instance that is signed with the user's # credentials. This allows you to access the BigQuery API on behalf # of the user.
import webapp2 from apiclient.discovery import build from oauth2client.client import GoogleCredentials from oauth2client.contrib.appengine import OAuth2DecoratorFromClientSecrets import happiness_scorer import user_getter TEMPLATE_PATH = os.path.join(os.path.dirname(__file__), 'templates') JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(TEMPLATE_PATH), extensions=['jinja2.ext.autoescape'], autoescape=True) decorator = OAuth2DecoratorFromClientSecrets( os.path.join(os.path.dirname(__file__), 'client_secrets.json'), 'https://www.googleapis.com/auth/plus.login') class MainHandler(webapp2.RequestHandler): @decorator.oauth_required def get(self): g_plus_service = get_g_plus_service() vision_service = get_vision_service() user = user_getter.get_individual(g_plus_service) happiness_scorer.evaluate_users(vision_service, [user]) friends = user_getter.get_friends(g_plus_service) happiness_scorer.evaluate_users(vision_service, friends) scored_friends = [f for f in friends if f.happiness_level]
'auth_url': deco.authorize_url(), 'login_url': users.create_login_url('/'), 'logout_url': users.create_logout_url('/'), 'nickname': user.nickname(), 'email': user.email() } #------------------------------------------------- # Setting up the OAuth2 authorization and google- # api-interfaces decorator = OAuth2DecoratorFromClientSecrets( os.path.join(os.path.dirname(__file__), 'client_secrets.json'), scope=[ 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/calendar', 'https://spreadsheets.google.com/feeds' ]) GoogleDrive = apgooglelayer.drive.GoogleDrive() GoogleCalendar = apgooglelayer.calendar.GoogleCalendar() """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~""" import traceback def printerrors(prefix): def thedecorator(f): def mydecorator(*args, **kwargs): try: return f(*args, **kwargs)
import os import webapp2 from google.appengine.api import memcache, taskqueue from google.appengine.ext import ndb from apiclient.discovery import build from oauth2client.contrib.appengine import (CredentialsNDBProperty, OAuth2DecoratorFromClientSecrets, StorageByKeyName) AUTH_ARGS = {'access_type': 'offline'} OAUTH_DECORATOR = OAuth2DecoratorFromClientSecrets( os.path.join(os.path.dirname(__file__), 'client_secrets.json'), 'https://www.googleapis.com/auth/youtube', **AUTH_ARGS) class CredentialsModel(ndb.Model): """Test""" credentials = CredentialsNDBProperty() class MainHandler(webapp2.RequestHandler): """Entry point for our web app.""" @OAUTH_DECORATOR.oauth_required def get(self): """Handler for GET requests to the app.""" http = OAUTH_DECORATOR.http() if not self.request.get('videoId'):