def test_decorator_from_cached_client_secrets(self): cache_mock = CacheMock() load_and_cache('client_secrets.json', 'secret', cache_mock) decorator = oauth2decorator_from_clientsecrets( # filename, scope, message=None, cache=None 'secret', '', cache=cache_mock) self.assertFalse(decorator._in_error)
def test_decorator_from_unfilled_client_secrets_aware(self): MESSAGE = 'File is missing' try: decorator = oauth2decorator_from_clientsecrets( datafile('unfilled_client_secrets.json'), scope=['foo_scope', 'bar_scope'], message=MESSAGE) except InvalidClientSecretsError: pass
def decorator(self): try: client_secrets_path = self.config['client_secrets_path'] except KeyError: raise config.ConfigError('Missing: client_secrets_path') decorator = appengine.oauth2decorator_from_clientsecrets( client_secrets_path, scope=self.config.get('scopes', config.Defaults.OAUTH_SCOPES)) decorator._callback_path = '{}/oauth2callback'.format(self.config['airlock_path']) return decorator
def decorator(self): try: client_secrets_path = self.config['client_secrets_path'] except KeyError: raise config.ConfigError('Missing: client_secrets_path') decorator = appengine.oauth2decorator_from_clientsecrets( client_secrets_path, scope=self.config.get('scopes', config.Defaults.OAUTH_SCOPES)) decorator._callback_path = '{}/oauth2callback'.format( self.config['airlock_path']) return decorator
def test_decorator_from_client_secrets(self): decorator = oauth2decorator_from_clientsecrets( 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)
def test_decorator_from_client_secrets_not_logged_in_aware(self): decorator = oauth2decorator_from_clientsecrets( 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_unfilled_client_secrets_aware(self): MESSAGE = 'File is missing' decorator = oauth2decorator_from_clientsecrets( datafile('unfilled_client_secrets.json'), scope=['foo_scope', 'bar_scope'], message=MESSAGE) self._finish_setup(decorator, user_mock=UserNotLoggedInMock) self.assertTrue(decorator._in_error) self.assertEqual(MESSAGE, decorator._message) # An initial request to an oauth_aware decorated path should be an # error message. response = self.app.get('/bar_path/2012/03') self.assertTrue(response.status.startswith('200')) self.assertTrue(MESSAGE in str(response))
def oauth(self,oauth_url,oauth_client_id,oauth_client_secret): http = httplib2.Http(memcache) service = build("plus", "v1", http=http) decorator = oauth2decorator_from_clientsecrets(OAUTH_CLIENT_SECRETS,OAUTH_PROVIDER) try: http = decorator.http() user = service.people().get(userId='me').execute(http) if user: u=db.GqlQuery("select * from User where oauth_id=:1",user) user=u.fetch(1) if len(user): user=user[0] self.response.out.write("User logged in:<br />Name: "+str(user.name)+"<br/>UID: "+str(id)+"<br />Cookie:"+str(cookie)) #a session id should only be created on successful login to prevent session fixation. self.new_session(user) except AccessTokenRefreshError: self.redirect('/')
def test_decorator_from_client_secrets(self): decorator = oauth2decorator_from_clientsecrets( 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 _build_decorator(): """Builds a decorator for using oauth2 with webapp2.RequestHandlers.""" try: return appengine.oauth2decorator_from_clientsecrets( _CLIENTSECRETS_JSON_PATH, scope=[ 'https://www.googleapis.com/auth/drive.readonly', 'https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', ], message='client_secrets.json missing') # Deliberately catch everything. pylint: disable=broad-except except Exception as e: display_error = ( 'oauth2 module enabled, but unable to load client_secrets.json. ' 'See docs in modules/oauth2.py. Original exception was:\n\n%s') % ( traceback.format_exc(e)) return _ErrorDecorator(error=display_error)
def _build_decorator(): """Builds a decorator for using oauth2 with webapp2.RequestHandlers.""" try: return appengine.oauth2decorator_from_clientsecrets( _CLIENTSECRETS_JSON_PATH, scope=[ 'https://www.googleapis.com/auth/drive.readonly', 'https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', ], message='client_secrets.json missing') # Deliberately catch everything. pylint: disable-msg=broad-except except Exception as e: display_error = ( 'oauth2 module enabled, but unable to load client_secrets.json. ' 'See docs in modules/oauth2.py. Original exception was:\n\n%s') % ( traceback.format_exc(e)) return _ErrorDecorator(error=display_error)
from google.appengine.api import users from google.appengine.api import memcache socket.setdefaulttimeout(60) http = httplib2.Http(cache=memcache if USE_APPENGINE else None) JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.FileSystemLoader( os.path.dirname(__file__)), autoescape=True, extensions=['jinja2.ext.autoescape']) client_secrets = os.path.join(os.path.dirname(__file__), 'client_secrets.json') if USE_APPENGINE and REQUIRE_OAUTH: decorator = appengine.oauth2decorator_from_clientsecrets( client_secrets, scope=[ 'https://www.googleapis.com/auth/genomics', ]) else: class FakeOauthDecorator(): def http(self): return http def oauth_aware(self, method): return method @property def callback_path(self): return '/unused' def callback_handler(self):
import httplib2 import os.path import webapp2 from oauth2client.appengine import oauth2decorator_from_clientsecrets from oauth2client.client import AccessTokenRefreshError from google.appengine.api import memcache from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), '../client_secrets.json') http = httplib2.Http(memcache) decorator = oauth2decorator_from_clientsecrets( CLIENT_SECRETS, 'https://www.googleapis.com/auth/prediction', 'Fill out %s' % CLIENT_SECRETS) class OAuthSetupHandler(webapp2.RequestHandler): @decorator.oauth_required def get(self): user = users.get_current_user() try: http = decorator.http() self.response.out.write('oauth set up for user id %r!' % user.user_id()) except AccessTokenRefreshError, e: self.response.out.write('oauth error! %s' % e)
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 http = httplib2.Http(memcache) service = build("plus", "v1", http=http) decorator = oauth2decorator_from_clientsecrets( CLIENT_SECRETS, 'https://www.googleapis.com/auth/plus.me', MISSING_CLIENT_SECRETS_MESSAGE) class MainHandler(BaseHandler): @decorator.oauth_aware def get(self): variables = { 'url': decorator.authorize_url(), 'has_credentials': decorator.has_credentials() } self.render_response('grant.html', **variables) class AboutHandler(BaseHandler):
</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 http = httplib2.Http(memcache) service = discovery.build('plus', 'v1', http=http) decorator = appengine.oauth2decorator_from_clientsecrets( CLIENT_SECRETS, scope=[ 'https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', ], message=MISSING_CLIENT_SECRETS_MESSAGE) people_resource = service.people() people_document = people_resource.get(userId='me').execute() class Greeting(ndb.Model): author = ndb.UserProperty() content = ndb.StringProperty(indexed=False) date = ndb.DateTimeProperty(auto_now_add=True)
# Increase timeout to the maximum for all requests and use caching urlfetch.set_default_fetch_deadline(60) socket.setdefaulttimeout(60) http = httplib2.Http(cache=memcache) JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), autoescape=True, extensions=['jinja2.ext.autoescape']) client_secrets = os.path.join(os.path.dirname(__file__), 'client_secrets.json') decorator = appengine.oauth2decorator_from_clientsecrets( client_secrets, scope=[ 'https://www.googleapis.com/auth/genomics', 'https://www.googleapis.com/auth/devstorage.read_write' ]) SUPPORTED_BACKENDS = { 'GOOGLE' : {'name' : 'Google', 'url': 'https://www.googleapis.com/genomics/v1beta'}, 'NCBI' : {'name' : 'NCBI', 'url': 'http://trace.ncbi.nlm.nih.gov'}, 'LOCAL' : {'name' : 'Local', 'url': 'http://localhost:5000'}, } class ApiException(Exception): pass # Basic user settings class UserSettings(db.Model):
MISSING_CLIENT_SECRETS_MESSAGE = """ <h1>Warning: Please configure OAuth 2.0</h1> <p> 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 # the decorator decorator = appengine.oauth2decorator_from_clientsecrets( CLIENT_SECRETS, scope=[ 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.appdata', 'https://www.googleapis.com/auth/drive.apps.readonly', 'https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/drive.metadata.readonly', 'https://www.googleapis.com/auth/drive.readonly', 'https://www.googleapis.com/auth/drive.scripts', ], message=MISSING_CLIENT_SECRETS_MESSAGE) http_cache = httplib2.Http(memcache) service = discovery.build('drive', 'v2', http=http_cache)
""" % CLIENT_SECRETS http = httplib2.Http(memcache) service = build("youtube", "v3", http=http, developerKey="INSERTZ_KEYZ_ERE") # Set up an OAuth2Decorator object to be used for authentication. Add one or # more of the following scopes in the scopes parameter below. PLEASE ONLY ADD # THE SCOPES YOU NEED. For more information on using scopes please see # <https://developers.google.com/+/best-practices>. decorator = oauth2decorator_from_clientsecrets( CLIENT_SECRETS, scope=[ 'https://www.googleapis.com/auth/youtube.readonly', 'https://www.googleapis.com/auth/youtube', 'https://www.googleapis.com/auth/youtubepartner', 'https://www.googleapis.com/auth/youtube.upload', ], message=MISSING_CLIENT_SECRETS_MESSAGE) application = webapp2.WSGIApplication( [ ('/', IndexHandler), (decorator.callback_path, decorator.callback_handler()), ('/categories', CategoriesHandler) ], debug=True)
import pickle JINJA_ENVIRONMENT = jinja2.Environment( autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), ''))) logging.getLogger().setLevel(logging.DEBUG) CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json') logging.info('CLIENT_SECRETS is ' + CLIENT_SECRETS) http = httplib2.Http(memcache) service = discovery.build("calendar", "v3", http=http) decorator = appengine.oauth2decorator_from_clientsecrets( CLIENT_SECRETS, scope='https://www.google.com/calendar/feeds/', message='MISSING_CLIENT_SECRETS_MESSAGE') logging.info("decorator.callback_path is %s" % decorator.callback_path) logging.info("decorator.callback_handler() is %s" % decorator.callback_handler()) class Event(ndb.Model): eName = ndb.StringProperty() eLocation = ndb.StringProperty() eDate = ndb.DateProperty() eTime = ndb.StringProperty() eDetails = ndb.TextProperty()
from apiclient import discovery from oauth2client import appengine from oauth2client import client from google.appengine.api import memcache import httplib2 import plangroup CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json') http = httplib2.Http(memcache) service = discovery.build('calendar', 'v3', http=http) decorator = appengine.oauth2decorator_from_clientsecrets( CLIENT_SECRETS, scope=[ 'https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/calendar.readonly', ], message='uh oh') def get_calendar_list(): calendarList = service.calendarList().list().execute(http=decorator.http()) return calendarList['items'] def get_calendar_from_calendar_id(the_calendar_id): calendar = service.calendars().get(calendarId=the_calendar_id).execute(http=decorator.http()) return calendar def get_events_from_calendar_id(the_calendar_id, the_start_date=None, the_end_date=None):
import webapp2 from apiclient import discovery from oauth2client import appengine from oauth2client import client from google.appengine.api import memcache TEMPLATE_DIR = os.path.join(os.path.dirname(__file__), 'templates') JINJA_ENV = jinja2.Environment(loader=jinja2.FileSystemLoader(TEMPLATE_DIR), autoescape=True) CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json') http = httplib2.Http(memcache) service = discovery.build("drive", "v2", http=http) decorator = appengine.oauth2decorator_from_clientsecrets( CLIENT_SECRETS, scope='https://www.googleapis.com/auth/drive', message='NO CLIENT SECRET MESSAGE FOUND') class BaseHandler(webapp2.RequestHandler): def render_str(self, template, params): t = JINJA_ENV.get_template(template) return t.render(params) def render(self, template, kw): self.response.out.write(self.render_str(template, kw)) class IndexHandler(BaseHandler): @decorator.oauth_required
from google.appengine.api import memcache socket.setdefaulttimeout(60) http = httplib2.Http(cache=memcache if USE_APPENGINE else None) JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), autoescape=True, extensions=['jinja2.ext.autoescape']) client_secrets = os.path.join(os.path.dirname(__file__), 'client_secrets.json') if USE_APPENGINE and REQUIRE_OAUTH: decorator = appengine.oauth2decorator_from_clientsecrets( client_secrets, scope=[ 'https://www.googleapis.com/auth/genomics', ]) else: class FakeOauthDecorator(): def http(self): return http def oauth_aware(self, method): return method @property def callback_path(self): return '/unused' def callback_handler(self): pass decorator = FakeOauthDecorator()
import httplib2 import pickle JINJA_ENVIRONMENT = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), ''))) logging.getLogger().setLevel(logging.DEBUG) CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json') logging.info('CLIENT_SECRETS is ' + CLIENT_SECRETS) http = httplib2.Http(memcache) service = discovery.build("calendar", "v3", http=http) decorator = appengine.oauth2decorator_from_clientsecrets( CLIENT_SECRETS, scope='https://www.google.com/calendar/feeds/', message='MISSING_CLIENT_SECRETS_MESSAGE') logging.info("decorator.callback_path is %s" % decorator.callback_path) logging.info("decorator.callback_handler() is %s" % decorator.callback_handler()) class Event(ndb.Model): eName = ndb.StringProperty() eLocation = ndb.StringProperty() eDate = ndb.DateProperty() eTime = ndb.StringProperty() eDetails = ndb.TextProperty() class Helper():
from apiclient.discovery import build from oauth2client.appengine import oauth2decorator_from_clientsecrets from oauth2client.client import AccessTokenRefreshError from google.appengine.api import memcache jinja_environment = jinja2.Environment( loader=jinja2.FileSystemLoader('templates')) CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'config/client_secrets.json') MISSING_CLIENT_SECRETS_MESSAGE = "Please configure the OAuth 2.0 file found at: %s" % CLIENT_SECRETS http = httplib2.Http(memcache) service = build("latitude", "v1", http=http) decorator = oauth2decorator_from_clientsecrets( CLIENT_SECRETS, scope='https://www.googleapis.com/auth/latitude.current.best', message=MISSING_CLIENT_SECRETS_MESSAGE) class MainHandler(webapp2.RequestHandler): def get(self): template_values = {} template = jinja_environment.get_template('index.html') self.response.out.write(template.render(template_values)) class StepOneHandler(webapp2.RequestHandler): def get(self): user = users.get_current_user() template_values = { 'name': user.nickname(),
# Helpful message to display in the browser if the CLIENT_SECRETS file # is missing. MISSING_CLIENT_SECRETS_MESSAGE = """ <h1>Warning: Please configure OAuth 2.0</h1> <p> 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 SCOPE = 'https://www.googleapis.com/auth/calendar.readonly' """OAuth scope""" logging.info("OAuth scope: {0}".format(SCOPE)) http = httplib2.Http(memcache) service = build("calendar", "v3", http=http) decorator = oauth2decorator_from_clientsecrets( CLIENT_SECRETS, scope=SCOPE, message=MISSING_CLIENT_SECRETS_MESSAGE) template_dir = os.path.join(os.path.dirname(__file__), '../templates/') logging.info('Loading templates from: {0}'.format(template_dir)) template_engine = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir))
logging.INFO, "\033[0;32m%s\033[0m\t" % logging.getLevelName(logging.INFO)) logging.addLevelName( logging.DEBUG, "\033[0;36m%s\033[0m\t" % logging.getLevelName(logging.DEBUG)) JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader('templates'), autoescape=True, extensions=['jinja2.ext.autoescape']) client_secrets = os.path.join(os.path.dirname(__file__), 'client_secrets.json') decorator = appengine.oauth2decorator_from_clientsecrets( client_secrets, scope=[ 'https://www.googleapis.com/auth/genomics', 'https://www.googleapis.com/auth/devstorage.read_write' ]) class GenomicsCoverageStatistics(db.Model): """Holds the calculated genomics coverage statistics. """ __SEP = ".." __NEXT = "./" readsetId = db.StringProperty() sequenceName = db.StringProperty() sequence = db.IntegerProperty() coverage = db.IntegerProperty()
import webapp2 import bqclient from gviz_data_table import encode from gviz_data_table import Table from google.appengine.api import memcache from google.appengine.ext.webapp.template import render CLIENT_SECRETS_FILE = os.path.join(os.path.dirname(__file__), 'client_secrets.json') SCOPES = [ 'https://www.googleapis.com/auth/bigquery' ] decorator = oauth2decorator_from_clientsecrets( filename=CLIENT_SECRETS_FILE, scope=SCOPES, cache=memcache) CLIENT_SECRETS = load_clientsecrets_from_file(CLIENT_SECRETS_FILE) # Project ID for a project where you and your users # are viewing members. This is where the bill will be sent. # During the limited availability preview, there is no bill. BILLING_PROJECT_ID = CLIENT_SECRETS[1]['client_id'][:CLIENT_SECRETS[1]['client_id'].find('-')] DATA_PROJECT_ID = 'publicdata' DATASET = 'samples' TABLE = 'natality' QUERY = '''SELECT state, SUM(gestation_weeks) / COUNT(gestation_weeks) as weeks FROM {data_project_id}:{dataset}.{the_table} WHERE year > 1990 AND year < 2005 AND IS_EXPLICITLY_DEFINED(gestation_weeks) GROUP BY state
ACTION_QUEUE = Actionqueue(actions = []) ACTION_QUEUE.put() MISSING_CLIENT_SECRETS_MESSAGE = """ <h1>Warning: Please configure OAuth 2.0</h1> <p> 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 http = httplib2.Http(memcache) service = discovery.build("plus", "v1", http=http) decorator = appengine.oauth2decorator_from_clientsecrets( CLIENT_SECRETS, # take care about the scope, we need: # 1. login authorization # 2. Not only access user's profile, but also friends' profiles, so plus.me does not suffice scope=['https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/plus.profile.emails.read', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'profile'], message=MISSING_CLIENT_SECRETS_MESSAGE)
from google.appengine.api import memcache from google.appengine.ext import webapp from google.appengine.ext.webapp import template # Project ID for your BigQuery Project in the API Console PROJECT_ID = '[YOUR PROJECT ID]' # CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this # application, including client_id and client_secret, which are found # on the API Access tab on the Google APIs # Console <http://code.google.com/apis/console> CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json') decorator = oauth2decorator_from_clientsecrets( filename=CLIENT_SECRETS, scope='https://www.googleapis.com/auth/bigquery', message=template.render( os.path.join(os.path.dirname(__file__), 'templates/error.html'), {'clientSecrets': CLIENT_SECRETS})) BQ = bigqueryv2.BigQueryClient(PROJECT_ID) class MainHandler(webapp.RequestHandler): """Display the index page.""" @decorator.oauth_aware def get(self): """Main handler. Displays index page if logged in. Otherwise, starts OAuth 2.0 dance.
<p> 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 http = httplib2.Http(memcache) service = build("calendar", "v3", http=http) decorator = oauth2decorator_from_clientsecrets( CLIENT_SECRETS, 'https://www.googleapis.com/auth/calendar', MISSING_CLIENT_SECRETS_MESSAGE) class HorasSindicales(BaseHandler): @decorator.oauth_required def get(self): self.execute() self.render(__file__) @decorator.oauth_required def post(self): try: self.execute() #=================================================================== # self.response.out.write(json.dumps({ "hoja" : self.context["hoja"],
# CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this # application, including client_id and client_secret, which may be downloaded # from API Access tab on the Google APIs Console <http://code.google.com/apis/console> CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json') # Load the secret that is used for client side sessions # Create one of these for yourself with, for example: # python -c "import os; print os.urandom(64)" > session.secret SESSION_SECRET = open('session.secret').read() http = httplib2.Http(memcache) user_service = build('plus','v1',http=http) decorator = oauth2decorator_from_clientsecrets( CLIENT_SECRETS, scope="https://www.googleapis.com/auto/plus.me", message="couldnt get user" ) def get_full_url(request_handler, path): """Return the full url from the provided request handler and path.""" pr = urlparse(request_handler.request.url) return '%s://%s%s' % (pr.scheme, pr.netloc, path) def load_session_credentials(request_handler): """Load credentials from the current session.""" session = sessions.LilCookies(request_handler, SESSION_SECRET) userid = session.get_secure_cookie(name='userid') if userid: return userid, StorageByKeyName(Credentials, userid, 'credentials').get()
from google.appengine.api import memcache from google.appengine.ext import webapp from google.appengine.ext.webapp import template # Project ID for your BigQuery Project in the API Console PROJECT_ID = '[YOUR PROJECT ID]' # CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this # application, including client_id and client_secret, which are found # on the API Access tab on the Google APIs # Console <http://code.google.com/apis/console> CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json') decorator = oauth2decorator_from_clientsecrets( filename=CLIENT_SECRETS, scope='https://www.googleapis.com/auth/bigquery', message=template.render( os.path.join(os.path.dirname(__file__), 'templates/error.html'), {'clientSecrets': CLIENT_SECRETS})) BQ = bigqueryv2.BigQueryClient(PROJECT_ID) class MainHandler(webapp.RequestHandler): """Display the index page.""" @decorator.oauth_aware def get(self): """Main handler. Displays index page if logged in. Otherwise, starts OAuth 2.0 dance. """
import webapp2 import jinja2 ROOT_DIR = os.path.dirname(__file__) CLIENT_SECRETS = os.path.join(ROOT_DIR, 'client_secrets.json') jinja_env = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.join(ROOT_DIR, 'templates')), extensions=['jinja2.ext.autoescape']) http = httplib2.Http(memcache) service = build("analytics", "v3", http=http) decorator = oauth2decorator_from_clientsecrets( CLIENT_SECRETS, scope=[ 'https://www.googleapis.com/auth/analytics', 'https://www.googleapis.com/auth/analytics.readonly', ], message="") def dtos(date): return date.strftime("%Y-%m-%d") class MainHandler(webapp2.RequestHandler): @decorator.oauth_required def get(self): req = service.management().profiles().list(accountId="~all", webPropertyId="~all") resp = req.execute(http=decorator.http()) d = json.dumps(resp) template = jinja_env.get_template('home.html')
from oauth2client.appengine import oauth2decorator_from_clientsecrets from oauth2client.client import AccessTokenRefreshError from google.appengine.api import memcache from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp import template jinja_environment = jinja2.Environment( autoescape=False, extensions=['jinja2.ext.autoescape'], loader=jinja2.FileSystemLoader(os.path.dirname(__file__))) CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json') service = build("drive", "v2") decorator = oauth2decorator_from_clientsecrets( CLIENT_SECRETS, scope='https://www.googleapis.com/auth/drive') def Redirect(req, msg, url): """Redirects to a URL after 100ms, first displaying a message. Args: req: The webapp2.RequestHandler object used to redirect. msg: The message to display. url: The URL to redirect to. """ tpl = "%s <script>setTimeout(function(){ window.location.href='%s';}, 100);\ </script>" req.response.out.write(tpl % (msg, url)) def ListFiles(http, folderId):
MISSING_CLIENT_SECRETS_MESSAGE = """ <h1>Warning: Please configure OAuth 2.0</h1> <p> 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 decorator = appengine.oauth2decorator_from_clientsecrets( CLIENT_SECRETS, scope=['https://www.googleapis.com/auth/calendar'], message=MISSING_CLIENT_SECRETS_MESSAGE) """decorator = OAuth2Decorator( client_id='*****@*****.**', client_secret='pbg2Xex8QjZDbmSTSgMaUKng', scope='https://www.googleapis.com/auth/calendar')""" class zoho_integrate(session_handler.BaseSessionHandler): def getTaskList(self): module_name = 'Tasks' authtoken = '7b64e8f8c6a3039b0e8199e02cdcca6b' params = {'authtoken': authtoken, 'scope': 'crmapi'} final_URL = 'https://crm.zoho.com/crm/private/json/' + [ module_name ] + '/getRecords'
# Project ID for a project where you and your users # are viewing members. This is where the bill will be sent. # During the limited availability preview, there is no bill. # Replace this value with the Client ID value from your project, # the same numeric value you used in client_secrets.json BILLING_PROJECT_ID = "475473128136" DATA_PROJECT_ID = "publicdata" DATASET = "samples" TABLE = "natality" QUERY = """ select state, SUM(gestation_weeks) / COUNT(gestation_weeks) as weeks from publicdata:samples.natality where year > 1990 and year < 2005 and IS_EXPLICITLY_DEFINED(gestation_weeks) group by state order by weeks """ decorator = oauth2decorator_from_clientsecrets(CLIENT_SECRETS, 'https://www.googleapis.com/auth/bigquery') class InfoHandler(webapp2.RequestHandler): @decorator.oauth_aware def get(self): self.response.out.write(decorator.authorize_url()) class MainHandler(webapp2.RequestHandler): def _bq4geo(self, bqdata): """geodata output for region maps must be in the format region, value. Assume the BigQuery query output is in this format and get names from schema. """ columnNameGeo = bqdata["schema"]["fields"][0]["name"] columnNameVal = bqdata["schema"]["fields"][1]["name"] #logging.info("Column Names=%s, %s" % (columnNameGeo, columnNameVal))
""" % CLIENT_SECRETS http = httplib2.Http(memcache) service = build("calendar", "v3", http=http) # Set up an OAuth2Decorator object to be used for authentication. Add one or # more of the following scopes in the scopes parameter below. PLEASE ONLY ADD # THE SCOPES YOU NEED. For more information on using scopes please see # <https://developers.google.com/+/best-practices>. decorator = oauth2decorator_from_clientsecrets( CLIENT_SECRETS, scope=[ 'https://www.googleapis.com/auth/calendar.readonly', 'https://www.googleapis.com/auth/calendar', ], message=MISSING_CLIENT_SECRETS_MESSAGE) class MainHandler(webapp.RequestHandler): @decorator.oauth_required def get(self): self.response.out.write("""<html><body> <p>Congratulations, you are up and running! At this point you will want to add calls into the Calendar API to the <code>main.py</code> file. Please read the <code>main.py</code> file carefully, it contains detailed information in the comments. For more information on the Calendar API Python library surface you can visit: </p>
import os from oauth2client.appengine import oauth2decorator_from_clientsecrets import webapp2 import bqclient from gviz_data_table import encode from gviz_data_table import Table from google.appengine.api import memcache from google.appengine.ext.webapp.template import render CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json') SCOPES = ['https://www.googleapis.com/auth/bigquery'] decorator = oauth2decorator_from_clientsecrets(filename=CLIENT_SECRETS, scope=SCOPES, cache=memcache) # Project ID for a project where you and your users # are viewing members. This is where the bill will be sent. # During the limited availability preview, there is no bill. # Replace this value with the Client ID value from your project, # the same numeric value you used in client_secrets.json BILLING_PROJECT_ID = "475473128136" DATA_PROJECT_ID = "publicdata" DATASET = "samples" TABLE = "natality" QUERY = ("select state," "SUM(gestation_weeks) / COUNT(gestation_weeks) as weeks " "from %s:%s.%s " "where year > 1990 and year < 2005 "
# CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this # application, including client_id and client_secret, which are found # on the API Access tab on the Google APIs # Console <http://code.google.com/apis/console> CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), "client_secrets.json") # Helpful message to display in the browser if the CLIENT_SECRETS file # is missing. CS_TEMPLATE = JINJA_ENVIRONMENT.get_template("templates/missing_client.html") CS_MESSAGE = CS_TEMPLATE.render({ "client_secrets": CLIENT_SECRETS }) decorator = appengine.oauth2decorator_from_clientsecrets( CLIENT_SECRETS, scope="https://www.googleapis.com/auth/mapsengine", message=CS_MESSAGE) class RenderHandler(webapp2.RequestHandler): """Generic handler class with helper methods for others to subclass.""" def Render(self, template, params): """Generic render method to save boilerplate in other get requests. Args: template: str, The name of the template file. params: dict, The variables for the template. """ template = JINJA_ENVIRONMENT.get_template("templates/%s" % template)
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 http = httplib2.Http(memcache) service = discovery.build("plus", "v1", http=http) decorator = appengine.oauth2decorator_from_clientsecrets( CLIENT_SECRETS, scope='https://www.googleapis.com/auth/plus.me', message=MISSING_CLIENT_SECRETS_MESSAGE) class MainHandler(webapp2.RequestHandler): @decorator.oauth_aware def get(self): variables = { 'url': decorator.authorize_url(), 'has_credentials': decorator.has_credentials() } template = JINJA_ENVIRONMENT.get_template('grant.html') self.response.write(template.render(variables)) class AboutHandler(webapp2.RequestHandler):
<p>You can find the Client ID and Client secret values on the API Access tab in the <a href="https://code.google.com/apis/console">APIs Console</a>. </p> """ % CLIENT_SECRETS http = httplib2.Http(memcache) service = build("youtube", "v3", http=http) # Set up an OAuth2Decorator object to be used for authentication. Add one or # more of the following scopes in the scopes parameter below. PLEASE ONLY ADD # THE SCOPES YOU NEED. For more information on using scopes please see # <https://developers.google.com/+/best-practices>. decorator = oauth2decorator_from_clientsecrets( CLIENT_SECRETS, scope='https://www.googleapis.com/auth/youtube', message=MISSING_CLIENT_SECRETS_MESSAGE) class MainHandler(webapp.RequestHandler): @decorator.oauth_required def get(self): self.response.out.write("""<html><body> <p>Congratulations, you are up and running! At this point you will want to add calls into the YouTube Data API to the <code>main.py</code> file. Please read the <code>main.py</code> file carefully, it contains detailed information in the comments. For more information on the YouTube Data API Python library surface you can visit: </p> <blockquote>
<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 http = httplib2.Http(memcache) service = discovery.build('drive', 'v2', http=http) decorator = appengine.oauth2decorator_from_clientsecrets( CLIENT_SECRETS, scope=[ 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.appdata', 'https://www.googleapis.com/auth/drive.apps.readonly', 'https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/drive.metadata.readonly', 'https://www.googleapis.com/auth/drive.readonly', 'https://www.googleapis.com/auth/drive.scripts', ], message=MISSING_CLIENT_SECRETS_MESSAGE) class MainHandler(webapp2.RequestHandler): @decorator.oauth_aware def get(self): variables = { 'url': decorator.authorize_url(), 'has_credentials': decorator.has_credentials() } template = JINJA_ENVIRONMENT.get_template('main.html')
href="https://code.google.com/apis/console">APIs Console</a>. </p> """ % CLIENT_SECRETS http = httplib2.Http(memcache) service = build("calendar", "v3", http=http) # Set up an OAuth2Decorator object to be used for authentication. Add one or # more of the following scopes in the scopes parameter below. PLEASE ONLY ADD # THE SCOPES YOU NEED. For more information on using scopes please see # <https://developers.google.com/+/best-practices>. decorator = oauth2decorator_from_clientsecrets( CLIENT_SECRETS, scope=[ 'https://www.googleapis.com/auth/calendar.readonly', 'https://www.googleapis.com/auth/calendar', ], message=MISSING_CLIENT_SECRETS_MESSAGE) class MainHandler(webapp.RequestHandler): @decorator.oauth_required def get(self): self.response.out.write("""<html><body> <p>Congratulations, you are up and running! At this point you will want to add calls into the Calendar API to the <code>main.py</code> file. Please read the <code>main.py</code> file carefully, it contains detailed information in the comments. For more information on the Calendar API Python library surface you can visit: </p>
href="https://code.google.com/apis/console">APIs Console</a>. </p> """ % CLIENT_SECRETS http = httplib2.Http(memcache) # Load the local copy of the discovery document f = file(os.path.join(os.path.dirname(__file__), "plus.v1whitelisted.rest.json"), "r") discovery_doc = f.read() f.close() service = build_from_document(discovery_doc, base="https://www.googleapis.com/", http=http) calendar_service = build("calendar", "v3", http=http) # service = build("plus", "dogfood", http=http, discoveryServiceUrl='https://www-googleapis-staging.sandbox.google.com/discovery/v1/apis/plus/dogfood/rest') decorator = oauth2decorator_from_clientsecrets( CLIENT_SECRETS, scope='https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/plus.profiles.read https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.readonly', message=MISSING_CLIENT_SECRETS_MESSAGE) def user_required(method): """Decorator for making sure the User entity is created for the user""" def _user_required(request_handler): user = users.get_current_user() u = User.get_by_key_name(user.email()) if not u: u = User(email=user.email(),user_id=user.user_id()) u.put() method(request_handler) return _user_required