def setUp(self): self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_datastore_v3_stub() self.testbed.init_memcache_stub() self.testbed.init_user_stub() decorator = OAuth2Decorator(client_id='foo_client_id', client_secret='foo_client_secret', scope=['foo_scope', 'bar_scope'], user_agent='foo') self.decorator = decorator class TestRequiredHandler(webapp.RequestHandler): @decorator.oauth_required def get(self): pass class TestAwareHandler(webapp.RequestHandler): @decorator.oauth_aware def get(self): self.response.out.write('Hello World!') application = webapp.WSGIApplication([('/oauth2callback', OAuth2Handler), ('/foo_path', TestRequiredHandler), ('/bar_path', TestAwareHandler)], debug=True) self.app = TestApp(application) users.get_current_user = UserMock self.httplib2_orig = httplib2.Http httplib2.Http = Http2Mock
def test_kwargs_are_passed_to_underlying_flow(self): decorator = OAuth2Decorator(client_id='foo_client_id', client_secret='foo_client_secret', user_agent='foo_user_agent', scope=['foo_scope', 'bar_scope'], access_type='offline', approval_prompt='force') self.assertEqual('offline', decorator.flow.params['access_type']) self.assertEqual('force', decorator.flow.params['approval_prompt']) self.assertEqual('foo_user_agent', decorator.flow.user_agent) self.assertEqual(None, decorator.flow.params.get('user_agent', None))
def to(cls, to_path, scopes=None): """Override this since we need to_path to instantiate the oauth decorator. """ global oauth_decorator if oauth_decorator is None: oauth_decorator = OAuth2Decorator( client_id=appengine_config.GOOGLE_CLIENT_ID, client_secret=appengine_config.GOOGLE_CLIENT_SECRET, scope=cls.make_scope_str(scopes, separator=' '), callback_path=to_path, # make sure we ask for a refresh token so we can use it to get an access # token offline. requires prompt=consent! more: # ~/etc/google+_oauth_credentials_debugging_for_plusstreamfeed_bridgy # http://googleappsdeveloper.blogspot.com.au/2011/10/upcoming-changes-to-oauth-20-endpoint.html access_type='offline', prompt='consent', # https://developers.google.com/accounts/docs/OAuth2WebServer#incrementalAuth include_granted_scopes='true') class Handler(cls): @oauth_decorator.oauth_required def get(self): assert ( appengine_config.GOOGLE_CLIENT_ID and appengine_config.GOOGLE_CLIENT_SECRET ), ("Please fill in the google_client_id and google_client_secret files in " "your app's root directory.") # get OpenID Connect user info # https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims try: _, user = oauth_decorator.http().request( OPENID_CONNECT_USERINFO) except BaseException as e: util.interpret_http_exception(e) raise user = json.loads(user.decode('utf-8')) logging.debug('Got one person: %r', user) store = oauth_decorator.credentials.store creds_model_key = ndb.Key(store._model.kind(), store._key_name) auth = GoogleAuth(id=user['sub'], creds_model=creds_model_key, user_json=json.dumps(user)) auth.put() self.finish(auth, state=self.request.get('state')) @oauth_decorator.oauth_required def post(self): return self.get() return Handler
def setUp(self): self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_datastore_v3_stub() self.testbed.init_memcache_stub() self.testbed.init_user_stub() decorator = OAuth2Decorator(client_id='foo_client_id', client_secret='foo_client_secret', scope=['foo_scope', 'bar_scope'], user_agent='foo') self._finish_setup(decorator, user_mock=UserMock)
def test_kwargs_are_passed_to_underlying_flow(self): decorator = OAuth2Decorator(client_id='foo_client_id', client_secret='foo_client_secret', user_agent='foo_user_agent', scope=['foo_scope', 'bar_scope'], access_type='offline', approval_prompt='force', revoke_uri='dummy_revoke_uri') request_handler = MockRequestHandler() decorator._create_flow(request_handler) self.assertEqual('https://example.org/oauth2callback', decorator.flow.redirect_uri) self.assertEqual('offline', decorator.flow.params['access_type']) self.assertEqual('force', decorator.flow.params['approval_prompt']) self.assertEqual('foo_user_agent', decorator.flow.user_agent) self.assertEqual('dummy_revoke_uri', decorator.flow.revoke_uri) self.assertEqual(None, decorator.flow.params.get('user_agent', None))
from apiclient import discovery, errors from datetime import datetime from copy import deepcopy from random import randint from oauth2client.appengine import OAuth2Decorator from google.appengine.api import users, mail from google.appengine.ext import db with open('secrets', 'r') as f: c_id, c_secret = f.read().split('\n') decorator = OAuth2Decorator( client_id=c_id, client_secret=c_secret, scope='https://www.googleapis.com/auth/calendar', access_type='offline', approval_prompt='force') service = discovery.build('calendar', 'v3') template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True) #list of campuses' calendar id campuses = { 'iskl_ms': ["*****@*****.**", "08:00"], 'iskl_es': ["*****@*****.**", "08:00"]} #list of form element names
from activitystreams import activitystreams import appengine_config import models from webutil import util from oauth2client.appengine import OAuth2Decorator from gdata.blogger import client from gdata import gauth from google.appengine.api import users from google.appengine.ext import db import webapp2 oauth = OAuth2Decorator( client_id=appengine_config.GOOGLE_CLIENT_ID, client_secret=appengine_config.GOOGLE_CLIENT_SECRET, # https://developers.google.com/blogger/docs/2.0/developers_guide_protocol#OAuth2Authorizing # (the scope for the v3 API is https://www.googleapis.com/auth/blogger) scope='http://www.blogger.com/feeds/', callback_path='/blogger/oauth2callback') class Blogger(models.Destination): """A Blogger blog. The key name is the blog hostname.""" owner_name = db.StringProperty(required=True) # the App Engine user id, ie users.get_current_user().user_id() gae_user_id = db.StringProperty(required=True) def hostname(self): return self.key().name()
import re import urllib import webapp2 from app.controller.base_controller import BaseController from app.helper import template_helper from app.model import page_model from bs4 import BeautifulSoup from oauth2client.appengine import OAuth2Decorator from random import randint from time import sleep # set up decorator decorator = OAuth2Decorator( client_id=config.client_id, client_secret=config.client_secret, scope= 'https://docs.googleusercontent.com/ https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/userinfo.email' ) # our item classes class BaseGItem(object): def __init__(self, item): self.g_id = item['id'] self.title = item['title'] self.name = re.sub(r'[^\w\d]+', '_', item['title'].lower()) class GFolder(BaseGItem): def __init__(self, item): BaseGItem.__init__(self, item)
#from google.appengine.ext import webapp from oauth2client.appengine import OAuth2Decorator from google.appengine.api import urlfetch urlfetch.set_default_fetch_deadline(45) #FLAGS = gflags.FLAGS email = '*****@*****.**' password = '******' spreadsheet_key = '1R3zLvtKxllRM71PdCDQu9XhNYo7xmf0On49WreyLi24' # key param worksheet_id = 'od6' # default decorator = OAuth2Decorator( client_id= '97297373612-mvc0t7e42nblkricfi4sn6tfcqqptjo2.apps.googleusercontent.com', client_secret='qbtiG-fyhN9iTucuu8OBdC98', scope='https://www.googleapis.com/auth/calendar') service = build('calendar', 'v3', developerKey='AIzaSyDwEDO-Qa3ep2l6kP2e_r6ivjKF28D6LXk') class MainHandler(webapp2.RequestHandler): @decorator.oauth_required def get(self): # Get the authorized Http object created by the decorator. http = decorator.http() #credentials = AppAssertionCredentials(scope='https://www.googleapis.com/auth/devstorage.read_write') #http = credentials.authorize(httplib2.Http(memcache))
import os import pickle from apiclient.discovery import build from oauth2client.appengine import OAuth2Decorator from oauth2client.client import AccessTokenRefreshError from google.appengine.api import memcache from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app # The client_id and client_secret are copied from the API Access tab on # the Google APIs Console <http://code.google.com/apis/console> decorator = OAuth2Decorator( client_id= '837647042410-75ifgipj95q4agpm0cs452mg7i2pn17c.apps.googleusercontent.com', client_secret='QhxYsjM__u4vy5N0DXUFRwwI', scope='https://www.googleapis.com/auth/buzz', user_agent='my-sample-app/1.0') http = httplib2.Http(memcache) service = build("buzz", "v1", http=http) class MainHandler(webapp.RequestHandler): @decorator.oauth_aware def get(self): path = os.path.join(os.path.dirname(__file__), 'grant.html') variables = { 'url': decorator.authorize_url(), 'has_credentials': decorator.has_credentials() }
# Other constants NUM_FEATURES = 1 # Define API calls # Creates a trained model API_INSERT = 'https://www.googleapis.com/prediction/v1.6/projects/%(project_id)s/trainedmodels' % { 'project_id': PROJECT_ID } API_GET = 'https://www.googleapis.com/prediction/v1.6/projects/%(project_id)s/trainedmodels/%(model_id)s' % { 'project_id': PROJECT_ID, 'model_id': MODEL_ID } decorator = OAuth2Decorator(client_id=OAUTH_CLIENT_ID, client_secret=OAUTH_CLIENT_SECRET, scope=OAUTH_SCOPE) http = httplib2.Http(memcache) service = build('prediction', 'v1.6', http=http) class Prediction(webapp2.RequestHandler): @decorator.oauth_aware def get(self): if decorator.has_credentials(): self.response.headers['Content-Type'] = 'text/plain' self.response.write('prediction\n') else: self.redirect(decorator.authorize_url())
from login import Login from apiclient import errors from apiclient.http import MediaFileUpload JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.FileSystemLoader( os.path.dirname(__file__)), extensions=['jinja2.ext.autoescape'], autoescape=True) INSTANCE_NAME = "gcdc2013-easyquiz:quiz1" DATABASE = "quizdb" decorator = OAuth2Decorator( client_id= '808381301213-rgl6qcaiabgqtg58aihcmth32ud9purv.apps.googleusercontent.com', client_secret='l7T9EGbQ4q9tfhRvRLm4VB0D', scope= 'https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/calendar' ) service = build('drive', 'v2') calendar_service = build('calendar', 'v3') MIME_FOLDER = "application/vnd.google-apps.folder" MIME_DOC = "application/vnd.google-apps.document" MIME_SHEET = "application/vnd.google-apps.spreadsheet" MIME_PRESENT = "application/vnd.google-apps.presentation" class Main(webapp2.RequestHandler): @decorator.oauth_required
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides oauth2 decorators in a mockable way.""" from oauth2client.appengine import OAuth2Decorator from dashboard import utils DECORATOR = OAuth2Decorator( client_id='425761728072.apps.googleusercontent.com', client_secret='9g-XlmEFW8ROI01YY6nrQVKq', scope=utils.EMAIL_SCOPE, message='Oauth error occurred!', callback_path='/oauth2callback')
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides oauth2 decorators in a mockable way.""" from oauth2client.appengine import OAuth2Decorator DECORATOR = OAuth2Decorator( client_id='425761728072.apps.googleusercontent.com', client_secret='9g-XlmEFW8ROI01YY6nrQVKq', scope=[ 'https://www.googleapis.com/auth/projecthosting', 'https://www.googleapis.com/auth/userinfo.email' ], message='Oauth error occurred!', callback_path='/oauth2callback')
# import webapp2 import jinja2 import os import cgi from google.appengine.api import mail from google.appengine.api import users from google.appengine.api import rdbms from apiclient.discovery import build import json from oauth2client.appengine import OAuth2Decorator from apiclient.http import MediaFileUpload import datetime decorator = OAuth2Decorator( client_id='1084112190775.apps.googleusercontent.com', client_secret='p24Uy-IqgZ_OyqzsqokOobBV', scope='https://www.googleapis.com/auth/calendar') service = build('calendar', 'v3') JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.FileSystemLoader( os.path.dirname(__file__)), extensions=['jinja2.ext.autoescape']) _INSTANCE_NAME = "prinya-th-2013:prinya-db" class MainHandler(webapp2.RequestHandler): @decorator.oauth_required def get(self): # student_id = self.request.get('student_id'); student_id = "2"
from googleapiclient import errors from google.appengine.api import users from google_directory_service import GoogleDirectoryService import logging from oauth2client.appengine import OAuth2Decorator # TODO(eholder): Add tests for this. Probably should test that we only # request the scopes we need and that the decorator is called with the # id and secret as intended. USER = '******' GROUP = 'https://www.googleapis.com/auth/admin.directory.group.readonly' MEMBER = 'https://www.googleapis.com/auth/admin.directory.group.member.readonly' SCOPES = [USER, GROUP, MEMBER] OAUTH_DECORATOR = OAuth2Decorator( client_id=OAuth.GetOrInsertDefault().client_id, client_secret=OAuth.GetOrInsertDefault().client_secret, scope=SCOPES) def AbortIfUserIsNotLoggedIn(self, user): """Check if the user is logged in and abort if not. Args: user: The user to check for being logged in. """ if not user or user is None: logging.error('User is not logged in.') self.abort(403) def AbortIfUserIsNotAppAdmin(self):
from apiclient.errors import HttpError from oauth2client.appengine import CredentialsModel from oauth2client.appengine import OAuth2Decorator from oauth2client.appengine import StorageByKeyName from google.appengine.api import users from google.appengine.ext import db from google.appengine.ext.webapp import template import webapp2 # service names and versions: # https://developers.google.com/api-client-library/python/reference/supported_apis json_service = discovery.build('plus', 'v1') oauth = OAuth2Decorator( client_id=appengine_config.GOOGLE_CLIENT_ID, client_secret=appengine_config.GOOGLE_CLIENT_SECRET, # G+ scopes: https://developers.google.com/+/api/oauth#oauth-scopes scope='https://www.googleapis.com/auth/plus.me', callback_path='/googleplus/oauth2callback') class GooglePlus(models.Source): """A Google+ account. The key name is the Google+ user id.""" DOMAIN = 'googleplus.com' name = db.StringProperty(required=True) # the App Engine user id, ie users.get_current_user().user_id() gae_user_id = db.StringProperty(required=True) def display_name(self): return self.name
# 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. from google.appengine.dist import use_library use_library('django', '1.2') from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app from apiclient.discovery import build import httplib2 from oauth2client.appengine import OAuth2Decorator import settings decorator = OAuth2Decorator(client_id=settings.CLIENT_ID, client_secret=settings.CLIENT_SECRET, scope=settings.SCOPE, user_agent='mytasks') class MainHandler(webapp.RequestHandler): @decorator.oauth_aware def get(self): if decorator.has_credentials(): service = build('tasks', 'v1', http=decorator.http()) result = service.tasks().list(tasklist='@default').execute() tasks = result.get('items', []) for task in tasks: task['title_short'] = truncate(task['title'], 26) self.response.out.write(template.render('templates/index.html', {'tasks': tasks}))
from compute_engine_controller import ComputeEngineController from load_info import LoadInfo from google.appengine.ext import db from google.appengine.api import app_identity jinja_environment = jinja2.Environment( loader=jinja2.FileSystemLoader('worker')) jinja_environment_html = jinja2.Environment( loader=jinja2.FileSystemLoader('static_files')) decorator = OAuth2Decorator( client_id= '996450208987-9259qcm3a6qh8ch15nsf6tpb0jrk2knu.apps.googleusercontent.com', client_secret='DPcR1rc9oZwBBuf6fzgj231a', scope=ComputeEngineController.SCOPE) class IpAddressRequestLog(db.Model): """Datastore schema for game server IP address retrieval log.""" client_ip = db.StringProperty() server_ip = db.StringProperty() timestamp = db.DateTimeProperty(auto_now=True) class LoginToken(db.Model): # Use token as key_name expiration = db.DateTimeProperty() user_id = db.StringProperty()
import datetime import gflags import httplib2 from google.appengine.api import users from google.appengine.api import memcache from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app from oauth2client.appengine import OAuth2Decorator from apiclient.discovery import build #===============================auth related================================================================== decorator = OAuth2Decorator( client_id= '785871267070-bm42i94l35chflm8s1aeus0pfrqqkssg.apps.googleusercontent.com', client_secret='eU6tFA1N5fCbDR1ACbejEUsl', scope='https://www.googleapis.com/auth/calendar', user_agent='review-words/1.0') http = httplib2.Http(memcache) service = build(serviceName='calendar', version='v3', http=http, developerKey='AIzaSyC0CdFe4FZDeF06SAf6UKkko90NAZ8EZbU') #=================================databases=================================================================== #database that store users' plan class Plans(db.Model): plan = db.StringProperty()
from google.appengine.ext import db from oauth2client.appengine import CredentialsProperty from google.appengine.api import users from google.appengine.api import oauth from oauth2client.appengine import StorageByKeyName #Clase de tipo datastore para almacenar la informacion de la credencial del usuario class CredentialsModel(db.Model): credentials = CredentialsProperty() #Creamos un decorator que sirve para manejar Oauth2 (pantalla de consentimiento al usuario para acceder a su informacion) decorator = OAuth2Decorator( client_id= '316673399221-ggs3lp34bnjsa2j59cudbit7nokqmrla.apps.googleusercontent.com', client_secret='R_FY5r1XWhqKyOK-2rNmGOsl', scope='https://www.googleapis.com/auth/youtube') #Funcion para obtener el servicio de youtube def getService(): flow = flow_from_clientsecrets( 'client_secrets.json', scope='https://www.googleapis.com/auth/youtube', redirect_uri='http://localhost:8080/oauth2callback') user = users.get_current_user() storage = StorageByKeyName(CredentialsModel, user.user_id(), 'credentials') credentials = storage.get()
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # 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. # from apiclient.discovery import build from google.appengine.api import users from oauth2client.appengine import OAuth2Decorator import webapp2 decorator = OAuth2Decorator( client_id='411488856174.apps.googleusercontent.com', client_secret='mW3BB9ibX7WiZfSnKSTQJ8X9', scope='https://www.googleapis.com/auth/admin.directory.group') service = build('admin', 'directory_v1') class Main(webapp2.RequestHandler): @decorator.oauth_required def get(self): html = """ <h2>Mailing Group Example</h2> <form method="POST" action="/CreateMailingGroup"> <b>Create Mailing Group</b><br> group name : <input name="name"><br> email for define mailing group : <input name="email"><br>
class BaseHandler(webapp.RequestHandler): """This is the base request handler. It contains code that's common to several request handlers. Some of these things couldn't be broken off into the utils directory because they had too much knowledge of the request handler's environment. """ # The client_id and client_secret are copied from the API Access tab on # the Google APIs Console <http://code.google.com/apis/console> oauth2_decorator = OAuth2Decorator( client_id='205496663185.apps.googleusercontent.com', client_secret='-84bG7a8jGJDRCqD6f8ug_c0', scope=" ".join([ "https://www.googleapis.com/auth/plus.me", "http://gdata.youtube.com" ]), user_agent=app_identity.get_application_id()) def __init__(self): """Set some instance variables. I hate to set these here (especially to None!) because they're actually set in various decorators. However, I'm trying to appease PyCharm because it's really useful to have it statically figure out where stuff is coming from. """ self.current_user_id = None self.current_display_name = None self.people = None self.owner_oauth_token = None self.playlist_uri = None self.playlist_entry_id = None @staticmethod def playlist_entry_uri_required(handler_method): """This is a decorator to parse the uri parameter. Set self.playlist_uri and self.playlist_entry_id. Automatically handle any errors. """ def handle(self, *args, **kargs): uri = self.request.get("uri") match = youtubeutils.PLAYLIST_ENTRY_URL_RE.match(uri) if not match: self.error(400) self.response.out.write("Invalid uri parameter: %s" % escape(uri)) return self.playlist_uri, self.playlist_entry_id = match.groups() return handler_method(self, *args, **kargs) return handle @staticmethod def authorize_playlist(handler_method): """Lookup the playlist and check authorization. The owner of the playlist can always edit the playlist. Other users can only edit the playlist if they have the right uuid in the URL. This decorator wraps handler methods. The handler method must receive a playlist_id argument, and it must use @decorator.oauth_required before this decorator. This decorator will set: - self.playlist_metadata - self.people - self.current_user_id - self.current_display_name - self.owner_oauth_token """ def handle(self, playlist_id): try: self.playlist_metadata = model.PlaylistMetadata.gql( "WHERE playlist_id = :1", playlist_id)[0] except IndexError: self.error(404) self.response.out.write("Party Playlist Picker does not know about playlist %s." % escape(playlist_id)) return if users.get_current_user() != self.playlist_metadata.owner: if self.request.get("uuid", -1) != self.playlist_metadata.uuid: self.error(401) self.response.out.write("You are not authorized to view this page.") return owner_id = self.playlist_metadata.owner.user_id() owner_credentials = StorageByKeyName(CredentialsModel, owner_id, 'credentials').get() self.owner_oauth_token = owner_credentials.access_token try: me = memcacheutils.cache_call( key=self.oauth2_decorator.credentials.access_token, namespace="oauth2_token_to_user", time=memcacheutils.USER_EXPIRATION_SECS, f=lambda: googleplusutils.service.people().get(userId="me").execute( webutils.create_authorized_http_with_timeout( self.oauth2_decorator.credentials))) except HttpError, e: if e.resp['status'] == 404: webutils.render_to_response(self, "no_profile.html") return raise self.current_user_id = me["id"] self.current_display_name = me["displayName"] # TODO: Front some of the following datastore lookups with memcache. query = model.Person.all().filter("user_id = ", me["id"]) person = query.get() if person is None: person = model.Person( user_id=me["id"], display_name=me["displayName"], image_url=me.get("image", {}).get("url", "/static/images/default_profile.jpg"), profile_url=me["url"] ) person.put() query = model.PlaylistEditors.all().filter("playlist_id = ", playlist_id).ancestor(person) if query.get() is None: model.PlaylistEditors(parent=person, playlist_id=playlist_id).put() # We'll probably end up moving this out of the decorator entirely. self.people = [] playlist_editors = model.PlaylistEditors.all().filter("playlist_id = ", playlist_id) for playlist_editor in playlist_editors: person = playlist_editor.parent() self.people.append(dict( user_id=person.user_id, display_name=person.display_name, image_url=person.image_url, profile_url=person.profile_url )) handler_method(self, playlist_id) return handle
GOOGLE_SCOPES = [ # These are the two scopes related to Glass, we'll use both: 'https://www.googleapis.com/auth/glass.timeline', 'https://www.googleapis.com/auth/glass.location', # Include this two if you need more information about the user, # or any other Google OAuth2 scope (drive, google+, ...) # 'https://www.googleapis.com/auth/userinfo.email', # 'https://www.googleapis.com/auth/userinfo.profile' ] # This decorator handle all of the OAuth 2.0 steps without you having to use # any Flow, Credentials, or Storage objects. decorator = OAuth2Decorator( client_id=GOOGLE_CLIENT_ID, client_secret=GOOGLE_CLIENT_SECRET, scope=GOOGLE_SCOPES, # Forces to get a refresh token, fixes { "error" : "invalid_grant" } # approval_prompt='force' ) # The model where we'll store the credentials class CredentialsModel(db.Model): credentials = CredentialsProperty() # We'll use this to execute all calls to the Mirror API service = build('mirror', 'v1') class MainHandler(webapp2.RequestHandler):
from apiclient.discovery import build import httplib2 # Crear una variable estática del entorno de nuestros templates JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.abspath('templates')), autoescape=True, extensions=['jinja2.ext.autoescape'] ) # creación del objeto decorator, objeto utilizado para OAuth2 decorator = OAuth2Decorator( client_id='<TU_ID_DE_CLIENTE>', client_secret='<TU_CLIENTE_SECRETO>', scope='https://www.googleapis.com/auth/userinfo.profile ' + 'https://www.googleapis.com/auth/userinfo.email ', ) # construcción del servicio de userinfo http = httplib2.Http() userinfo_service = build('oauth2', 'v2', http=http) # Una clase controladora de peticiones HTTP (get, post, put, delete) class ControladorInicio(webapp2.RequestHandler): @decorator.oauth_aware def get(self): # validar si el usuario Google esta o no autentificado
from soc.views.helper import url_patterns as soc_url_patterns from soc.modules.gsoc.views import forms from soc.modules.gsoc.views.helper import url_names from soc.modules.gsoc.views.helper import url_patterns from soc.modules.gsoc.views.helper.url_patterns import url from soc.modules.gsoc.views import base from summerofcode.request import links from summerofcode.models import shipment_tracking # TODO(daniel): once Site has been migrated to ndb, update this to make sure # it benefits from ndbs caching mechanisms. site = site_logic.singleton() decorator = OAuth2Decorator(client_id=site.google_client_id, client_secret=site.google_client_secret, scope='https://www.googleapis.com/auth/drive.file') URL_FMT = ("https://docs.google.com/feeds/download/spreadsheets/Export" + "?key=%s&exportFormat=csv&gid=%d") def redirect(self, uri): raise exception.Redirect(uri) class CallbackPage(base.GSoCRequestHandler): """View with the document picker. """ access_checker = access.PROGRAM_ADMINISTRATOR_ACCESS_CHECKER
# -*- coding: utf-8 -*- import webapp2 import os import yaml from apiclient.discovery import build from oauth2client.appengine import OAuth2Decorator from google.appengine.ext import ndb # api.yamlから読み取り api_key = yaml.safe_load(open('api.yaml').read().decode('utf-8')) decorator = OAuth2Decorator( client_id=api_key['client_id'], client_secret=api_key['client_secret'], scope='https://www.googleapis.com/auth/calendar', ) # オブジェクトを生成。build() は JSON のサービス定義ファイルからメソッドを構築するためのもの。 service = build('calendar', 'v3') # add start DEFAULT_GUESTBOOK_NAME = 'default_guestbook' def guestbook_key(guestbook_name=DEFAULT_GUESTBOOK_NAME): """Constructs a Datastore key for a Guestbook entity with guestbook_name.""" return ndb.Key('CalendarRead', guestbook_name)
from google.appengine.api import mail, users from oauth2client.appengine import OAuth2Decorator from pprint import pformat from schema import Gamenight, Invitation, User, Config, Auth from utils import Utils JINJA_ENVIRONMNT = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=['jinja2.ext.autoescape']) config = {x.name: x.value for x in Config.query().fetch()} decorator = OAuth2Decorator( client_id=config.get('client_id'), client_secret=config.get('client_secret'), scope='https://www.googleapis.com/auth/calendar') def admin_only(func): def dec(self, **kwargs): sys_user = users.get_current_user() if not sys_user: self.redirect(users.create_login_url(self.request.uri)) return user = User.lookup(sys_user.email()) if not user or not user.superuser: self.redirect("/invite") return
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # 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. import webapp2 from webapp2_extras import jinja2 from googleapiclient.discovery import build from oauth2client.appengine import OAuth2Decorator import settings decorator = OAuth2Decorator(client_id=settings.CLIENT_ID, client_secret=settings.CLIENT_SECRET, scope=settings.SCOPE) service = build('tasks', 'v1') class MainHandler(webapp2.RequestHandler): def render_response(self, template, **context): renderer = jinja2.get_jinja2(app=self.app) rendered_value = renderer.render_template(template, **context) self.response.write(rendered_value) @decorator.oauth_aware def get(self): if decorator.has_credentials(): result = service.tasks().list(tasklist='@default').execute( http=decorator.http())
#gdocs = gdata.docs.client.DocsClient(source = "gplustimeline") clients = {} clients["youtube"] = gdata.youtube.client.YouTubeClient() #gdata.alt.appengine.run_on_appengine(clients["youtube"]) clients["picasa"] = gdata.photos.service.PhotosService() #gdata.alt.appengine.run_on_appengine(clients["picasa"]) clients["calendar"] = gdata.calendar.client.CalendarClient(source="") #gdata.alt.appengine.run_on_appengine(clients["calendar"]) # The client_id and client_secret are copied from the API Access tab on # the Google APIs Console <http://code.google.com/apis/console> decorator = OAuth2Decorator( client_id=settings.CLIENT_ID, client_secret=settings.CLIENT_SECRET, scope = 'https://www.googleapis.com/auth/plus.me https://picasaweb.google.com/data/ http://gdata.youtube.com https://docs.google.com/feeds/ https://www.google.com/calendar/feeds/') http = httplib2.Http(memcache) httpUnauth = httplib2.Http(memcache) # Get discovery document ul = urllib.urlopen(settings.DISCOVERY_DOCUMENT) discovery_doc = ul.read() ul.close() service = build("plus", "v1", http=http) serviceUnauth = build("plus", "v1", http=http, developerKey=settings.API_KEY)