Example #1
0
    def acquire_token(client_secrets, oauth2_token, flags):
        """Handles the user consent process and saves the retrieved OAuth2 token

        Args:
            client_secrets              - path to client_secrets file
            oauth2_token                - path to save oauth2_token

            (YouTube Service Parameters)
            https://google-api-python-client.googlecode.com/hg/docs/epy/oauth2client.tools-module.html

            flags.auth_host_name         - Host name to use when running a local web server to handle redirects during
                                          OAuth authorization.
                                          (default: 'localhost')

            flags..auth_host_port         - Port to use when running a local web server to handle redirects during OAuth
                                          authorization.; repeat this option to specify a list of values
                                          (default: '[8080, 8090]')
                                          (an integer)

            flags.auth_local_webserver   - True/False Run a local web server to handle redirects during OAuth
                                          authorization.
                                          (default: True)
        """
        scope = ["https://www.googleapis.com/auth/youtube.upload"]
        message = (
            "Please specify a valid client_secrets.json file.\n"
            "For instructions to obtain one, please visit:\n"
            "https://docs.google.com/document/d/1ro9I8jnOCgQlWRRVCPbrNnQ5-bMvQxDVg6o45zxud4c/edit"
        )
        flow = client.flow_from_clientsecrets(client_secrets, scope=scope, message=message)
        storage = file.Storage(oauth2_token)
        tools.run_flow(flow, storage, flags)
Example #2
0
def get_user_permission():
    """Run through the OAuth flow to get credentials."""
    client_id_file = os.path.join(HERE, "instance", CLIENT_SECRET)
    store = get_credentials_store()
    flow = client.flow_from_clientsecrets(client_id_file, SCOPES)
    flow.user_agent = APPLICATION_NAME
    tools.run_flow(flow, store)
Example #3
0
def main():
    client_id = sys.argv[1]
    client_secret = sys.argv[2]
    scope = sys.argv[3]
    flow = OAuth2WebServerFlow(client_id, client_secret, scope)
    storage = Storage("google.json")
    flags = argparser.parse_args([])
    run_flow(flow, storage, flags)
Example #4
0
def build(*args, **kwargs):
    ip = get_ipython()
    if "google_credential_path" in kwargs:
        credential_path = kwargs["google_credential_path"]
        del kwargs["google_credential_path"]
    elif "Googleapihelper" in ip.config and "credential_path" in ip.config.Googleapihelper:
        credential_path = ip.config.Googleapihelper["credential_path"]
    else:
        logger.info("Credential store path not specified, trying default: " + DEFAULT_CREDENTIALS_PATH)
        credential_path = DEFAULT_CREDENTIALS_PATH

    if "google_secrets_path" in kwargs:
        secrets_path = kwargs["google_secrets_path"]
        del kwargs["google_secrets_path"]
    elif "Googleapihelper" in ip.config and "secrets_path" in ip.config.Googleapihelper:
        secrets_path = ip.config.Googleapihelper["secrets_path"]
    else:
        logger.info("Secrets path not specified, trying default: " + DEFAULT_SECRETS_PATH)
        secrets_path = DEFAULT_SECRETS_PATH

    if "redirect_uri" in kwargs:
        redirect_uri = kwargs["redirect_uri"]
        del kwargs["redirect_uri"]
    elif "Googleapihelper" in ip.config and "redirect_uri" in ip.config.Googleapihelper:
        redirect_uri = ip.config.Googleapihelper["redirect_uri"]
    else:
        logger.info("Redirect uri not specified, trying default: " + DEFAULT_REDIRECT_URI)
        redirect_uri = DEFAULT_REDIRECT_URI

    if "scope" in kwargs:
        scope = kwargs["scope"]
        del kwargs["scope"]
    elif "Googleapihelper" in ip.config and "scope" in ip.config.Googleapihelper:
        scope = ip.config.Googleapihelper["scope"]
    else:
        logger.error(
            "No scope specified in options or ipython config. "
            + "Store scope in ipython profile or specify on command line."
        )
        return None

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

    if credentials is None:
        flow = flow_from_clientsecrets(secrets_path, scope=scope, redirect_uri=redirect_uri)
        flags, kwargs = extract_flags_from_kwargs(kwargs)
        tools.run_flow(flow, storage, flags)
        credentials = storage.get()

    if credentials is None:
        logger.error("Unable to retrieve google oauth credentials")
        return None

    http = httplib2.Http()
    http = credentials.authorize(http)
    kwargs["http"] = http
    return discovery.build(*args, **kwargs)
Example #5
0
    def test_run_flow_webserver_exchange_error(self, webbrowser_open_mock, server_ctor_mock, logging_mock):
        server_ctor_mock.return_value = self.server
        self.server.query_params = {"error": "any error"}

        # Exchange returned an error code.
        with self.assertRaises(SystemExit):
            tools.run_flow(self.flow, self.storage, flags=self.server_flags)

        self.assertTrue(self.server.handle_request.called)
Example #6
0
    def test_run_flow_no_webserver_exchange_error(self, input_mock, logging_mock):
        input_mock.return_value = "auth_code"
        self.flow.step2_exchange.side_effect = FlowExchangeError()

        # Error while exchanging.
        with self.assertRaises(SystemExit):
            tools.run_flow(self.flow, self.storage, flags=self.flags)

        self.flow.step2_exchange.assert_called_once_with("auth_code", http=None)
Example #7
0
    def test_run_flow_webserver_no_code(self, webbrowser_open_mock, server_ctor_mock, logging_mock):
        server_ctor_mock.return_value = self.server
        self.server.query_params = {}

        # No code found in response
        with self.assertRaises(SystemExit):
            tools.run_flow(self.flow, self.storage, flags=self.server_flags)

        self.assertTrue(self.server.handle_request.called)
Example #8
0
def getCredentials(secrets_file, tokens_file, scopes, flags):
    # create an auth flow in case we need to authenticate
    auth_flow = flow_from_clientsecrets(secrets_file, scope=scopes, message="Visit the APIs Console")
    # search for existing tokens
    storage = Storage(tokens_file)
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        run_flow(auth_flow, storage, flags, http=Http())
        return storage.get()
    return credentials
Example #9
0
 def client(self):
     http_client = httplib2.Http()
     credential_store = self.credential_store()
     credentials = credential_store.get()
     if not credentials or credentials.invalid:
         flow = client.OAuth2WebServerFlow(
             client_id=self.client_secrets["client_id"],
             client_secret=self.client_secrets["client_secret"],
             scope=self.scope,
             user_agent=self.user_agent,
             redirect_url="urn:ietf:wg:oauth:2.0:oob",
         )
         tools.run_flow(flow, credential_store, self.args)
     credential_store.get().authorize(http_client)
     return http_client
Example #10
0
def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential../
    """
    home_dir = os.path.expanduser("~")
    # credential_dir = os.path.join(home_dir, '.credentials')
    credential_dir = "/home/nikolay/playgarden/google_calendar"
    print("credential_dir" + str(credential_dir))
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir, "client_secret.json1")
    print("Credential_Path: " + str(credential_path))

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        print("OLOLO")
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else:  # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print("Storing credentials to " + credential_path)
    return credentials
Example #11
0
    def get_credentials(self):
        try:
            from oauth2client.client import OAuth2WebServerFlow
            from oauth2client.file import Storage
            from oauth2client.tools import run_flow, argparser

        except ImportError:
            raise ImportError("Could not import Google API Client.")

        _check_google_client_version()

        flow = OAuth2WebServerFlow(
            client_id="495642085510-k0tmvj2m941jhre2nbqka17vqpjfddtd.apps.googleusercontent.com",
            client_secret="kOc9wMptUtxkcIFbtZCcrEAc",
            scope="https://www.googleapis.com/auth/bigquery",
            redirect_uri="urn:ietf:wg:oauth:2.0:oob",
        )

        storage = Storage("bigquery_credentials.dat")
        credentials = storage.get()

        if credentials is None or credentials.invalid or self.reauth:
            credentials = run_flow(flow, storage, argparser.parse_args([]))

        return credentials
Example #12
0
def get_authenticated_service(user_key):

    args = namedtuple("flags", ["noauth_local_webserver", "logging_level"])

    args.noauth_local_webserver = True
    args.logging_level = "ERROR"

    auth = yt[user_key]  ## from dict of credentials
    filename = auth["filename"]

    # how and where tokens are stored
    storage = Storage(filename)

    # http://google-api-python-client.googlecode.com/hg/docs/epy/oauth2client.multistore_file-module.html

    credentials = storage.get()

    if credentials is None or credentials.invalid:

        flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=YOUTUBE_READ_WRITE_SCOPE)

        # do the "allow access" step, save token.
        credentials = run_flow(flow, storage, args)

    return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, http=credentials.authorize(httplib2.Http()))
Example #13
0
def main(argv):
    # Parse the command-line flags.
    flags = parser.parse_args(argv[1:])

    # If the credentials don't exist or are invalid run through the native client
    # flow. The Storage object will ensure that if successful the good
    # credentials will get written back to the file.
    storage = file.Storage("github-timeline.dat")
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(FLOW, storage, flags)

    # Create an httplib2.Http object to handle our HTTP requests and authorize it
    # with our good Credentials.
    http = httplib2.Http()
    http = credentials.authorize(http)

    # Construct the service object for the interacting with the BigQuery API.
    service = discovery.build("bigquery", "v2", http=http)

    try:
        # print "Success! Now add code here."
        runSyncQuery(service, "cmpe272-group8", "publicdata:samples", 1000)

    except client.AccessTokenRefreshError:
        print ("The credentials have been revoked or expired, please re-run" "the application to re-authorize")
Example #14
0
def get_credentials(client_secret_file, default_token, scopes):
    """
    FIXME DOCs
    Taken from:
    https://developers.google.com/drive/web/quickstart/python
    """
    try:
        import argparse

        flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_known_args()[0]
    except ImportError:
        flags = None
        logr.error("Unable to parse oauth2client args; `pip install argparse`")

    store = file.Storage(default_token)

    credentials = store.get()
    if not credentials or credentials.invalid:

        flow = client.flow_from_clientsecrets(client_secret_file, scopes)
        flow.redirect_uri = client.OOB_CALLBACK_URN
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else:  # Needed only for compatability with Python 2.6
            credentials = tools.run(flow, store)
        # logr.info('Storing credentials to ' + default_token)

    return credentials
Example #15
0
    def _get_credentials(keyfile):
        """
        Gets valid user credentials from storage.

        If nothing has been stored, or if the stored credentials are invalid,
        the OAuth2 flow is completed to obtain the new credentials.

        Returns:
            Credentials, the obtained credential.
        """

        home_dir = os.path.expanduser("~")  # TODO(KNR): is this portable to Windows?
        credential_dir = os.path.join(home_dir, ".caspr")  # TODO(KNR): is this portable to Windows?
        if not os.path.exists(credential_dir):
            os.makedirs(credential_dir)
        credential_path = os.path.join(credential_dir, "drive.json")

        store = oauth2client.file.Storage(credential_path)
        credentials = store.get()
        if not credentials or credentials.invalid:
            flags = tools.argparser.parse_args(args=[])
            flow = client.flow_from_clientsecrets(keyfile, SCOPES)
            flow.user_agent = APPLICATION_NAME
            credentials = tools.run_flow(flow, store, flags)
        return credentials
Example #16
0
def main(argv):
    # Parse the command-line flags.
    flags = parser.parse_args(argv[1:])

    # If the credentials don't exist or are invalid run through the native client
    # flow. The Storage object will ensure that if successful the good
    # credentials will get written back to the file.
    configdir = os.path.expanduser("~/.gget")
    if not os.path.exists(configdir):
        os.makedirs(configdir, 0700)
    storage = file.Storage(os.path.join(configdir, "auth.dat"))
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(FLOW, storage, flags)

    # Create an httplib2.Http object to handle our HTTP requests and authorize it
    # with our good Credentials.
    http = httplib2.Http()
    http = credentials.authorize(http)

    # Construct the service object for the interacting with the Drive API.
    drive = discovery.build("drive", "v2", http=http)

    try:
        for item in ls(drive, flags.gdrive_path):
            download(drive, item["id"], flags.dest_path, item)

    except client.AccessTokenRefreshError:
        print("The credentials have been revoked or expired, please re-run" "the application to re-authorize")
Example #17
0
def main(argv):
    flags = parser.parse_args(argv[1:])
    storage = file.Storage("sample.dat")
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(FLOW, storage, flags)

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

    service = discovery.build("storage", _API_VERSION, http=http)
    options = {"1": put, "2": exitprog, "3": listobj, "4": deleteobj, "5": connect2cloud, "6": exitprog}
    while True:
        print ("\nSelect any of the options from the menu.\n")
        print ("1:Upload CSV file\n2:Download\n")
        print ("3:List Files in Cloud\n4:Delete\n6:Exit")
        print ("5:Connect to Cloud SQL\n")
        option = raw_input("Enter the option:")
        if option not in options:
            print "Invalid option!!Please try again.\n"
            continue
        else:
            if option in ["3", "6"]:
                options[option](service)
            elif option in ["5"]:
                options[option]()
            else:
                filename = raw_input("\nEnter the filename with extension:")
                options[option](service, filename)
Example #18
0
def get_credentials(flags):
    """
    Read token file from ./.credentials/drive-access.json or create one if not exist.
    Creation process will ask user to copy url that display on screen to get allow token.
    :param flags : oauth2client flags. read more [https://goo.gl/dL03yF]
    :return:
        Oauth2 credential ready for use in client
    """
    home_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
    credential_dir = os.path.join(home_dir, ".credentials")
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir, "drive-access.json")
    logger.debug("Get credentials : %s", credential_path)

    store = oauth_file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        logger.info("Not found credentials. Try to get new key.")
        flow = oauth_client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if not flags:
            # if function call with non-implement flags, force to use default flags for oauth2client api
            import argparse

            parser = argparse.ArgumentParser(parents=[oauth_tools.argparser])
            flags = parser.parse_args()
        credentials = oauth_tools.run_flow(flow, store, flags)
        logger.debug("Storing credentials to %s", credential_path)

    logger.debug("Init credential success : %s", credentials)
    return credentials
Example #19
0
def CredentialsFromFile(path, client_info, oauth2client_args=None):
    """Read credentials from a file."""
    credential_store = multistore_file.get_credential_storage(
        path, client_info["client_id"], client_info["user_agent"], client_info["scope"]
    )
    if hasattr(FLAGS, "auth_local_webserver"):
        FLAGS.auth_local_webserver = False
    credentials = credential_store.get()
    if credentials is None or credentials.invalid:
        print("Generating new OAuth credentials ...")
        for _ in range(20):
            # If authorization fails, we want to retry, rather than let this
            # cascade up and get caught elsewhere. If users want out of the
            # retry loop, they can ^C.
            try:
                flow = oauth2client.client.OAuth2WebServerFlow(**client_info)
                flags = _GetRunFlowFlags(args=oauth2client_args)
                credentials = tools.run_flow(flow, credential_store, flags)
                break
            except (oauth2client.client.FlowExchangeError, SystemExit) as e:
                # Here SystemExit is "no credential at all", and the
                # FlowExchangeError is "invalid" -- usually because
                # you reused a token.
                print("Invalid authorization: %s" % (e,))
            except httplib2.HttpLib2Error as e:
                print("Communication error: %s" % (e,))
                raise exceptions.CredentialsError("Communication error creating credentials: %s" % e)
    return credentials
Example #20
0
def get_credentials():
    """Gets valid user credentials from storage
    If nothing has been stored, of ir the stored credential are invalid,
    the OAuth2 flow is completed to ogtain the new credentials.

    Returns:
    the obtained credential.
    """
    home_dir = os.path.expanduser("~")  # homedir='/usr/VuThaiHa
    credential_dir = os.path.join(home_dir, ".credentials")  #'/usr/VuThaiHa/.credentials'
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir, "googleDriveTerminal-trial.json")
    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()

    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else:  # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print("Storing credentials to " + credential_path)
    return credentials
Example #21
0
def from_secrets_file(
    client_secrets,
    storage=None,
    flags=None,
    storage_path=None,
    api_version="v3",
    readonly=False,
    http_client=None,
    ga_hook=None,
):
    """Create a client for a web or installed application.

    Create a client with a client secrets file.

    Args:
        client_secrets: str, path to the client secrets file (downloadable from
                             Google API Console)
      storage: oauth2client.client.Storage, a Storage implementation to store
               credentials.
      storage_path: str, path to a file storage.
      readonly: bool, default False, if True only readonly access is requested
                from GA.
      http_client: httplib2.Http, Override the default http client used.
      ga_hook: function, a hook that is called every time a query is made
               against GA.
    """
    scope = GOOGLE_API_SCOPE_READONLY if readonly else GOOGLE_API_SCOPE
    flow = flow_from_clientsecrets(client_secrets, scope=scope)
    storage = _get_storage(storage, storage_path)
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = run_flow(flow, storage, flags)

    return Client(_build(credentials, api_version, http_client), ga_hook)
def main(argv):
    # Parse the command-line flags.
    flags = parser.parse_args(argv[1:])

    # If the credentials don't exist or are invalid run through the native client
    # flow. The Storage object will ensure that if successful the good
    # credentials will get written back to the file.
    storage = file.Storage("youtubeplaylistbot_credentials.dat")
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(FLOW, storage, flags)

    # Create an httplib2.Http object to handle our HTTP requests and authorize it
    # with our good Credentials.
    http = httplib2.Http()
    http = credentials.authorize(http)

    # Construct the service object for the interacting with the YouTube Data API.
    service = discovery.build("youtube", "v3", http=http)

    try:
        run_bot(service)

    except client.AccessTokenRefreshError:
        print("The credentials have been revoked or expired, please re-run" "the application to re-authorize")
Example #23
0
    def get_service(self):
        if not self.service:
            # If the credentials don't exist or are invalid run through the native client
            # flow. The Storage object will ensure that if successful the good
            # credentials will get written back to the file.
            storage = file.Storage(os.path.join(os.path.dirname(__file__), "credentials.dat"))
            credentials = storage.get()
            if credentials is None or credentials.invalid:
                # Set up a Flow object to be used for authentication.
                # Add one or more of the following scopes. PLEASE ONLY ADD THE SCOPES YOU
                # NEED. For more information on using scopes please see
                # <https://developers.google.com/+/best-practices>.
                FLOW = client.flow_from_clientsecrets(
                    self.CLIENT_SECRETS,
                    scope=["https://www.googleapis.com/auth/calendar.readonly"],
                    message=tools.message_if_missing(self.CLIENT_SECRETS),
                )

                credentials = tools.run_flow(FLOW, storage, self.flags)

            # Create an httplib2.Http object to handle our HTTP requests and authorize it
            # with our good Credentials.
            http = httplib2.Http()
            http = credentials.authorize(http)
            # Construct the service object for the interacting with the Calendar API.
            self.service = discovery.build("calendar", "v3", http=http)

        return self.service
def get_credentials(flags):
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser("~")
    credential_dir = os.path.join(home_dir, ".config", "google-photo-dedup")
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir, "auth-cache.json")
    client_secret_path = os.path.join(credential_dir, "client_id.json")

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(client_secret_path, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else:  # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print("Storing credentials to " + credential_path)
    return credentials
def setup(flags):
    """Handles authentication and loading of the API.

  Args:
    flags: command-line flags obtained by calling ''get_arguments()''.

  Returns:
    An initialized service object.
  """
    # Name of a file containing the OAuth 2.0 information for this
    # application, including client_id and client_secret, which are found
    # on the Credentials tab on the Google Developers Console.
    client_secrets = os.path.join(os.path.dirname(__file__), "client_secrets.json")

    # Set up a Flow object to be used if we need to authenticate.
    flow = client.flow_from_clientsecrets(
        client_secrets, scope=API_SCOPES, message=tools.message_if_missing(client_secrets)
    )

    # Prepare credentials, and authorize HTTP object with them.
    # If the credentials don't exist or are invalid run through the installed
    # client flow. The Storage object will ensure that if successful the good
    # credentials will get written back to a file.
    storage = oauthFile.Storage(CREDENTIAL_STORE_FILE)
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage, flags)
    http = credentials.authorize(http=httplib2.Http())

    # Construct and return a service object via the discovery service.
    return discovery.build(API_NAME, API_VERSION, http=http)
def main(argv):
    # Parse the command-line flags.
    flags = parser.parse_args(argv[1:])

    # If the credentials don't exist or are invalid run through the native client
    # flow. The Storage object will ensure that if successful the good
    # credentials will get written back to the file.
    storage = file.Storage("sample.dat")
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(FLOW, storage, flags)

    # Create an httplib2.Http object to handle our HTTP requests and authorize it
    # with our good Credentials.
    http = httplib2.Http()
    http = credentials.authorize(http)

    # Construct the service object for the interacting with the Calendar API.
    service = discovery.build("calendar", "v3", http=http)

    events = service.events().list(calendarId="noterrain@gmail.com").execute()
    # service.events().insert(calendarId='noterrain@gmail.com', body="{u'status': u'confirmed', u'kind': u'calendar#event', u'end': {u'dateTime': u'2013-09-22T17:30:00-04:00'}, u'description': u'This is robtime event', u'created': u'2013-09-23T00:05:23.000Z', u'iCalUID': u'tjd87p4ebs0f8fe0bviv5l7jto@google.com', u'reminders': {u'useDefault': True}, u'htmlLink': u'https://www.google.com/calendar/event?eid=dGpkODdwNGViczBmOGZlMGJ2aXY1bDdqdG8gbm90ZXJyYWluQG0', u'sequence': 0, u'updated': u'2013-09-23T00:05:23.527Z', u'summary': u'Appropriating Interaction Technologies', u'start': {u'dateTime': u'2013-09-22T18:00:00-09:00'}, u'etag': u'"B0R-JqZ1uFKvtifdS4AVDz7BCB4/MTM3OTg5NDcyMzUyNzAwMA"', u'organizer': {u'self': True, u'displayName': u'Tianyu WU', u'email': u'noterrain@gmail.com'}, u'creator': {u'self': True, u'displayName': u'Tianyu WU', u'email': u'noterrain@gmail.com'}, u'id': u'tjd87p4ebs0f8fe0bviv5l7jto'}])",sendNotifications=None, maxAttendees=None)
    print events["items"][0]["end"]

    try:
        print "Success! Now add code here."

    except client.AccessTokenRefreshError:
        print ("The credentials have been revoked or expired, please re-run" "the application to re-authorize")
    def setup(self, client_secrets):
        storage = Storage("credentials.dat")
        credentials = storage.get()

        if credentials is None or credentials.invalid:
            flow = flow_from_clientsecrets(
                client_secrets,
                scope="https://www.googleapis.com/auth/genomics",
                message="You need to copy a client_secrets.json file into this directory, "
                "or pass in the --client_secrets_filename option to specify where "
                "one exists. See the README for more help.",
            )

            # There's probably a better way to generate the 'flags' object.  Doing it this way for now.
            parser = argparse.ArgumentParser(
                description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser]
            )
            parser.add_argument(
                "--client_secrets_filename",
                default=client_secrets,
                help="The filename of a client_secrets.json file from a "
                'Google "Client ID for native application" that '
                "has the Genomics API enabled.",
            )
            flags = parser.parse_args()

            credentials = run_flow(flow, storage, flags)
            # Create a genomics API service
        http = httplib2.Http()
        http = credentials.authorize(http)
        service = build("genomics", "v1beta2", http=http)
        return service
def goog_get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """

    SCOPES = "https://www.googleapis.com/auth/calendar.readonly"
    CLIENT_SECRET_FILE = "/.credentials/client_secret.json"
    APPLICATION_NAME = "Olin calendar synchronization project (beta)"

    credential_dir = "/.credentials"
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir, "google-calendar-credentials.json")

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME

        credentials = tools.run_flow(flow, store, flags)
        print "Storing credentials to " + credential_path
    return credentials
Example #29
0
def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser("~")
    credential_dir = os.path.join(home_dir, ".credentials")
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir, "gmail-python-quickstart.json")

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else:  # Needed only for compatability with Python 2.6
            credentials = tools.run(flow, store)
        print("Storing credentials to " + credential_path)
    return credentials
Example #30
0
    def get_credentials(self):
        """Gets valid user credentials from storage.

        If nothing has been stored, or if the stored credentials are invalid,
        the OAuth2 flow is completed to obtain the new credentials.

        Returns:
            Credentials, the obtained credential.
        """
        credential_dir = resource_path(".credentials")
        if not os.path.exists(credential_dir):
            os.makedirs(credential_dir)
        credential_path = os.path.join(credential_dir, "ucal.json")

        store = oauth2client.file.Storage(credential_path)
        credentials = store.get()
        if not credentials or credentials.invalid:

            flow = client.flow_from_clientsecrets(self.CLIENT_SECRET_FILE, self.SCOPES)

            flow.user_agent = self.APPLICATION_NAME
            if self.flags:
                credentials = tools.run_flow(flow, store, self.flags)
            else:  # Needed only for compatibility with Python 2.6
                credentials = tools.run(flow, store)
            print "Storing credentials to " + credential_path
        return credentials