Beispiel #1
0
 def get_authorize_http():
     """ Method which is helpful to get authorize http from your credentials.
      Can be used for make some service from google api """
     json = db(GoogleToken).first().credentials
     cred = Credentials()
     credentials = cred.new_from_json(json)
     http = httplib2.Http()
     http = credentials.authorize(http)
     return http
Beispiel #2
0
 def get_credentials_from_db():
     """ Static method. This method make query from db to get json-credentials, and
      then return object correct credentials which has been made from json.
       Set httplib2.debuglevel = 4 to debug http"""
     # httplib2.debuglevel = 4
     json = db(GoogleToken).one().credentials
     cred = Credentials()
     credentials = cred.new_from_json(json)
     http = httplib2.Http()
     http = credentials.authorize(http)
     credentials.refresh(http)
     session['access_token'] = credentials.access_token
     return credentials
Beispiel #3
0
 def test_to_json_and_from_json(self):
     credentials = AppAssertionCredentials(
         scope=['http://example.com/a', 'http://example.com/b'])
     json = credentials.to_json()
     credentials_from_json = Credentials.new_from_json(json)
     self.assertEqual(credentials.access_token,
                      credentials_from_json.access_token)
  def test_get_access_token_on_refresh(self):
    app_identity_stub = self.AppIdentityStubImpl()
    apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
    apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service",
                                            app_identity_stub)
    apiproxy_stub_map.apiproxy.RegisterStub(
      'memcache', memcache_stub.MemcacheServiceStub())

    scope = [
     "http://www.googleapis.com/scope",
     "http://www.googleapis.com/scope2"]
    credentials = AppAssertionCredentials(scope)
    http = httplib2.Http()
    credentials.refresh(http)
    self.assertEqual('a_token_123', credentials.access_token)

    json = credentials.to_json()
    credentials = Credentials.new_from_json(json)
    self.assertEqual(
      'http://www.googleapis.com/scope http://www.googleapis.com/scope2',
      credentials.scope)

    scope = "http://www.googleapis.com/scope http://www.googleapis.com/scope2"
    credentials = AppAssertionCredentials(scope)
    http = httplib2.Http()
    credentials.refresh(http)
    self.assertEqual('a_token_123', credentials.access_token)
    self.assertEqual(
      'http://www.googleapis.com/scope http://www.googleapis.com/scope2',
      credentials.scope)
Beispiel #5
0
  def test_to_from_json(self):
    c = AppAssertionCredentials(scope=['http://example.com/a',
                                       'http://example.com/b'])
    json = c.to_json()
    c2 = Credentials.new_from_json(json)

    self.assertEqual(c.access_token, c2.access_token)
def getDriveList():
	global drivecredentials
	global drive_service

	if (drive_service is None):
		if (drivecredentials is None):
			driveauthfile = open('drivecredentials.txt', 'r')
			drivecredentials = Credentials.new_from_json(driveauthfile.read())
			driveauthfile.close()

		http = httplib2.Http()
		http = drivecredentials.authorize(http)
		drive_service = build('drive', 'v2', http=http)

	#Variable donde almacenaremos todos los ficheros listados
	resultados = []
	page_token = None
	siguiente_pagina = True
	while siguiente_pagina:
		parametros = {}

		#Comprobar si hay otra pagina
		if page_token:
			parametros['pageToken'] = page_token

		#Ejecutamos la consulta
		files = drive_service.files().list(**parametros).execute()

		#Concatenamos los resultados con los de la página anterior
		resultados.extend(files['items'])

		#Guardamos el token de la página siguiente
		page_token = files.get('nextPageToken')

		#Comprobamos si hay que continuar
		if not page_token:
			siguiente_pagina = False


	#Procesamos los resultados, almacenando la información relevante
	respuesta = []
	for elemento in resultados:
		try:
			respuesta.extend([{
				'id': elemento['id'],
				'filename': elemento['title'],
				'link': elemento['alternateLink'],
				'size': elemento['fileSize'],
				'remove_link': 'remove_drive_file?id=' + elemento['id']
			}])
		except:
			respuesta.extend([{
				'id': elemento['id'],
				'filename': elemento['title'],
				'link': elemento['alternateLink'],
				'size': 0,
				'remove_link': 'remove_drive_file?id=' + elemento['id']
			}])

	return json.dumps(respuesta)
Beispiel #7
0
    def get(self):
        # credentials = sessions.get_store(request=self.request).get_session().get('credentials')
        credentials = self.session.get('credentials')
        credentials = Credentials.new_from_json(credentials)
        logging.debug("nawwwwww")
        logging.debug(credentials)
        # credentials = credentials[0].from_json()
        # logging.debug(credentials)
        # logging.debug("F**K")
  # Only fetch a list of people for connected users.
        if credentials is None:
            logging.debug("creds = none!")
            self.response.headers['Content-Type'] = 'application/json'
            self.response.status = 401
            self.response.out.write(json.dumps('Current user not connected.'))
            

        try:
            # Create a new authorized API client.
            http = httplib2.Http()
            http = credentials.authorize(http)
            # Get a list of people that this user has shared with this app.
            google_request = SERVICE.people().list(userId='me', collection='visible')
            result = google_request.execute(http=http)
            logging.debug(json.dumps(result))
            self.response.headers['Content-Type'] = 'application/json'
            self.response.status = 200
            self.response.out.write(json.dumps(result))

            

        except AccessTokenRefreshError:
            self.response.headers['Content-Type'] = 'application/json'
            self.response.status = 500
            self.response.out.write(json.dumps('Failed to refresh access token.'))
Beispiel #8
0
def run():
    if "creds" in session:
        creds = Credentials.new_from_json(session["creds"])
        #Tracks2Cal(creds).run()
        return "DONE", 200
    else:
        return render_template("error.html", message="No auth token found")
Beispiel #9
0
 def __init__(self, client_secret_file, oauth_scope_key, re_autheticate=False):
     if(not oauth_scope_key in self.scopes):
         self.oauth_scope = self.scopes['READ_ONLY'];
     else:
         self.oauth_scope = self.scopes[oauth_scope_key]
     
     self.client_secret_file_data = self.get_client_secret_file(client_secret_file)
     
     self.client_id = self.client_secret_file_data['installed']['client_id']
     self.client_secret = self.client_secret_file_data['installed']['client_secret']
     self.redirect_uri = self.client_secret_file_data['installed']['redirect_uris'][0]
     
     #Authenticate
     # check whether or not trying to authenticate again
     if os.path.isfile(self.credentials_file) and not re_autheticate:
         credentials_file_data = self.get_client_credentials()
         credentials = Credentials.new_from_json(credentials_file_data)
     else:
         # client needs to manually get credentials
         flow = OAuth2WebServerFlow(self.client_id, self.client_secret, self.oauth_scope, redirect_uri=self.redirect_uri) 
                                     #access_type='offline')
         authorize_url = flow.step1_get_authorize_url()
         flow.step1_get_authorize_url()
          
         log('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 next authorization
         self.set_client_credentials(credentials)
     
     self.set_drive_service(credentials)
def authorize_installed_app(scope, env_key):
    """Prepare oAuth2 credentials for an installed app.

    Args:
        env_key: The environment variable from which to read the credentials.
        scope: The scope needed. (Only used here for documentation purposes.)

    Returns:
        An authorized httplib2.Http() instance.
    """
    content = os.getenv(env_key)

    if not content:
        raise RuntimeError(
            'Missing credentials for %s' % env_key)

    try:
        credentials = Credentials.new_from_json(content)
        if credentials.invalid:
            raise ValueError()
    except ValueError:
        raise RuntimeError(
            'Invalid credentials for %s' % env_key)

    return credentials.authorize(httplib2.Http())
Beispiel #11
0
    def locked_get(self):
        """Retrieve Credential from file.

    Returns:
      oauth2client.client.Credentials

    Raises:
      CredentialsFileSymbolicLinkError if the file is a symbolic link.
    """
        credentials = None
        self._validate_file()
        try:
            f = open(self._filename, "rb")
            content = f.read()
            f.close()
        except IOError:
            return credentials

        try:
            credentials = Credentials.new_from_json(content)
            credentials.set_store(self)
        except ValueError:
            pass

        return credentials
Beispiel #12
0
 def test_serialize_deserialize(self, get_metadata):
     credentials = AppAssertionCredentials()
     credentials_from_json = Credentials.new_from_json(
         credentials.to_json())
     self.assertEqual(
         credentials.service_account_info,
         credentials_from_json.service_account_info)
def get_credentials():
    if __cache.has_key('credentials'):
        return __cache['credentials']
    elif os.path.exists('%s/.googledrive'%os.environ['HOME'] ):
        ss = open('%s/.googledrive'%os.environ['HOME']).read()
        credentials = Credentials.new_from_json( ss )
    else:
        # Copy your credentials from the APIs Console
        CLIENT_ID = 'your client id'
        CLIENT_SECRET = 'your client secrete'
        REDIRECT_URI = 'your redirect uri'
        # Check https://developers.google.com/drive/scopes for all available scopes
        OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'
    
        # 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()
        credentials = flow.step2_exchange(code)
        f = open('%s/.googledrive'%os.environ['HOME'], 'w')
        f.write(credentials.to_json())
        f.close()
        
    return credentials
Beispiel #14
0
 def get_access_token():
         if not settings.GOOGLE_API_CREDENTIALS or settings.GOOGLE_API_CREDENTIALS == "":
             print ">>> ERR >>> GOOGLE_API_CREDENTIALS not defined"
         credential = Credentials.new_from_json(settings.GOOGLE_API_CREDENTIALS)
         http = httplib2.Http()
         credential._refresh(http.request)
         return credential.access_token
Beispiel #15
0
def disconnect(request):
    # Check to make sure the user is logged in
    url = redirect_if_not_logged_in(request)
    if url is not None:
        return url

    # Only disconnect a connected user.
    creditionals_in_json = request.session['credentials']
    if creditionals_in_json is None:
        # Trying to disconnect a connected user so some sort of error probably occured
        return redirect(reverse("ding:error_401"))
    # Retrieve the dcredentials object
    credentials = Credentials.new_from_json(creditionals_in_json)

    # Execute HTTP GET request to revoke current token.
    access_token = credentials.access_token
    url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token
    h = httplib2.Http()
    result = h.request(url, 'GET')[0]

    if result['status'] == '200':
        # Reset the user's session.
        del request.session['credentials']
        request.session.delete()
        # Redirect back to sign in page
        url = reverse("ding:disconnect_sign_in");
        return redirect(url)
    else:
        # For whatever reason, the given token was invalid.
        error = {'error_type': 400, 'request_path': request.path}
        return render(request, 'ding/error.html', error, status=400)
Beispiel #16
0
def user_info(creds=None):
    if creds is None:
        creds = session['google_creds']
    creds = Credentials.new_from_json(creds)
    user_info_service = build('oauth2', 'v2', http=creds.authorize(httplib2.Http()))
    user_info = user_info_service.userinfo().get().execute()
    if user_info and user_info.get('id'):
        return user_info
Beispiel #17
0
 def locked_get(self):
     credentials = None
     if not pkg_resources.resource_exists(__name__, self._filename):
         return super(Storage, self).locked_get()
     content = pkg_resources.resource_string(__name__, self._filename)
     credentials = Credentials.new_from_json(content)
     credentials.set_store(self)
     return credentials
Beispiel #18
0
def __create_service():
    with open('credentials', 'rw') as f:
        credentials = Credentials.new_from_json(f.read())

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

    return build('calendar', 'v3', http=http)
Beispiel #19
0
    def get_user_credentials(self):
        j_credentials = self.memcache_session.get(self.CREDENTIALS_KEY)
        if j_credentials is None:
            return

        credentials = Credentials.new_from_json(j_credentials)
        if not credentials.invalid:
            return credentials
Beispiel #20
0
 def __init__(self):
   YOUTUBE_DATA_API_NAME = "youtube"
   YOUTUBE_DATA_API_VERSION = "v3"
   content = os.environ['YT']
   credentials = Credentials.new_from_json(content)
   http = httplib2.Http()
   http = credentials.authorize(http)
   self.youtube = build(YOUTUBE_DATA_API_NAME, YOUTUBE_DATA_API_VERSION, http=http)
Beispiel #21
0
 def _set_expiration_to_long_time(self, creds):
     cred_str = creds.to_json()
     cred_json = json.loads(cred_str)
     # incase it might have an expiration
     if(cred_json['token_expiry'] is not None):
         return creds
     cred_json['token_expiry'] = '2100-01-01T00:00:01Z'
     cred_new_json = json.dumps(cred_json)
     return Credentials.new_from_json(cred_new_json)
Beispiel #22
0
 def test_credentials_to_from_json(self):
     credentials = self._make_credentials()
     json = credentials.to_json()
     restored = Credentials.new_from_json(json)
     self.assertEqual(credentials._private_key_pkcs12,
                      restored._private_key_pkcs12)
     self.assertEqual(credentials._private_key_password,
                      restored._private_key_password)
     self.assertEqual(credentials._kwargs, restored._kwargs)
 def __init__(self, credentials, user_email=None):
     if credentials:
         self.service = build_service(Credentials.new_from_json(credentials))
     else:
         logging.error('This user failed in credentials error %s and email %s' % (credentials, user_email))
         auth_url = 'no_url'
         if user_email:
             auth_url = get_authorization_url(user_email, 1)
         raise GetCredentialsException(auth_url)
Beispiel #24
0
 def oauth_credentials_are_valid(self, credentials_json):
     if not credentials_json:
         return False
     try:
         credentials = Credentials.new_from_json(credentials_json)
     except Exception:
         return False
     if credentials is None or credentials.invalid:
         return False
     return True
Beispiel #25
0
def http_and_service():
    import httplib2
    from apiclient.discovery import build
    from oauth2client.client import Credentials

    with open('credentials.json','r') as ff: 
        credentials = Credentials.new_from_json(ff.read())
    http = httplib2.Http()
    http = credentials.authorize(http)
    return http, build('drive', 'v2', http=http)
 def test_credentials_to_from_json(self):
     private_key = datafile("privatekey.p12")
     credentials = SignedJwtAssertionCredentials(
         "*****@*****.**", private_key, scope="read+write", prn="*****@*****.**"
     )
     json = credentials.to_json()
     restored = Credentials.new_from_json(json)
     self.assertEqual(credentials.private_key, restored.private_key)
     self.assertEqual(credentials.private_key_password, restored.private_key_password)
     self.assertEqual(credentials.kwargs, restored.kwargs)
 def tick(self, config):
     Logger.Info('%s - tick - started - with config: %s' % (__name__, config))
     keywords = [e for e in config['elements'] if e['name'] == 'keywords'][0]['value']
     credentials = Credentials.new_from_json([e for e in config['elements'] if e['name'] == 'oauth2'][0]['value'])
     http = credentials.authorize(httplib2.Http())
     service = build('plus', 'v1', http=http)
     response = service.activities().search(query=keywords).execute()
     Logger.Debug('%s - tick - JSON response: %s' % (__name__, response))
     content = [self._map_googleplus_item_to_content_item(config, item) for item in response['items']]
     Logger.Info('%s - tick - finished' % __name__)
     return content
Beispiel #28
0
def setup_api_service():
    secret_data = None
    with open(CLIENT_SECRETS) as f:
        secret_data = f.read()
    credentials = Credentials.new_from_json(secret_data)

    # 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
Beispiel #29
0
def get_gcloud_oauth2_creds():
  gcfp = '~/.config/gcloud/credentials'
  credfn = os.path.expanduser(gcfp)
  if not os.path.exists(credfn):
    msg = "[edx2bigquery] Authentication error!  You have specified USE_GCLOUD_AUTH in the configuration, but do not have gcloud authentication available.\n"
    msg += "               Please authenticate using 'gcloud auth login' before running this."
    print msg
    raise Exception(msg)
  gcloud_cred = json.loads(open(credfn).read())['data'][0]['credential']
  credentials = Credentials.new_from_json(json.dumps(gcloud_cred))
  return credentials
Beispiel #30
0
 def make_value_from_datastore(self, value):
   logger.info("make: Got type " + str(type(value)))
   if value is None:
     return None
   if len(value) == 0:
     return None
   try:
     credentials = Credentials.new_from_json(value)
   except ValueError:
     credentials = None
   return credentials
Beispiel #31
0
def drive():
    query = session.query(Buy)
    last = query.filter(bool(Buy.buy_id)).count()
    even_cal = query.filter(Buy.buy_id == last).one()
    new = even_cal.id_user
    query = session.query(User)
    add_tok = query.filter(User.user_id == even_cal.id_user).one()
    credentials = Credentials.new_from_json(add_tok.token)
    http = credentials.authorize(httplib2.Http())
    service = build('drive', 'v3', http=http)
    create(new, service)
    pass
Beispiel #32
0
 def __init__(self, credentials, user_email=None):
     if credentials:
         self.service = build_service(
             Credentials.new_from_json(credentials))
     else:
         logging.error(
             'This user failed in credentials error %s and email %s' %
             (credentials, user_email))
         auth_url = 'no_url'
         if user_email:
             auth_url = get_authorization_url(user_email, 1)
         raise GetCredentialsException(auth_url)
 def test_credentials_to_from_json(self):
     private_key = datafile('privatekey.%s' % self.format)
     credentials = SignedJwtAssertionCredentials('*****@*****.**',
                                                 private_key,
                                                 scope='read+write',
                                                 sub='*****@*****.**')
     json = credentials.to_json()
     restored = Credentials.new_from_json(json)
     self.assertEqual(credentials.private_key, restored.private_key)
     self.assertEqual(credentials.private_key_password,
                      restored.private_key_password)
     self.assertEqual(credentials.kwargs, restored.kwargs)
Beispiel #34
0
 def prepareCredential(mail, credential_json):
     """  build credential object from json, and check expiry or refresh it.
     may be throw exceptions while dealing with google-apis.
     :param mail:
     :param credential_json:
     :return: credential obj
     """
     credential = Credentials.new_from_json(credential_json)
     if credential.access_token_expired:
         credential.refresh(httplib2.Http())
         CredentialManager.updateCredential(mail, credential.to_json())
         log.info('Credential refreshed and saved.')
     return credential
Beispiel #35
0
  def locked_get(self):
    """Return Credentials."""
    content = db_config.get_value('client_credentials')
    if not content:
      return None

    try:
      credentials = Credentials.new_from_json(content)
      credentials.set_store(self)
    except ValueError:
      return None

    return credentials
def get_stored_credentials(email_address):
    """Retrieved stored credentials for the provided user ID.

    Args:
      email_address: User's email address.
    Returns:
      Stored oauth2client.client.OAuth2Credentials if found, None otherwise.
    Raises:
      NotImplemented: This function has not been implemented.
    """
    json_creds = dc.get_credentials(email_address)
    creds = Credentials.new_from_json(json_creds)
    return creds
    def locked_get(self):
        credentials = None
        try:
            content = StaffDictionary.objects.get(key="ga_credentials").value
        except Exception:
            return credentials

        try:
            credentials = Credentials.new_from_json(content)
            credentials.set_store(self)
        except ValueError:
            pass

        return credentials
Beispiel #38
0
def retrieve_credentials():
    #TODO: replace with db call
    db_file = '/home/pi/scripts/drive_security/db.txt'
    if os.path.isfile(db_file) == False:
        return None
    f = open(db_file)
    credentials = ''
    for line in f.read():
        credentials += line
    f.close()
    # print 'cred: ' + credentials
    if credentials.strip() == '':
        return None
    return Credentials.new_from_json(credentials)
Beispiel #39
0
  def _decode_credential_from_json(self, cred_entry):
    """Load a credential from our JSON serialization.

    Args:
      cred_entry: A dict entry from the data member of our format

    Returns:
      (key, cred) where the key is the key tuple and the cred is the
        OAuth2Credential object.
    """
    raw_key = cred_entry['key']
    key = util.dict_to_tuple_key(raw_key)
    credential = None
    credential = Credentials.new_from_json(json.dumps(cred_entry['credential']))
    return (key, credential)
Beispiel #40
0
def get_authenticated_service():
    """Initializes the analyticsreporting service object.

    Returns:
        analytics an authorized analyticsreporting service object.
    """

    json = load_credentials('GA_API')
    credentials = Credentials.new_from_json(json)
    http = credentials.authorize(http=httplib2.Http())

    # Build the service object.
    analytics = build('analytics', 'v4', http=http)

    return analytics
Beispiel #41
0
 def __init__(self):
     """
         Initializer for Drive class
         Args: None
         Returns: Authenticated drive service object
     """
     # try:
     if not settings.GOOGLE_API_CREDENTIALS or settings.GOOGLE_API_CREDENTIALS == "":
         print ">>> ERR >>> GOOGLE_API_CREDENTIALS not defined"
     credential = Credentials.new_from_json(settings.GOOGLE_API_CREDENTIALS)
     # except Exception, e:
     #     return redirect('get_refresh_token')
     http = httplib2.Http()
     http = credential.authorize(http)
     self.service = build('drive', 'v2', http=http)
Beispiel #42
0
def get_stored_credentials(user_id):
    """Retrieved stored credentials for the provided user ID.

    Args:
      user_id: User's ID.
    Returns:
      Stored oauth2client.client.OAuth2Credentials if found, None otherwise.
    Raises:
      NotImplemented: This function has not been implemented.
    """
    profile = Profile.objects.get(drive_id=user_id)
    if profile and profile.drive_token:
        return Credentials.new_from_json(profile.drive_token)
    else:
        return None
 def test_credentials_to_from_json(self):
     private_key = datafile('privatekey.pem')
     credentials = PyCryptoSignedJwtAssertionCredentials(
         '*****@*****.**',
         private_key,
         scope='read+write',
         prn='*****@*****.**')
     json = credentials.to_json()
     print json
     restored = Credentials.new_from_json(json)
     print restored.to_json()
     self.assertEqual(credentials.private_key, restored.private_key)
     self.assertEqual(credentials.private_key_password,
                      restored.private_key_password)
     self.assertEqual(credentials.kwargs, restored.kwargs)
Beispiel #44
0
def calendar_service():
    flow = OAuth2WebServerFlow(
        client_id=os.environ['CLIENT_ID'],
        client_secret=os.environ['CLIENT_SECRET'],
        scope='https://www.googleapis.com/auth/calendar.readonly',
        redirect_uri=os.environ['REDIRECT_URI'],
        approval_prompt='force')

    credentials_json = os.environ['CREDENTIALS']
    credentials = Credentials.new_from_json(credentials_json)
    if credentials is None or credentials.invalid:
        credentials = run(flow, storage)

    http = httplib2.Http()
    http = credentials.authorize(http)
    return build('calendar', 'v3', http=http)
def calendar_service():
    flow = OAuth2WebServerFlow(
        client_id='<REDACTED>',
        client_secret='<REDACTED>',
        scope='https://www.googleapis.com/auth/calendar.readonly',
        redirect_uri='<REDACTED>',
        approval_prompt='force')

    credentials_json = '<REDACTED>'
    credentials = Credentials.new_from_json(credentials_json)
    if credentials is None or credentials.invalid:
        credentials = run(flow, storage)

    http = httplib2.Http()
    http = credentials.authorize(http)
    return build('calendar', 'v3', http=http)
def _load_credentials_file(credentials_file):
    """Load credentials from the given file handle.

    The file is expected to be in this format:

        {
            "file_version": 2,
            "credentials": {
                "key": "base64 encoded json representation of credentials."
            }
        }

    This function will warn and return empty credentials instead of raising
    exceptions.

    Args:
        credentials_file: An open file handle.

    Returns:
        A dictionary mapping user-defined keys to an instance of
        :class:`oauth2client.client.Credentials`.
    """
    try:
        credentials_file.seek(0)
        data = json.load(credentials_file)
    except Exception:
        logger.warning('Credentials file could not be loaded, will ignore and '
                       'overwrite.')
        return {}

    if data.get('file_version') != 2:
        logger.warning('Credentials file is not version 2, will ignore and '
                       'overwrite.')
        return {}

    credentials = {}

    for key, encoded_credential in iteritems(data.get('credentials', {})):
        try:
            credential_json = base64.b64decode(encoded_credential)
            credential = Credentials.new_from_json(credential_json)
            credentials[key] = credential
        except:
            logger.warning(
                'Invalid credential {0} in file, ignoring.'.format(key))

    return credentials
Beispiel #47
0
    def locked_get(self):
        """Retrieve Credential from file.

    Returns:
      oauth2client.client.Credentials
    """
        credentials = None
        content = keyring.get_password(self._service_name, self._user_name)

        if content is not None:
            try:
                credentials = Credentials.new_from_json(content)
                credentials.set_store(self)
            except ValueError:
                pass

        return credentials
Beispiel #48
0
    def _googledrive_auth(self):
        credentials = None
        dataManager = LocalDataManager()

        #A KeyError will be raised if there is no token.
        credentials = dataManager.get_credentials('GoogleDrive')

        credentials = Credentials.new_from_json(credentials)
        http = credentials.authorize(httplib2.Http())
        try:
            drive_service = build('drive', 'v2', http=http)
        except httplib2.ServerNotFoundError:
            raise faults.NetworkError('No internet.')

        try:
            #Check whether the target folder exists
            container = dataManager.get_service_root('GoogleDrive')
            if container:
                arguments = [
                    'title = "{}"'.format(container),
                    'mimeType = "application/vnd.google-apps.folder"',
                    'trashed = False'
                ]
                q = ' and '.join(arguments)
                response = drive_service.files().list(q=q).execute()
                if not response['items']:
                    #Create the folder
                    self.logger.info(
                        'GoogleDrive folder changed:{}'.format(container))
                    body = {
                        'title': container,
                        'mimeType': 'application/vnd.google-apps.folder'
                    }
                    response = drive_service.files().insert(
                        body=body).execute()
                    dataManager.set_folder_id(response['id'])
                else:
                    dataManager.set_folder_id(response['items'][0]['id'])
        except errors.HttpError as e:
            #raise
            raise faults.NetworkError('No internet.')
        except AccessTokenRefreshError:
            raise faults.InvalidAuth('GoogleDrive')

        dataManager.set_credentials('GoogleDrive', credentials)
        return drive_service
def handle(event, context):
    calendarId = getConfigValue('GoogleCalendarId')
    oauthSecret = getConfigValue('GoogleOAuth2ClientSecret')
    oauthId = getConfigValue('GoogleOAuth2ClientId')
    oauthRedirectUri = getConfigValue('GoogleOAuth2RedirectUri')
    try:
        credentialJson = getConfigValue('GoogleOAuth2Credentials')
    except:
        credentialJson = None
    if (credentialJson is not None):
        credentials = Credentials.new_from_json(credentialJson)
    else:
        flow = OAuth2WebServerFlow(client_id=oauthId, client_secret=oauthSecret, scope='https://www.googleapis.com/auth/calendar', redirect_uri=oauthRedirectUri)
        flow.params['access_type'] = 'offline'
        auth_uri = flow.step1_get_authorize_url()
        webbrowser.open(auth_uri)
        raw_input()
        code = getConfigValue('GoogleOAuth2Code')
        credentials = flow.step2_exchange(code)
        setConfigValue('GoogleOAuth2Credentials', credentials.to_json())
    http_auth = credentials.authorize(httplib2.Http())
    calendar = build('calendar', 'v3', http=http_auth)
    resourceId = getConfigValue('GoogleCalendarResourceId')
    try:
        id = getConfigValue('GoogleCalendarWatchId')
    except:
        id = None
    if id is not None:
        calendar.channels().stop(body={'id': id, 'resourceId': resourceId}).execute()
    id = str(uuid.uuid1())
    setConfigValue('GoogleCalendarWatchId', id)
    expiration = datetime.datetime.utcnow() + datetime.timedelta(days=365)
    expirationUnix = time.mktime(expiration.timetuple()) * 1000
    body = {
            'kind': 'api#channel',
            'address': getConfigValue('GoogleWebhookAddress'),
            'type': 'web_hook',
            'id': id,
            'expiration': expirationUnix
            }
    try:
        print calendar.events().watch(calendarId=calendarId, body=body).execute()
    except Exception as e:
        deleteConfigValue('GoogleCalendarWatchId')
        raise e
Beispiel #50
0
  def _decode_credential_from_json(self, cred_entry):
    """Load a credential from our JSON serialization.

    Args:
      cred_entry: A dict entry from the data member of our format

    Returns:
      (key, cred) where the key is the key tuple and the cred is the
        OAuth2Credential object.
    """
    raw_key = cred_entry['key']
    client_id = raw_key['clientId']
    user_agent = raw_key['userAgent']
    scope = raw_key['scope']
    key = (client_id, user_agent, scope)
    credential = None
    credential = Credentials.new_from_json(simplejson.dumps(cred_entry['credential']))
    return (key, credential)
Beispiel #51
0
    def _from_base_type(self, value):
      """Converts our stored JSON string back to the desired type.

      Args:
        value: A value from the datastore to be converted to the desired type.

      Returns:
        A deserialized Credentials (or subclass) object, else None if the
            value can't be parsed.
      """
      if not value:
        return None
      try:
        # Uses the from_json method of the implied class of value
        credentials = Credentials.new_from_json(value)
      except ValueError:
        credentials = None
      return credentials
Beispiel #52
0
    def setup_credentials(self):
        scope = 'https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/drive https://spreadsheets.google.com/feeds https://docs.google.com/feeds https://www.googleapis.com/auth/gmail.compose'

        # This is what we do to get the credentials in the first place.
        # Note the access_type *offline*
        #flow=OAuth2WebServerFlow(client_id="116366442836.apps.googleusercontent.com", client_secret="DfS28bOzihgyqyKjsgS0Rum7",
        #  scope=scope, redirect_uri="urn:ietf:wg:oauth:2.0:oob", access_type="offline")
        #flow.step1_get_authorize_url()
        #code=<from_that_webpage>
        #credentials = flow.step2_exchange(code=code)
        # After that, we save the credentials as a json to s3 and retrieve them from there going forward
        conn = boto.connect_s3()
        # if Validate=True, boto validates by listing the contents of the bucket. But our ec2 IAM role doesn't have
        # list permissions, just read for its directory
        bucket = conn.get_bucket('hobby.lyceum.dyn.dhs.org', validate=False)
        credentials_string = bucket.get_key(
            "cal-tracker/credentials.json").get_contents_as_string()
        self.credentials = Credentials.new_from_json(credentials_string)
Beispiel #53
0
def get_stored_credentials(user_id):
    """Retrieved stored credentials for the provided user ID.

    Args:
      user_id: User's ID.
    Returns:
      Stored oauth2client.client.OAuth2Credentials if found, None otherwise.
    Raises:
      NotImplemented: This function has not been implemented.
    """
    # TODO: Implement this function to work with your database.
    #       To instantiate an OAuth2Credentials instance from a Json
    #       representation, use the oauth2client.client.Credentials.new_from_json
    #       class method.
    with open(SAVED_CREDENTIALS, 'r') as fd:
        creds = pickle.load(fd.read())
        user_credentials = creds.get(user_id)
        if user_credentials is not None:
            return Credentials.new_from_json(user_credentials)
Beispiel #54
0
def get_google_cred(db, userId, code):
    user = db.session.query(User).get(str(userId))
    print "potato"
    print str(user.google_cred)
    if len(str(user.google_cred)) > 5:
        #store in db
        http = httplib2.Http()
        credentials = Credentials.new_from_json(str(user.google_cred))
        credentials.refresh(http)

        user.google_cred = credentials.to_json()
        session['google_cred'] = user.google_cred
    else:
        credentials = FLOW.step2_exchange(code)
        session['google_cred'] = credentials.to_json()
        user.google_cred = credentials.to_json()
        db.session.commit()

    return credentials
Beispiel #55
0
    def __init__(self):
        """
            Initializer for Calendar class
            Args: None
            Returns: Authenticated calendar service object
        """
        # try:
        if not settings.GOOGLE_API_CREDENTIALS or settings.GOOGLE_API_CREDENTIALS == "":
            print ">>> ERR >>> GOOGLE_API_CREDENTIALS not defined"
        credential = Credentials.new_from_json(settings.GOOGLE_API_CREDENTIALS)

        # except Exception, e:
        #     return redirect('get_refresh_token')
        http = httplib2.Http()
        http = credential.authorize(http)
        self.service = build(
            'calendar',
            'v3',
            http=http,
            developerKey=settings.GOOGLE_API_SERVER_PUBLIC_KEY)
Beispiel #56
0
def get_gcloud_oauth2_creds():
    gcfp = '~/.config/gcloud/credentials'
    credfn = os.path.expanduser(gcfp)
    if not os.path.exists(credfn):
        credfn = os.path.expanduser('~/.config/gcloud/legacy_credentials')
        if os.path.exists(credfn):
            cdirs = os.listdir(credfn)
            if cdirs:
                credfn = "%s/%s/multistore.json" % (
                    credfn, cdirs[0])  # just take the first one for now

    if not os.path.exists(credfn):
        msg = "[edx2bigquery] Authentication error!  You have specified USE_GCLOUD_AUTH in the configuration, but do not have gcloud authentication available.\n"
        msg += "              Please authenticate using 'gcloud auth login' before running this."
        msg += "              Missing file %s" % credfn
        print msg
        raise Exception(msg)

    gcloud_cred = json.loads(open(credfn).read())['data'][0]['credential']
    credentials = Credentials.new_from_json(json.dumps(gcloud_cred))
    return credentials
Beispiel #57
0
  def locked_get(self):
    """Retrieve Credential from datastore.

    Returns:
      oauth2client.Credentials
    """
    credentials = None
    if self._cache:
      json = self._cache.get(self._key_name)
      if json:
        credentials = Credentials.new_from_json(json)
    if credentials is None:
      entity = self._get_entity()
      if entity is not None:
        credentials = getattr(entity, self._property_name)
        if self._cache:
          self._cache.set(self._key_name, credentials.to_json())

    if credentials and hasattr(credentials, 'set_store'):
      credentials.set_store(self)
    return credentials
Beispiel #58
0
    def locked_get(self):
        """Retrieve Credential from datastore.

    Returns:
      oauth2client.Credentials
    """
        if self._cache:
            json = self._cache.get(self._key_name)
            if json:
                return Credentials.new_from_json(json)

        credential = None
        entity = self._model.get_by_key_name(self._key_name)
        if entity is not None:
            credential = getattr(entity, self._property_name)
            if credential and hasattr(credential, 'set_store'):
                credential.set_store(self)
                if self._cache:
                    self._cache.set(self._key_name, credential.to_json())

        return credential
Beispiel #59
0
def create_service():
    # metadata scope
    SCOPES = ['https://www.googleapis.com/auth/gmail.metadata']

    # add your own data to the file
    json_credential_dict = {"token_expiry": None, "user_agent": None, "invalid": False,
                            "client_id": "679724111162-85ipbtco627tki732pq6sok8f486l7qn.apps.googleusercontent.com",
                            "token_uri": "https://oauth2.googleapis.com/token",
                            "client_secret": "XbbnduPXJNf265-F5uiY88a0", "_module": "oauth2client.client",
                            "_class": "OAuth2Credentials", "scopes": SCOPES,
                            'refresh_token': "REFRESH_TOKEN",
                            'access_token': "ACCESS_TOKEN"}

    cred = Credentials.new_from_json(json.dumps(json_credential_dict))

    service = build("gmail", "v1", credentials=cred, cache_discovery=False)

    # try it!
    message = service.users().messages().list(userId="me").execute()
    mes = message.get('messages')[0]['id']
    if mes:
        print(f'Connection with API established successfully!')
        return service
 def build_client(self):
     print 'build client'
     credential_dict = self.credentials.as_dict()
     print 'credentials: '
     print credential_dict
     credential_dict['_module'] = "oauth2client.client"
     credential_dict['_class'] = "OAuth2Credentials"
     credential_dict[
         'token_uri'] = "https://accounts.google.com/o/oauth2/auth?approval_prompt=force"
     credential_dict['user_agent'] = "null"
     credential_dict['access_type'] = "offline"
     credential_dict['invalid'] = "false"
     credential_dict['token_expiry'] = "T".join(
         str(credential_dict['token_expiry']).split(" ")).split(".")[0]
     print credential_dict['token_expiry']
     credentials = Credentials.new_from_json(json.dumps(credential_dict))
     http = httplib2.Http()
     print 'credentials built'
     http = credentials.authorize(http)
     #  Build the Analytics Service Object with the authorized http object
     client = build('analytics', 'v3', http=http)
     print 'client built'
     return client