コード例 #1
0
def goog_cred(name):

	flow = client.flow_from_clientsecrets(
		'client_secret.json',
		scope='https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/gmail.readonly',
		redirect_uri='urn:ietf:wg:oauth:2.0:oob')

	auth_uri = flow.step1_get_authorize_url()
	
	webbrowser.open(auth_uri)

	auth_code = input('Login and enter code here: ')
	file = str(name) + '_goog.txt'
	
	try:
		credentials = flow.step2_exchange(auth_code)
		storage = Storage(file)
		storage.put(credentials)
		return 1
		
	except oauth2client.client.FlowExchangeError:
		fob = open(file, 'w')
		fob.write("None")
		fob.close()
		return 0
コード例 #2
0
def Autorise(Flags):
    # using http://stackoverflow.com/questions/20248555/list-of-spreadsheets-gdata-oauth2/29157967#29157967 (thanks)
    # copy-paste-changed from https://github.com/leocrawford/picasawebsync (thanks x2 )!
    from oauth2client.file import Storage
    filename = 'user_credidentials.txt'
    storage = Storage(filename)
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        flow = client.flow_from_clientsecrets(Flags['ClientSecret'],scope='https://picasaweb.google.com/data/',redirect_uri='urn:ietf:wg:oauth:2.0:oob')
        auth_uri = flow.step1_get_authorize_url()
        print 'Authorization URL: %s' % auth_uri
        auth_code = raw_input('Enter the auth code: ')
        credentials = flow.step2_exchange(auth_code)
        storage.put(credentials)
    if credentials.access_token_expired:
        try:
            credentials.refresh(httplib2.Http())
        except Exception as error:
            print "Either your credidentials has expired and cannot be refreshed or httplib2 is not installed."
            print "Try to delete user_credidentials.txt and run script again or install http2lib with pip install httplib2"
            print "Error: "+str(error)
            exit(-1)
    gd_client = gdata.photos.service.PhotosService(email='default',additional_headers={'Authorization' : 'Bearer %s' % credentials.access_token})

    return(gd_client)
コード例 #3
0
    def handle(self, *args, **options):
        print("=" * 50)
        print(" Login to Google Calendar API")
        print("=" * 50)
        flow = flow_from_clientsecrets(
            settings.GOOGLE_CALENDAR_CLIENT_SECRETS,
            scope='https://www.googleapis.com/auth/calendar',
            redirect_uri='urn:ietf:wg:oauth:2.0:oob')

        auth_uri = flow.step1_get_authorize_url()

        print("Open the following URL to authorize the API")
        print()
        print(auth_uri)
        print()
        code = input("Please fill the code: ")

        if not code:
            print("Canceled")
            exit(1)

        credentials = flow.step2_exchange(code)

        storage = Storage(settings.GOOGLE_CALENDAR_CREDENTIALS)
        storage.put(credentials)

        print("Credentials are saved in '{}'".format(
            settings.GOOGLE_CALENDAR_CREDENTIALS))
コード例 #4
0
ファイル: update_db.py プロジェクト: pekko/speksi-tekijat
	def __init__(self):
		CREDENTIALS_FILENAME = 'secret/credentials'

		if not os.path.isfile(CREDENTIALS_FILENAME):
			flow = flow_from_clientsecrets('secret/client_secret.json',
									   scope='https://spreadsheets.google.com/feeds',
									   redirect_uri='http://localhost')

			auth_uri = flow.step1_get_authorize_url()
			print auth_uri

			code = '4/VxEGacqWScdA6XbV-3lePdaC9AiR.kuGt6o4KeRcYYKs_1NgQtmVnMiLyigI'
			credentials = flow.step2_exchange(code)
			storage = Storage(CREDENTIALS_FILENAME)
			storage.put(credentials)

		else:
			storage = Storage(CREDENTIALS_FILENAME)
			credentials = storage.get()

		http = httplib2.Http()
		http = credentials.authorize(http)

		self.http = http
		self.db = MySQLdb.connect(host=db_settings.host, user=db_settings.user, passwd=db_settings.passwd, db=db_settings.db, charset='utf8')
		self.cur = self.db.cursor()
コード例 #5
0
def OAuth2Login(client_secrets, credential_store, email):
    scope='https://picasaweb.google.com/data/'
    user_agent='picasawebuploader'

    storage = Storage(credential_store)
    credentials = storage.get()
    
    if credentials is None or credentials.invalid:
        flow = flow_from_clientsecrets(client_secrets, scope=scope, redirect_uri='urn:ietf:wg:oauth:2.0:oob')
        uri = flow.step1_get_authorize_url()
        webbrowser.open(uri)
        code = raw_input('Enter the authentication code: ').strip()
        credentials = flow.step2_exchange(code)
    if (credentials.token_expiry - datetime.utcnow()) < timedelta(minutes=5):
        http = httplib2.Http()
        http = credentials.authorize(http)
        credentials.refresh(http)

    storage.put(credentials)

    gd_client = gdata.photos.service.PhotosService(source=user_agent,
                                                   email=email,
                                                   additional_headers={'Authorization' : 'Bearer %s' % credentials.access_token})

    return gd_client
コード例 #6
0
	def _connect(self, scope="https://www.googleapis.com/auth/drive",
					redirect_url="urn:ietf:wg:oauth:2.0:oob", saved_credentials="drive_cred.txt"):
		""" Start connection for Google drive

		:param scope: Service to access
		:param redirect_url: URI handled by application
		:param storage: Store authorization credentials to avoid auth every time
		"""
		flow = OAuth2WebServerFlow(
				self._key, self._secret,
				scope, redirect_url)

		storage = Storage(saved_credentials)
		credentials = storage.get()

		if credentials is None:
			auth_url = flow.step1_get_authorize_url()
			print '1. Go to: ' + auth_url
			print '2. Click "Allow" (you might have to log in first)'
			print '3. Copy the authorization code.'
			code = raw_input("Enter the authorization code here: ").strip()
			credentials = flow.step2_exchange(code)
		else:
			print 'Previous authorization will be used!'

		http = httplib2.Http()
		http = credentials.authorize(http)
		print "Authorization successful!"

		self._client = build("drive", "v2", http=http)

		storage.put(credentials)
コード例 #7
0
    def oauth2_login(self):
        """
        :return:
        """
        user_agent = "picasawebuploader"

        storage = Storage(self.credential_storage + self.user + ".dat")
        credentials = storage.get()

        if credentials is None or credentials.invalid:
            print "Failed to get credential in cache. Going to get new"
            credentials = self.get_credentials()

        if (credentials.token_expiry - datetime.utcnow()) < timedelta(minutes=5):
            http = httplib2.Http()
            http = credentials.authorize(http)
            credentials.refresh(http)

        storage.put(credentials)

        gd_client = gdata.photos.service.PhotosService(
            source=user_agent,
            email=self.user + "@gmail.com",
            additional_headers={"Authorization": "Bearer %s" % credentials.access_token},
        )

        return gd_client
コード例 #8
0
ファイル: drive.py プロジェクト: Tagtoo/iyp-spider
def get_drive_service(credential_file=CLIENT_SECRET_FILE):
    """
    Returns a Google Drive service instance in order to make use of Google Drive API
    In the flow it will open a new browser window and guide you how to authenticate automatically
    """
    # Credentials
    credentialStorage = Storage(CLIENT_CREDENTIAL_STORAGE_LOCATION)
    credentials = credentialStorage.get()

    if not credentials:
        # OAuth authentication if no any credentials
        
        # determine client secrets
        flow = flow_from_clientsecrets(credential_file,
                scope=OAUTH_SCOPE,
                redirect_uri=REDIRECT_URI)

        # Step1
        authorizeUrl = flow.step1_get_authorize_url()
        print 'Go to the following link:\n%s' % authorizeUrl
        os.system('open "%s"' % authorizeUrl)
        authorizeCode = raw_input("Verification Code: ").strip()

        # Step2
        credentials = flow.step2_exchange(authorizeCode)

        # save credentials
        credentialStorage.put(credentials)

    # Build Drive Service Point
    http = httplib2.Http()
    http = credentials.authorize(http)

    return build('drive', 'v2', http=http)
コード例 #9
0
ファイル: youtube.py プロジェクト: joeladdison/eventstreamr
def get_authenticated_youtube_service(credential_storage_file, client_id, client_secret):
    flow = OAuth2WebServerFlow(
        client_id=client_id,
        client_secret=client_secret,
        scope=YOUTUBE_UPLOAD_SCOPE,
        redirect_uri=OOB_CALLBACK_URN)

    storage = Storage(credential_storage_file)
    credentials = storage.get()

    if credentials is None or credentials.invalid:
        # Start Authorization Process
        authorize_url = flow.step1_get_authorize_url()

        # Give user URL for authorization
        print
        print authorize_url
        print

        # Prompt for authorization code
        code = raw_input('Enter verification code: ').strip()
        credentials = flow.step2_exchange(code)

        # Save credentials for next time
        storage.put(credentials)
        credentials.set_store(storage)

    return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
        http=credentials.authorize(httplib2.Http()))
コード例 #10
0
ファイル: drive.py プロジェクト: royaurko/google-drive
def authorize():
    # Check if credentials already exist
    fname = '.credentials'
    if os.path.isfile(fname):
        storage = Storage('.credentials')
        credentials = storage.get()
    else:
        # Create a flow object to get user authentication
        flow = OAuth2WebServerFlow(os.environ['CLIENT_ID'],
                                   os.environ['CLIENT_SECRET'],
                                   OAUTH_SCOPE, redirect_uri=REDIRECT_URI)
        authorize_url = flow.step1_get_authorize_url()
        print 'Go to the following link in your browser: ' + authorize_url
        code = raw_input('Enter verification code: ').strip()
        credentials = flow.step2_exchange(code)
        # Store credentials for future use
        storage = Storage('.credentials')
        storage.put(credentials)

    # Create an httplib2.Http object and authorize it with our credentials
    http = httplib2.Http()
    http = credentials.authorize(http)

    drive_service = build('drive', 'v2', http=http)
    return drive_service
コード例 #11
0
ファイル: server.py プロジェクト: clee231/clee231.github.io
def googlePOST(temperature, humidity):
    flow = client.flow_from_clientsecrets(
        filepath + "/" + config.get("Config", "client_secrets_file"),
        scope="https://www.googleapis.com/auth/fusiontables",
    )
    http = httplib2.Http()
    storage = Storage(filepath + "/" + "sec_storage.enc")
    parser = argparse.ArgumentParser(parents=[tools.argparser])
    flags = parser.parse_args()
    if storage.get():
        credentials = storage.get()
    else:
        credentials = tools.run_flow(flow, storage, flags)
    storage.put(credentials)
    http_auth = credentials.authorize(http)
    service = build("fusiontables", "v2", developerKey=config.get("Config", "google_api_key"), http=http_auth)
    query = service.query()
    sqlstring = "INSERT INTO {:s} (nodeid, temperature, humidity, date) VALUES ({:d}, {:f}, {:f}, '{:s}');".format(
        config.get("Config", "table_id"),
        int(config.get("Config", "node_id")),
        temperature,
        humidity,
        datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
    )
    query.sql(sql=sqlstring).execute()
コード例 #12
0
ファイル: Base.py プロジェクト: OpenDMM/enigma2-plugins
def saveCredentials(credentials_file, credentials):
	try:
		storage = Storage(credentials_file)
		storage.put(credentials)
		return True
	except:
		return False
コード例 #13
0
def refresh_creds():

    '''
    Utility to refresh OAuth2 access_token.
    Refresh is currently not supported by Observant OpenLink.
    '''
    global storage
    print 'Token has expired... refreshing'
    creds = json.loads(flask.session['credentials'])
    payload = {'grant_type': creds['refresh_token'],
               'client_id': creds['client_id'],
               'redirect_uri': redir}
    r = requests.post(creds['token_uri'], params=payload)
    res = r.json()
    if 'error' in res:
        print 'refresh error: {}'.format(res['error'])
        return flask.redirect(flask.url_for('oauth2callback'))

    # create a new creds object and save it off
    credentials = client.OAuth2Credentials(access_token=res['access_token'],
                                           client_id=creds['client_id'],
                                           client_secret=creds['client_secret'],
                                           refresh_token=creds['refresh_token'],
                                           token_expiry=datetime.now() + timedelta(seconds=res['expires_in']),
                                           token_uri=creds['token_uri'],
                                           user_agent=creds['user_agent']
                                           )
    if storage is None:
        fname = '{}_{}'.format(app_name, service)
        storage = Storage(fname)
    storage.put(credentials)
    flask.session['credentials'] = client.OAuth2Credentials.to_json(credentials)
    return flask.redirect(flask.url_for('index'))
コード例 #14
0
ファイル: sumcoresg.py プロジェクト: pomeslab/sumcoresg
def oauth2callback_accept():
    args = flask.request.args
    code = args.get('code', None)
    if code:                      # meaning the user has granted the permission
        flow = pickle.loads(thedata.MEMC.get("OAUTH2_FLOW"))
        credentials = flow.step2_exchange(args)
        storage = Storage(thedata.STORAGE)
        storage.put(credentials)
        return flask.redirect('/cal')
        # credentials have the attributes something like the following: (or check oauth2client:client.py +360
        # [['access_token', u'ya29.AHES6ZTlEnVejuwDk7G3YF1CAYWgAIWix8LkF697H2ichz_DDs73fA'],
        #  ['access_token_expired', False],
        #  ['refresh_token', None],
        #  ['token_expiry', datetime.datetime(2012, 7, 8, 21, 0, 33, 904819)],
        #  ['token_uri', 'https://accounts.google.com/o/oauth2/token'],
        #  ['client_id', '1090543704733-hg2lc1ak1t7c3gf9ubtgvr7ha29ll8dm.apps.googleusercontent.com'],
        #  ['client_secret', 's5akWp-3F_1csjFkwvCqksEj'],
        #  ['user_agent', 'sumcoresg/1.0']]
        #  ['apply', >],
        #  ['authorize', >],
        #  ['from_json', >],
        #  ['id_token', None],
        #  ['invalid', False],
        #  ['new_from_json', >],
        #  ['refresh', >],
        #  ['set_store', >],
        #  ['store', None],
        #  ['to_json', >],
    else:
        try:
            if args['error'] == 'access_denied':
                return "Sorry, you cannot view the cal if you deny, go back to <a href='/'>home</a>"
        except KeyError:
            return "key not in args: wired thing happen, please report to the maintainer"
コード例 #15
0
ファイル: auth.py プロジェクト: rodolf0/google-apis
def consoleCredentials(client_id, clients_secret, tokens_file, scopes):
  # https://developers.google.com/google-apps/calendar/instantiate
  flow = OAuth2WebServerFlow(
      client_id=client_id, client_secret=clients_secret,
      scope=scopes, redirect_uri=OOB_CALLBACK_URN,
      user_agent='apitools/api-client-0.1')
  # To disable the local server feature, uncomment the following line:
  # import gflags
  # gflags.FLAGS.auth_local_webserver = False
  storage = Storage(tokens_file)
  credentials = storage.get()
  if credentials is None or credentials.invalid == True:
    if not sys.stdout.isatty():
      sys.stderr.write("OAuth2 setup requires interactive input\n")
      return None
    authorize_url = flow.step1_get_authorize_url()
    sys.stderr.write('Follow this link in your browser: %s\n' % authorize_url)
    code = raw_input('Enter verification code: ').strip()
    try:
      credentials = flow.step2_exchange(code)
    except FlowExchangeError, e:
      sys.stderr.write('Authentication has failed: %s\n' % e)
      return None
    storage.put(credentials)
    credentials.set_store(storage)
コード例 #16
0
ファイル: utils.py プロジェクト: quasipedia/googios
 def get_credentials(conf_fname):
     '''Run interactive OAuth 2.0 setup dance and return True on success.'''
     log.debug('Getting 3-legged credentials...')
     configuration = json.load(open(conf_fname))['installed']
     creds_fname = '{}.credentials'.format(os.path.splitext(conf_fname)[0])
     storage = Storage(creds_fname)
     credentials = storage.get()
     if credentials is None:
         log.info('Generating new 3-legged token')
         kwargs = {
             'client_id': configuration['client_id'],
             'client_secret': configuration['client_secret'],
             'scope': [SCOPES['contacts']],
             'user_agent': AGENT_NAME,
             'xoauth_displayname': AGENT_NAME,
         }
         flow = OAuth2WebServerFlow(**kwargs)
         log_level_string = logging.getLevelName(log.level)
         flags = MockArgparseFlags(log_level_string, True)
         credentials = run_flow(flow, storage, flags)
         storage.put(credentials)
     elif credentials.access_token_expired:
         credentials.refresh(httplib2.Http())
         storage.put(credentials)
     return credentials
コード例 #17
0
ファイル: secret.py プロジェクト: gddb/gddb
def run_local_oauth_flow():
  """
  Initiates local installed client oauth flow.  
  Inserts final credentials at 'secretfiles/credentials'.  
  This is necessary because service accounts such as AppAssertionCredentials do not load in 
  the local dev_server appengine SDK environment.  
  Local development mimicks the service account using a local installed client.

  returns Nothing

  Called by running from commandline:
  $ python secret.py
  """
  
  REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
  local_client_id = secret_cred.LOCAL_CLIENT_ID
  local_client_secret = secret_cred.LOCAL_CLIENT_SECRET
  flow = OAuth2WebServerFlow(local_client_id, local_client_secret, OAUTH_SCOPE, REDIRECT_URI)
  authorize_url = flow.step1_get_authorize_url()
  print 'Go to the following link in your browser: ' + authorize_url
  code = raw_input('Enter verification code: ').strip()
  credentials = flow.step2_exchange(code)
  credentials_path = secret_cred.CREDENTIALS
  storage = Storage(credentials_path)
  storage.put(credentials)
  print "Credentials stored at '%s'" % (credentials_path)
  f = open(credentials_path, 'r')
  data = f.read()
  f.close()
  credentials_path = os.path.join('test', secret_cred.CREDENTIALS)
  fw = open(credentials_path, 'w')
  fw.write(data)
  fw.flush()
  fw.close()
  print "Credentials copied to '%s'" % (credentials_path)
コード例 #18
0
ファイル: generaux.py プロジェクト: Taknok/Minecraft_P2P_v2
def login():

    # Copy information from the google page developper
    CLIENT_ID = '1055360985442-0ctghdaasiqd5b6hrak2ksuhigf30640.apps.googleusercontent.com'
    CLIENT_SECRET = 'BOz3lv0HEORunY6JQnQMa44o'
    
    # Check https://developers.google.com/drive/scopes for all available scopes
    OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'
    
    # Redirect URI for installed apps, display on the google page devlopper too
    REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
    
    credentials = credentials_creator()
    
    # Only attempt to get new credentials if the load failed.
    if not credentials:
    
        # Run through the OAuth flow and retrieve credentials                                                                                 
        flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
    
        authorize_url = flow.step1_get_authorize_url()
        print ('Go to the following link in your browser: ' + authorize_url)
        code = input('Enter verification code: ').strip()
    
        credentials = flow.step2_exchange(code)
        storage = Storage('a_credentials_file')
        storage.put(credentials)
コード例 #19
0
ファイル: youtube.py プロジェクト: djeebus/gmusic-cli
    def __init__(self, username, password):
        self.username = username
        self.password = password

        flow = flow_from_clientsecrets(
            CLIENT_SECRETS_FILE,
            scope=YOUTUBE_READ_WRITE_SCOPE,
            message=MISSING_CLIENT_SECRETS_MESSAGE,
        )

        storage = Storage("reds-oauth2.json")
        credentials = storage.get()

        if credentials is None or credentials.invalid:
            auth_uri = flow.step1_get_authorize_url(
                redirect_uri='http://localhost:12345',
            )
            print("auth_uri: %s" % auth_uri)
            code = input("code?")

            credentials = flow.step2_exchange(code)
            storage.put(credentials)

        self.yt = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
                        http=credentials.authorize(httplib2.Http()))
コード例 #20
0
ファイル: main.py プロジェクト: bozhiz/picasawebuploader
def OAuth2Login():
    configdir = os.path.expanduser(config_dir)
    client_secrets = os.path.join(configdir, secret_file)
    credential_store = os.path.join(configdir, store_file)

    storage = Storage(credential_store)
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        flow = flow_from_clientsecrets(client_secrets, scope=scope, redirect_uri='urn:ietf:wg:oauth:2.0:oob')
        uri = flow.step1_get_authorize_url()
        print uri + "\r\n"
        print "copy the uri to web browser to get the authentication code and enter it\r\n"
        webbrowser.open(uri)
        code = raw_input('Enter the authentication code: ').strip()
        credentials = flow.step2_exchange(code)

    global token_expire
    token_expire = credentials.token_expiry
    if ( token_expire - datetime.utcnow()) < timedelta(minutes=5):
        http = httplib2.Http()
        http = credentials.authorize(http)
        credentials.refresh(http)
        token_expire = credentials.token_expiry
        print 'refresh token in login'

    print "Token will expire at ", token_expire
    storage.put(credentials)

    return gdata.photos.service.PhotosService(source=user_agent,
                                                   email=email,
                                                   additional_headers={'Authorization' : 'Bearer %s' % credentials.access_token})
コード例 #21
0
def _get_credentials(http):
    storage = Storage('/home/btsai/.ftp-to-picasaweb-bridge/credentials')
    credentials = storage.get()

    if (credentials is not None and
        credentials.refresh_token is not None):
        if credentials.access_token_expired:
            credentials.refresh(http)
        return credentials

    flow = client.flow_from_clientsecrets(
        '/home/btsai/.ftp-to-picasaweb-bridge/client_secrets.json',
        scope='https://picasaweb.google.com/data/',
        redirect_uri='urn:ietf:wg:oauth:2.0:oob')
    
    auth_uri = flow.step1_get_authorize_url()
    
    sys.stdout.write("Opening window for authorization...\n")
    sys.stdout.flush()
    
    # webbrowser.open_new(auth_uri)
    print auth_uri
 
    sys.stdout.write("Authorization Code: ")
    sys.stdout.flush()

    auth_code = sys.stdin.readline()
    auth_code = auth_code[:-1]

    credentials = flow.step2_exchange(auth_code)
    storage.put(credentials)

    return credentials
コード例 #22
0
ファイル: gcaltweet.py プロジェクト: snkhrn/gCalTweet.py
    def __init__(self):
        self.calendars = []
        self.events = []
        self.service = ""

        storage = Storage('calendar.dat')
        credentials = storage.get()
        if credentials is None or credentials.invalid:
            # !!change this
            with open("secret_json.json") as f:
                jf = json.load(f)
                private_key = jf['private_key']
                client_email = jf['client_email']

            credentials = SignedJwtAssertionCredentials(
                client_email,
                private_key,
                'https://www.googleapis.com/auth/calendar.readonly'
                )
            storage.put(credentials)

        http = httplib2.Http()
        http = credentials.authorize(http)

        self.service = build(
            serviceName='calendar',
            version='v3',
            http=http)

        if(self.service):
            print("success: Oauth authorization")
コード例 #23
0
def main():
    storage = Storage('credentials.dat')
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        #credentials = run(flow, storage)
        auth_uri = flow.step1_get_authorize_url()
        print "Please goto this link: [%s]" % auth_uri
        code = raw_input("Enter verrification code: ").strip()
        credentials = flow.step2_exchange(code)
        if credentials:
            storage.put(credentials)

    if len(sys.argv) > 1:
        query = sys.argv[1]
    else:
        query = ""
    print "[%s]" % query

    http = httplib2.Http()
    http = credentials.authorize(http)
    service = build('drive', 'v2', http=http)
    print_about(service)

    me_files = retrieve_me_files(service, query)
    for fl in me_files:
        print "%s, %s, %s, %s" % (fl['title'], fl['id'], fl['fileSize'], fl['mimeType'])
        dlurl = fl['downloadUrl']
        if dlurl:
            resp, content = service._http.request(dlurl)
            print "Status: %s" % resp
            if resp.status == 200:
                f = open(fl['title'], 'w')
                f.write(content)
コード例 #24
0
ファイル: gdrive.py プロジェクト: akovalyov/gaz-counter
def getAuthorizedHttp():
    
    config = ConfigParser.ConfigParser()
    config.read([os.path.dirname(__file__)+'/config.ini'])
    
    # Copy your app credentials from the console
    CLIENT_ID = config.get('gdrive','CLIENT_ID')
    CLIENT_SECRET = config.get('gdrive','CLIENT_SECRET')

    # OAuth 2.0 scope that will be authorized.
    # Check https://developers.google.com/drive/scopes for all available scopes.
    OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'
    
    # Redirect URI for installed apps
    REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
    
    # Init auth storage
    storage = Storage(os.path.dirname(__file__) + '/client_secrets.json')
    credentials = storage.get()
    
    # Check credentials existance
    if not credentials:
        # Perform OAuth2.0 authorization flow.
        flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
        authorize_url = flow.step1_get_authorize_url()
        print 'Go to the following link in your browser: ' + authorize_url
        code = raw_input('Enter verification code: ').strip()
        credentials = flow.step2_exchange(code)
        # Store allowed credentials
        storage.put(credentials)
    
    # Create an authorized Drive API client.
    http = httplib2.Http()
    credentials.authorize(http)
    return http
コード例 #25
0
def main():
    """
    main function
    """

    with open(settings.SERVICE_ACCOUNT_JSON) as json_file:

        json_data = json.load(json_file)
        #print json_data
        credentials = SignedJwtAssertionCredentials(
            json_data['client_email'],
            json_data['private_key'],
            scope='https://apps-apis.google.com/a/feeds/emailsettings/2.0/',
            access_type="offline",
            approval_prompt = "force",
            sub=email
        )

    storage = Storage(settings.STORAGE_FILE)

    storage.put(credentials)
    #credentials = storage.get()
    credentials.get_access_token()

    if test:
        print credentials.__dict__
        #print credentials.access_token

    http = httplib2.Http()
    auth = credentials.authorize(http)
    # refresh does not seem to work
    credentials.refresh(http)
    print credentials.__dict__
コード例 #26
0
ファイル: googledrive.py プロジェクト: wycg1984/deltaic
def cmd_googledrive_auth(config, args):
    settings = config['settings']

    client_id = settings.get('googledrive-client-id')
    client_secret = settings.get('googledrive-client-secret')

    if not client_id or not client_secret:
        print 'Missing client id or secret, check setup instructions'
        return -1

    flow = client.OAuth2WebServerFlow(client_id, client_secret,
                                      scope=' '.join(OAUTH_SCOPE),
                                      redirect_uri=REDIRECT_URI)
    flow.user_agent = 'Deltaic'

    authorize_url = flow.step1_get_authorize_url()
    print 'Go to the following link in your browser: ' + authorize_url
    code = raw_input('Enter verification code: ').strip()
    credentials = flow.step2_exchange(code)

    # write credentials to file
    credentials_file = _default_drive_credentials_path(settings)
    foreverholdyourpeace("writing credentials to %s" % credentials_file,
                         file=sys.stderr)

    os.makedirs(os.path.dirname(credentials_file))
    storage = Storage(credentials_file)
    storage.put(credentials)
コード例 #27
0
ファイル: util.py プロジェクト: sylsi/schedule
def ensureOAuthCredentials(
    secrets_file="client_secrets.json",
    storage_file="a_credentials_file",
    redirect_uri="https://localhost:8000/oauth2callback",
    scope=["https://www.googleapis.com/auth/calendar", "https://apps-apis.google.com/a/feeds/calendar/resource/"],
):
    """
    Returns credentials (creates a_credentials_file in current dir if absent).

    If that file is missing, reads client_secrets.json then prints a URL
    for you to authorize the App on Google. Paste the resulting token and it
    will create a_credentials_file.
    """
    storage = Storage(storage_file)
    credentials = storage.get()
    if not credentials:
        flow = flow_from_clientsecrets(filename=secrets_file, scope=scope, redirect_uri=redirect_uri)
        # Try to get refresh token in response. Taken from:
        # https://developers.google.com/glass/develop/mirror/authorization
        flow.params["approval_prompt"] = "force"
        auth_uri = flow.step1_get_authorize_url()
        print auth_uri
        code = raw_input("Auth token: ")
        credentials = flow.step2_exchange(code)
        storage.put(credentials)
    return credentials
コード例 #28
0
  def test_pickle_and_json_interop(self):
    # Write a file with a pickled OAuth2Credentials.
    access_token = 'foo'
    client_id = 'some_client_id'
    client_secret = 'cOuDdkfjxxnv+'
    refresh_token = '1/0/a.df219fjls0'
    token_expiry = datetime.datetime.utcnow()
    token_uri = 'https://www.google.com/accounts/o8/oauth2/token'
    user_agent = 'refresh_checker/1.0'

    credentials = OAuth2Credentials(
        access_token, client_id, client_secret,
        refresh_token, token_expiry, token_uri,
        user_agent)

    f = open(FILENAME, 'w')
    pickle.dump(credentials, f)
    f.close()

    # Storage should be not be able to read that object, as the capability to
    # read and write credentials as pickled objects has been removed.
    s = Storage(FILENAME)
    read_credentials = s.get()
    self.assertEquals(None, read_credentials)

    # Now write it back out and confirm it has been rewritten as JSON
    s.put(credentials)
    f = file(FILENAME)
    data = simplejson.load(f)
    f.close()

    self.assertEquals(data['access_token'], 'foo')
    self.assertEquals(data['_class'], 'OAuth2Credentials')
    self.assertEquals(data['_module'], OAuth2Credentials.__module__)
コード例 #29
0
ファイル: dl-gdocs.py プロジェクト: monperrus/dl-gdocs
def get_credential_oauth():
  """ returns a credential object from the Google OAuth webservice"""

  # the application id: 
  # if this one gets blocked (by Google or myself)
  # you may create your own at https://console.developers.google.com/
  # menu APIs & Auth >> APIs: enable Drive API
  # menu APIs & Auth >> credentials >> Create New Client ID >> Installed application >> Other
  client_secrets = json.loads('{"installed":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret":"tB6CKB-KcegkcUONYZqKQw1j","token_uri":"https://accounts.google.com/o/oauth2/token","client_email":"","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","oob"],"client_x509_cert_url":"","client_id":"879219052242-anuu8p1or7c3ju6hv7fu426vkk1rf27k.apps.googleusercontent.com","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs"}}')

  #  flow = flow_from_clientsecrets('google.json', scope='',  redirect_uri='urn:ietf:wg:oauth:2.0:oob')
  
  flow = OAuth2WebServerFlow(client_id=client_secrets["installed"]["client_id"],
                           client_secret=client_secrets["installed"]["client_secret"],
                           scope='https://www.googleapis.com/auth/drive',
                           redirect_uri='urn:ietf:wg:oauth:2.0:oob')
  

  auth_uri = flow.step1_get_authorize_url()

  print("Please go to this URL and get an authentication code:")
  print(auth_uri)

  print("Please input the authentication code here:")
  code = raw_input("code?")

  credentials = flow.step2_exchange(code)

  storage = Storage(GOOGLE_CREDENTIALS_FILE)
  storage.put(credentials)

  return credentials
コード例 #30
0
ファイル: gSpreadSheet.py プロジェクト: joenery/BclPipeline
    def _getNewCredentials(self):
        """
        Since there isn't an credentials to work from authorize a new set.
    
        Some Google Plus scopes are used to get the User Emails / Names
        """

        print("First I've got to log you into your Google Drive!")

        # Step 0 Create Flow
        flow = flow_from_clientsecrets(self.client_secrets_json,
                                       scope=['https://spreadsheets.google.com/feeds',
                                              'https://www.googleapis.com/auth/drive',
                                              'https://www.googleapis.com/auth/userinfo.email',
                                              'https://www.googleapis.com/auth/userinfo.profile'],
                                       redirect_uri="urn:ietf:wg:oauth:2.0:oob")

        # Step 1 Get an authorize URL and get Code
        authorize_url = flow.step1_get_authorize_url()
    
        print 'Copy and paste the following link in your browser: \n\n%s' % (authorize_url)
        code = raw_input("\n\nEnter verification code: ").strip()
    
        # Step 2: Exchange Code for credentials
        credentials = flow.step2_exchange(code)
    
        # Store credentials
        storage = Storage(self.credentials_storage)
        storage.put(credentials)

        self.storage = storage
コード例 #31
0
ファイル: cli.py プロジェクト: mouedhen/sndlatr
def code_auth(code):
    credentials = credentials_from_clientsecrets_and_code(
        'client_secrets.json', SCOPES, code)
    storage = Storage('credentials_file')
    storage.put(credentials)
    print credentials.to_json()
コード例 #32
0
ファイル: cli.py プロジェクト: mouedhen/sndlatr
def auth2(code):
    flow = get_flow()
    credentials = flow.step2_exchange(code)
    print credentials.to_json()
    storage = Storage('credentials_file')
    storage.put(credentials)
コード例 #33
0
if not os.path.exists(OUT_PATH):
    os.makedirs(OUT_PATH)

storage = Storage(CREDS_FILE)
credentials = storage.get()

if credentials is None:
    # Run through the OAuth flow and retrieve credentials
    flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE,
                               REDIRECT_URI)
    authorize_url = flow.step1_get_authorize_url()
    print('Go to the following link in your browser: ' + authorize_url)
    code = raw_input('Enter verification code: ').strip()
    #code ="4/AACrsLsy4yJ1wbQSaneHl2dlSGklb8n8GDAnSwYJJHUdTizNX5UtKFw"
    credentials = flow.step2_exchange(code)
    storage.put(credentials)

print("credential part is done!")
# Create an httplib2.Http object and authorize it with our credentials
http = httplib2.Http()
http = credentials.authorize(http)
drive_service = build('drive', 'v2', http=http)

#drive_service.setRootUrl("https://drive.google.com/drive/u/2/folders/1WxYaa5rvGB-x_BgaxrVvRzCm2JPbXRxo")

folder_id = "https://drive.google.com/drive/u/2/folders/1WxYaa5rvGB-x_BgaxrVvRzCm2JPbXRxo"


def list_files(service):
    page_token = None
    while True:
コード例 #34
0
class State(object):
    """Device state."""
    def __init__(self):
        self.oauth_storage_ = Storage('oauth_creds')
        self.clear()

    def clear(self):
        self.credentials_ = None
        self.has_credentials_ = False
        self.has_wifi_ = False
        self.ssid_ = ''
        self.password_ = ''
        self.device_id_ = ''

    def reset(self):
        self.clear()
        self.dump()

    def dump(self):
        """Saves device state to file."""
        json_obj = {
            'has_credentials': self.has_credentials_,
            'has_wifi': self.has_wifi_,
            'ssid': self.ssid_,
            'password': self.password_,
            'device_id': self.device_id_
        }
        statefile = open(_DEVICE_STATE_FILE, 'w')
        json.dump(json_obj, statefile)
        statefile.close()

        if self.has_credentials_:
            self.oauth_storage_.put(self.credentials_)

    def load(self):
        if os.path.exists(_DEVICE_STATE_FILE):
            statefile = open(_DEVICE_STATE_FILE, 'r')
            json_obj = json.load(statefile)
            statefile.close()

            self.has_credentials_ = json_obj['has_credentials']
            self.has_wifi_ = json_obj['has_wifi']
            self.ssid_ = json_obj['ssid']
            self.password_ = json_obj['password']
            self.device_id_ = json_obj['device_id']

            if self.has_credentials_:
                self.credentials_ = self.oauth_storage_.get()

    def set_credentials(self, credentials, device_id):
        self.device_id_ = device_id
        self.credentials_ = credentials
        self.has_credentials_ = True
        self.dump()

    def set_wifi(self, ssid, password):
        self.ssid_ = ssid
        self.password_ = password
        self.has_wifi_ = True
        self.dump()

    def has_wifi(self):
        return self.has_wifi_

    def has_credentials(self):
        return self.has_credentials_

    def credentials(self):
        return self.credentials_

    def ssid(self):
        return self.ssid_

    def password(self):
        return self.password_

    def device_id(self):
        return self.device_id_
コード例 #35
0
class GoogleGrabber():
	
	def __init__(self):
		self.cred_path = "system\iba_google_credential"
		self.client_secret = "system\client_secret.json"
		self.storage = Storage(self.cred_path)
		self.redirect_uri='urn:ietf:wg:oauth:2.0:oob'
		self.scope = 'https://spreadsheets.google.com/feeds https://docs.google.com/feeds'
		self.credentials = self.storage.get()
		
		#Data Storage
		self.session_planungsdaten = []
		
	
	def get_planungsdaten(self):
		self.get_credentials()
		gSheet = myConfig.get('planungSpread')
		
		GSpread = gspread.authorize(self.credentials)
		act_sh = GSpread.open(gSheet)
		wks = act_sh.sheet1
		
		planungsdaten = wks.get_all_records(empty2zero=True, head=2)
		planungsdaten = self.clean_data(planungsdaten)
		
		self.session_planungsdaten = planungsdaten
		return planungsdaten
		
	def get_credentials(self):
		try:
			token = self.credentials.get_access_token
			if self.credentials.access_token_expired:
				self.credentials = self.obtain_new_credential()
		except:
			self.credentials = self.obtain_new_credential()
	
	def obtain_new_credential(self):
		parser = argparse.ArgumentParser(parents=[tools.argparser])
		flags = parser.parse_args()
		
		flow = flow_from_clientsecrets(self.client_secret, scope=self.scope, redirect_uri=self.redirect_uri)
		credentials = tools.run_flow(flow,self.storage,flags)
		
		self.storage.put(credentials)
		print('Obtained new Google Credential')
		
		return credentials    
		
	def clean_data(self, sheetData):
		#Entfernt HeaderZeilen und alle Einträge ohne geplantes Installationsdatum
		sheetData.pop(0)
		sheetData.pop(0)
		remove = []
		for s in sheetData:
			if s['Datum Installation']==0:
				remove.append(sheetData.index(s))
		
		for rem in sorted(remove, reverse=True):
			del sheetData[rem]
		
		return sheetData
コード例 #36
0
 def save_credentials(self, fake_user, credentials):
   """Using the fake user name as a key, save the credentials."""
   storage = Storage('credentials-%s.dat' % (fake_user))
   storage.put(credentials)