示例#1
0
    def create_service(scope, CLIENT_CREDENTIALS_FILE, CLIENT_SECRET_FILE):

        # Run through the OAuth flow and retrieve credentials
        flow = None
        try:
            flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, scope=scope, redirect_uri="urn:ietf:wg:oauth:2.0:oob")
        except Exception, e:
            flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, scope=scope)
示例#2
0
def get_credentials():
    try:
        flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
    except ImportError:
        flags = None
        
    store = file.Storage(_consts.STORAGE)
    creds = store.get()
   
    if not creds or creds.invalid:
        client.flow_from_clientsecrets(_consts.CLIENT_SECRET, _consts.SCOPES)
        tools.run_flow(flow, store, flags)

    return creds;
示例#3
0
def oauth2callback():
  flow = client.flow_from_clientsecrets(
      CLIENT_SECRETS,
      scope='https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.email',
      redirect_uri=flask.url_for('oauth2callback', _external=True))
  if 'code' not in flask.request.args:
    auth_uri = flow.step1_get_authorize_url()
    # webbrowser.open_new_tab(auth_uri)
    return flask.redirect(auth_uri)
  else:
    auth_code = flask.request.args.get('code')
    credentials = flow.step2_exchange(auth_code)
    flask.session['credentials'] = credentials.to_json()
    
    http_auth = credentials.authorize(httplib2.Http())
    result = main.classes(http_auth, flask.session["initData"])

    campus = flask.session["initData"]["campus"][::]

    flask.session.pop("initData",None)

    if "success" in result:
      return flask.redirect(flask.url_for("index"+campus)+'#'+result["course"].replace(" ","+"))
    else:
      return flask.redirect(flask.url_for('index'+campus)+"#BadInput")
    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
示例#5
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,
                                   'peacemail.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(constants.CLIENT_SECRET_FILE, constants.AUTHORIZATION_SCOPE)
        flow.user_agent = constants.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
示例#6
0
    def get_credentials(self):

        if not os.path.exists(CLIENT_SECRET_FILE):
            print("the credentials file is missing. follow the tutorial in the readme so you know what to do")
            exit()
        """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,
                                       'drive-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 compatibility with Python 2.6
                credentials = tools.run(flow, store)
            print('Storing credentials to ' + credential_path)
        return credentials
示例#7
0
def auth():
    """
    Returns an auth code after user logs in through Google+.
    :param string code: code that is passed in through Google+.
                        Do not provide this yourself.
    :return: An html page with an auth code.
    :rtype: flask.Response
    """

    # Get code from params.
    code = request.args.get('code')
    if not code:
        return render_template('auth.html',
                               success=False)

    try:
        # Exchange code for email address.
        # Get Google+ ID.
        oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
        gplus_id = credentials.id_token['sub']

        # Get first email address from Google+ ID.
        http = httplib2.Http()
        http = credentials.authorize(http)

        h, content = http.request(
            'https://www.googleapis.com/plus/v1/people/' + gplus_id, 'GET')
        data = json.loads(content)
        email = data["emails"][0]["value"]

        # Verify email is valid.
        regex = re.match(CU_EMAIL_REGEX, email)

        if not regex:
            return render_template('auth.html',
                                   success=False,
                                   reason="Please log in with your " +
                                   "Columbia or Barnard email. You logged " +
                                   "in with: " + email)

        # Get UNI and ask database for code.
        uni = regex.group('uni')
        code = db.get_oauth_code_for_uni(g.cursor, uni)
        return render_template('auth.html', success=True, uni=uni, code=code)
    except psycopg2.IntegrityError:
        return render_template('auth.html',
                               success=False,
                               reason="Attempt to generate API key resulted in"
                                      " a collision with another key in the"
                                      " database. Please refresh to try and"
                                      " generate a new key.")

    except Exception as e:
        # TODO: log errors
        print(e)
        return render_template('auth.html',
                               success=False,
                               reason="An error occurred. Please try again.")
    def __enter__(self):
        # Ensure that we have not re-entered
        if self.temp_path != None or self.service != None:
            raise Exception('Cannot use multiple nested with blocks on same Youtube object!')

        flow = flow_from_clientsecrets(
            self.client_secrets_path,
            scope=YOUTUBE_UPLOAD_SCOPE,
            message=MISSING_CLIENT_SECRETS_MESSAGE)

        temp_file = NamedTemporaryFile(delete=False)
        self.temp_path = temp_file.name
        temp_file.close()

        storage = Storage(self.temp_path)
        credentials = storage.get()

        if credentials is None or credentials.invalid:
            credentials = run_flow(
                flow, storage, argparser.parse_args(list())
            )

        self.service = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
            http=credentials.authorize(httplib2.Http()))

        return self
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.
    """
    try:
        import argparse
        flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
    except ImportError:
        flags = None

    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,
                                   'calendar-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
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,'')  #,'Google Drive/G/IT/Development/ETL/.credentials') #JLD - customized path to working directory
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir, 'client_secret.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
示例#11
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.
    """

    # TODO: fetch the path from the current dir
    home_dir = '/home/paraboul'
    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,
                                   'calendar-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 compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials
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('~') #/Users/TMD
    credential_dir = os.path.join(home_dir, '.credentials') #This line adds the directory .credentials to my home_dir so /Users/TMD/.credentials
    print credential_dir
    #If the credentials directory does not exist, the conditional creates the credential 
    #directory and joins it's json file containing the id and pwd to the credentials directory
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'task-manager.json')
    store = oauth2client.file.Storage(credential_path) #Creates an object named store <oauth2client.file.Storage object at 0x10324c6d0>
    credentials = store.get() #Applies the get() method on the object and stores the new object as credentials
    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
示例#13
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.
        """
        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,
                                       'calendar-python-sisgap.json')

        store = oauth2client.file.Storage(credential_path)
        credentials = store.get()
        if not credentials or credentials.invalid:
            flow = client.flow_from_clientsecrets(
                self._google_client_secret_file, self._google_scopes)
            flow.user_agent = self._google_application_name
            credentials = tools.run_flow(flow, store, None)

        return credentials
示例#14
0
def init(argv, name, version, doc, filename, scope=None, parents=[]):
  """A common initialization routine for samples.

  Many of the sample applications do the same initialization, which has now
  been consolidated into this function. This function uses common idioms found
  in almost all the samples, i.e. for an API with name 'apiname', the
  credentials are stored in a file named apiname.dat, and the
  client_secrets.json file is stored in the same directory as the application
  main file.

  Args:
    argv: list of string, the command-line parameters of the application.
    name: string, name of the API.
    version: string, version of the API.
    doc: string, description of the application. Usually set to __doc__.
    file: string, filename of the application. Usually set to __file__.
    parents: list of argparse.ArgumentParser, additional command-line flags.
    scope: string, The OAuth scope used.

  Returns:
    A tuple of (service, flags), where service is the service object and flags
    is the parsed command-line flags.
  """
  if scope is None:
    scope = 'https://www.googleapis.com/auth/' + name

  # Parser command-line arguments.
  parent_parsers = [tools.argparser]
  parent_parsers.extend(parents)
  parser = argparse.ArgumentParser(
      description=doc,
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=parent_parsers)
  flags = parser.parse_args(argv[1:])

  # Name of a file containing the OAuth 2.0 information for this
  # application, including client_id and client_secret, which are found
  # on the API Access tab on the Google APIs
  # Console <http://code.google.com/apis/console>.
  client_secrets = os.path.join(os.path.dirname(filename),
                                'client_secrets.json')

  # Set up a Flow object to be used if we need to authenticate.
  flow = client.flow_from_clientsecrets(client_secrets,
      scope=scope,
      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 native client
  # flow. The Storage object will ensure that if successful the good
  # credentials will get written back to a file.
  storage = file.Storage(name + '.dat')
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)
  http = credentials.authorize(http = httplib2.Http())

  # Construct a service object via the discovery service.
  service = discovery.build(name, version, http=http)
  return (service, flags)
示例#15
0
def main(argv):
    # create the orchestration object
    gce_cluster = GceCondor(None, PROJECT_ID)

    # create the top-level parser
    parser = argparse.ArgumentParser(parents=[argparser])
    subparsers = parser.add_subparsers()

    # create the parser for the "start_cluster" command
    parser_start = subparsers.add_parser('start', help="start a condor cluster")
    parser_start.add_argument('node_count', type=int, default=1, help="the number of nodes, including master")
    parser_start.add_argument('-i', '--image', action="store_true", help="create instance from predefined image")
    parser_start.set_defaults(func=gce_cluster.start)

    # create the parser for the "terminate" command
    parser_terminate = subparsers.add_parser('terminate', help="shutdown cluster, ie terminate all instances in project")
    parser_terminate.set_defaults(func=gce_cluster.terminate)

    args = parser.parse_args(argv)

    # Perform OAuth 2.0 authorization.
    flow = flow_from_clientsecrets(CLIENT_SECRETS, scope=GCE_SCOPE)
    storage = Storage(OAUTH2_STORAGE)
    credentials = storage.get()

    if credentials is None or credentials.invalid:
        credentials = run_flow(flow, storage, args)
    http = httplib2.Http()
    auth_http = credentials.authorize(http)

    # update the orchestration object with the authorized Http object
    gce_cluster.set_auth_http(auth_http)

    # perform the command
    args.func(args)
示例#16
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-empty-trash.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)
        print('Storing credentials to ' + credential_path)
    return credentials
示例#17
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, '.eam')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'access_token.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    flags = tools.argparser.parse_args(args=[])
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE,  scope=' '.join(SCOPES))
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials
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, "calendar-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
示例#19
0
def authorize_google_calendar():
    FLOW = flow_from_clientsecrets(flask_config.INSTALLED_APP_SECRET_PATH,
                   scope='https://www.googleapis.com/auth/calendar')

    # Save the credentials file here for use by the app
    storage = Storage(flask_config.INSTALLED_APP_CREDENTIALS_PATH)
    run_flow(FLOW, storage, FLAGS)
示例#20
0
def authenService():
    CLIENT_SECRETS_FILE = "client_secrets.json"
    #display following message if file not found
    MISSING_CLIENT_SECRETS_MESSAGE = """
WARNING: Please configure OAuth 2.0

To make this sample run you will need to populate the client_secrets.json file
found at:

   %s

with information from the Developers Console
https://console.developers.google.com/

For more information about the client_secrets.json file format, please visit:
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),
                                   CLIENT_SECRETS_FILE))

    YOUTUBE_READ_WRITE_SCOPE = "https://www.googleapis.com/auth/youtube"
    YOUTUBE_API_SERVICE_NAME = "youtube"
    YOUTUBE_API_VERSION = "v3"

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

    storage = Storage("%s-oauth2.json" % sys.argv[0])
    credentials = storage.get()

    if credentials is None or credentials.invalid:
        flags = argparser.parse_args()
        credentials = run_flow(flow, storage, flags)

    youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,http=credentials.authorize(httplib2.Http()))
    return youtube
示例#21
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('C:\\Users\\nmishra\\PycharmProjects\\EDI\\')
    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 compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials
示例#22
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
def get_credentials(calendar_name):
    """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.
    """
    credentials_file = settings.CALENDAR_CREDENTIALS[calendar_name]["credentials_file"]
    client_secret_file = settings.CALENDAR_CREDENTIALS[calendar_name]["client_secret_file"]

    project_dir = os.path.dirname(os.path.realpath(__file__))
    credential_dir = project_dir
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir, credentials_file)

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

    if not credentials or credentials.invalid:
        client_secret_file_path = os.path.join(project_dir, client_secret_file)
        flow = client.flow_from_clientsecrets(client_secret_file_path, SCOPES)
        flow.user_agent = APPLICATION_NAME

        flags = tools.argparser.parse_args(args=[])
        credentials = tools.run_flow(flow, store, flags)

        logger.info('[google_calendar_backend] Storing GCal acccess credentials to ' + credential_path)

    return credentials
    def auth_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 = './'
        if not os.path.exists(credential_dir):
            os.makedirs(credential_dir)
        credential_path = os.path.join(credential_dir,
                                       self._session_file)

        store = oauth2client.file.Storage(credential_path)
        self._credentials = store.get()
        if not self._credentials or self._credentials.invalid:
            flow = client.flow_from_clientsecrets(self._client_secret_file, self._scopes)
            flow.user_agent = self._application_name
            flow.params['access_type'] = 'offline'
            if flags:
                self._credentials = tools.run_flow(flow, store, flags)
            else: # Needed only for compatability with Python 2.6
                self._credentials = tools.run(flow, store)

        # Authorize with HTTP
        self._http = self._credentials.authorize(httplib2.Http())

        # Setup Service in order to upload file
        self._service = discovery.build('drive', 'v2', http=self._http)
    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))
def load_user_credentials(client_secrets, storage, flags):
  """Attempts to load user credentials from the provided client secrets file.

  Args:
    client_secrets: path to the file containing client secrets.
    storage: the data store to use for caching credential information.
    flags: command-line flags.

  Returns:
    A credential object initialized with user account credentials.
  """
  # 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))

  # Retrieve credentials from storage.
  # 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 file.
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)

  return credentials
def get_email_service(config):
    """Return an authorized Gmail API service instance."""
    google_client_secret_path = config.get_google_client_secret_path()
    print("google_client_secret_path: {0}".format(google_client_secret_path))
    # The "scope" scope allows--
    #   "Create, read, update, and delete drafts. Send messages and drafts."
    # Check https://developers.google.com/gmail/api/auth/scopes for all
    # available scopes
    OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.compose'
    # Start the OAuth flow to retrieve credentials
    flow = flow_from_clientsecrets(google_client_secret_path, scope=OAUTH_SCOPE)

    http = httplib2.Http()
    # Get default flags.
    parser = argparse.ArgumentParser(parents=[tools.argparser])
    flags = parser.parse_args([])
    print("debug: flags: {0!r}".format(flags))
    # Location of the credentials storage file
    storage_path = config.get_gmail_storage_path()
    storage = Storage(storage_path)
    # Try to retrieve credentials from storage or run the flow to generate them
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage, flags=flags, http=http)

    # Authorize the httplib2.Http object with our credentials
    http = credentials.authorize(http)

    # Build the Gmail service from discovery
    gmail_service = build('gmail', 'v1', http=http)

    return gmail_service
示例#28
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, '.gflows')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'credential.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        script_path = os.path.dirname(os.path.realpath(__file__))
        flow = client.flow_from_clientsecrets(os.path.join(script_path,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
示例#29
0
def connect(request):

    # Ensure that the request is not a forgery and that the user sending this connect request is the expected user.
    if request.POST['state'.decode("utf-8")] != request.session['state']:
        return redirect(reverse("ding:error_401"))

    # Retrieve the authorization code
    code = request.POST['authCode'.decode("utf-8")]
    # Upgrade the authorization code into a credentials object
    try:
        oauth_flow = flow_from_clientsecrets(os.path.join(BASE, "client_secrets.json"), scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        return redirect(reverse("ding:error_401"))
    # Access the currently connected user
    gplus_id = credentials.id_token['sub']

    stored_credentials = request.session.get('credentials')
    stored_gplus_id = request.session.get('gplus_id')

    # Updated the credentials and id if necessary
    if stored_gplus_id != gplus_id or stored_credentials is None:
        request.session['credentials'] = credentials.to_json()
        request.session['gplus_id'] = gplus_id

    # Respond with success url
    response_data = {}
    response_data['result'] = 'Success'
    response_data['message'] = 'User authenticated and session stored.'
    response_data['redirect_url'] = reverse("ding:search")
    return HttpResponse(json.dumps(response_data), content_type="application/json")
示例#30
0
def openidconnect_flow_from_clientsecrets(filename, scope = GOOGLE_OPENIDCONNECT_SCOPE, message=None):
  """Create OpenID Connect Flow from a clientsecrets file.

  Will create the right kind of Flow based on the contents of the clientsecrets
  file or will raise InvalidClientSecretsError for unknown types of Flows.

  Args:
    filename: string, File name of client secrets.
    scope: string or list of strings, scope(s) to request.
    message: string, A friendly string to display to the user if the
      clientsecrets file is missing or invalid. If message is provided then
      sys.exit will be called in the case of an error. If message in not
      provided then clientsecrets.InvalidClientSecretsError will be raised.

  Returns:
    A Flow object.

  Raises:
    UnknownClientSecretsFlowError if the file describes an unknown kind of Flow.
    clientsecrets.InvalidClientSecretsError if the clientsecrets file is
      invalid.
  """

  # Check if submitted scope contains the Ope
  oauth_flow = flow_from_clientsecrets(filename,scope,message)
  return OpenIDConnectFlow(client_id = oauth_flow.client_id,
      client_secret = oauth_flow.client_secret,
      scope = oauth_flow.scope,
      user_agent = oauth_flow.user_agent,
      auth_uri = oauth_flow.auth_uri,
      token_uri = oauth_flow.token_uri)
示例#31
0
def gconnect():
    """
    this method followed the idea of udacity course about how to create
    anti forgery Oauth Signin
    """
    # Validate state token
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state parameter.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    # Obtain authorization code
    code = request.data

    try:
        # Upgrade the authorization code into a credentials object
        oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = make_response(
            json.dumps('Failed to upgrade the authorization code.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Check that the access token is valid.
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' %
           access_token)
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])
    # If there was an error in the access token info, abort.
    if result.get('error') is not None:
        response = make_response(json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is used for the intended user.
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = make_response(
            json.dumps("Token's user ID doesn't match given user ID."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is valid for this app.
    if result['issued_to'] != CLIENT_ID:
        response = make_response(
            json.dumps("Token's client ID does not match app's."), 401)
        print "Token's client ID does not match app's."
        response.headers['Content-Type'] = 'application/json'
        return response

    stored_access_token = login_session.get('access_token')
    stored_gplus_id = login_session.get('gplus_id')
    if stored_access_token is not None and gplus_id == stored_gplus_id:
        response = make_response(
            json.dumps('Current user is already\
        connected.'), 200)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Store the access token in the session for later use.
    login_session['access_token'] = credentials.access_token
    print 'accsee token = ' + login_session['access_token']
    login_session['gplus_id'] = gplus_id

    # Get user info
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)

    data = answer.json()

    login_session['username'] = data['name']
    login_session['picture'] = data['picture']
    login_session['email'] = data['email']

    output = ''
    output += '<h1>Welcome, '
    output += login_session['username']
    output += '!</h1>'
    output += '<img src="'
    output += login_session['picture']
    output += ' " style = "width: 300px; height: 300px;border-radius: 150px;-we\
    bkit-border-radius: 150px;-moz-border-radius: 150px;"> '

    flash("you are now logged in as %s" % login_session['username'])
    print "done!"
    return output
示例#32
0
    elif o == '--publish':
        isDraft = False
    elif o == '-t':
        title = a
    elif o == '-l':
        labels = a

# If we want to publish we must supply a title
if (isDraft == False and title == 'Default Title'):
    print("You must provide a title if you want to publish")
    sys.exit()

# If there is no userkey authenticate with Google and save the key.
if (os.path.exists('userkey') == False):
    flow = client.flow_from_clientsecrets(
        'client_id.json',
        scope='https://www.googleapis.com/auth/blogger',
        redirect_uri='urn:ietf:wg:oauth:2.0:oob')

    auth_uri = flow.step1_get_authorize_url()
    webbrowser.open_new(auth_uri)
    auth_code = raw_input('Enter the auth code: ')
    credentials = flow.step2_exchange(auth_code)
    http_auth = credentials.authorize(httplib2.Http())

    # Store the credentials
    storage = Storage('userkey')
    storage.put(credentials)

# If the userkey already exists use it.
else:
    storage = Storage('userkey')
示例#33
0
def gconnect():
    # Validate state token
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state parameter.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    # Obtain authorization code, now compatible with Python3
    request.get_data()
    code = request.data.decode('utf-8')

    try:
        # Upgrade the authorization code into a credentials object
        oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = make_response(
            json.dumps('Failed to upgrade the authorization code.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Check that the access token is valid.
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' %
           access_token)
    # Submit request, parse response - Python3 compatible
    h = httplib2.Http()
    response = h.request(url, 'GET')[1]
    str_response = response.decode('utf-8')
    result = json.loads(str_response)

    # If there was an error in the access token info, abort.
    if result.get('error') is not None:
        response = make_response(json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is used for the intended user.
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = make_response(
            json.dumps("Token's user ID doesn't match given user ID."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is valid for this app.
    if result['issued_to'] != CLIENT_ID:
        response = make_response(
            json.dumps("Token's client ID does not match app's."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    stored_access_token = login_session.get('access_token')
    stored_gplus_id = login_session.get('gplus_id')
    if stored_access_token is not None and gplus_id == stored_gplus_id:
        response = make_response(
            json.dumps('Current user is already connected.'), 200)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Store the access token in the session for later use.
    login_session['access_token'] = access_token
    login_session['gplus_id'] = gplus_id

    # Get user info
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)

    data = answer.json()

    login_session['username'] = data['name']
    login_session['picture'] = data['picture']
    login_session['email'] = data['email']
    login_session['provider'] = 'google'

    # see if user exists, if it doesn't make a new one
    user_id = getUserID(login_session['email'])
    if not user_id:
        user_id = createUser(login_session)
    login_session['user_id'] = user_id

    output = ''
    output += '<h1>Welcome, '
    output += login_session['username']
    output += '!</h1>'
    output += '<img src="'
    output += login_session['picture']
    output += ' " style = "width: 300px; height: 300px;'
    output += 'border-radius: 150px;-webkit-border-radius: 150px;'
    output += '-moz-border-radius: 150px;">'
    flash("you are now logged in as %s" % login_session['username'])
    return output
示例#34
0
def gconnect():
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state parameter.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    code = request.data

    try:
        oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = \
            make_response(json.dumps('''Failed to upgrade the
                                        authorization code.'''), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    access_token = credentials.access_token
    url = \
        'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' \
        % access_token
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])
    if result.get('error') is not None:
        response = make_response(json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'

    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = \
            make_response(json.dumps('''Token's user ID doesn't
                          match given user ID.'''), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    if result['issued_to'] != CLIENT_ID:
        response = \
            make_response(json.dumps('''Token's client ID does not
                                     match app's.'''), 401)
        print "Token's client ID does not match app's."
        response.headers['Content-Type'] = 'application/json'
        return response

    stored_access_token = login_session.get('access_token')
    stored_gplus_id = login_session.get('gplus_id')
    if stored_access_token is not None and gplus_id == stored_gplus_id:
        response = \
            make_response(json.dumps('''Current user is
                            already connected.'''), 200)
        response.headers['Content-Type'] = 'application/json'

    login_session['provider'] = 'google'
    login_session['access_token'] = credentials.access_token
    login_session['gplus_id'] = gplus_id

    userinfo_url = 'https://www.googleapis.com/oauth2/v1/userinfo'
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)
    data = answer.json()

    login_session['username'] = data['name']
    login_session['picture'] = data['picture']
    login_session['email'] = data['email']

    user_id = getUserID(login_session['email'])
    if not user_id:
        user_id = createUser(login_session)
    login_session['user_id'] = user_id

    output = ''
    output += '<h1>Welcome, '
    output += login_session['username']

    output += '!</h1>'
    output += '<img src="'
    output += login_session['picture']
    output += \
        ''' " style = "width: 300px;
        height: 300px;border-radius: 150px;
        -webkit-border-radius: 150px;-moz-border-radius: 150px;"> '''
    flash('you are now logged in as %s' % login_session['username'])
    print 'done!'
    return output
示例#35
0
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import redirect, render

from oauth2client.client import flow_from_clientsecrets

from .models import (
    Credential,
    User,
)

FLOW = flow_from_clientsecrets(
    settings.GOOGLE_OAUTH_CLIENT_SECRETS,
    scope=[
        'https://www.googleapis.com/auth/calendar',
        'https://www.googleapis.com/auth/userinfo.email',
    ],
    redirect_uri='http://localhost:8000/accounts/google_callback',
)


def index(request):
    return render(request,
                  'accounts/register.html', {},
                  content_type='text/html; charset=utf-8')


def google_callback(request):
    error = request.GET.get('error')
    if error:
        raise ValueError('We gots prahblems.')
def main(reportName):
    # argv = [sys.argv, argv]

    flow = client.flow_from_clientsecrets("client_secrets.json",
                                          scope=OAUTH_SCOPES)
    storage = Storage(CREDENTIAL_STORE_FILE)
    credentials = storage.get()
    http_setup = credentials.authorize(httplib2.Http())

    service = discovery.build('dfareporting', 'v3.1', http=http_setup)
    # Retrieve command line arguments.
    #flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser])

    # Authenticate and construct service.
    # service = dfareporting_utils.setup(flags)

    report_name = reportName

    ##############

    try:
        # Construct the request.
        # Profile ID
        request = service.userProfiles().list()

        # Execute request and print response.
        response = request.execute()

        get_profile = [
            profile for profile in response['items']
            if profile['accountId'] in ['817771']
        ]
        profile_id = get_profile[0]['profileId']

        print(
            '1 - Searching reports for Account ID 817771 (Diageo DCM) with Profile ID %s.'
            % profile_id)
        print()

        #############

        # Construct the request.
        # Report ID
        request = service.reports().list(profileId=profile_id)

        while True:
            # Execute request and print response.
            response = request.execute()

            report_id = []
            for report in response['items']:
                if report['name'] == report_name:
                    print('2 - Found %s report with ID %s and name "%s".' %
                          (report['type'], report['id'], report['name']))
                    print()
                    report_id.append(report['id'])
                    break

            if response['items'] and response['nextPageToken']:
                request = service.reports().list_next(request, response)
            else:
                break

        ##############

        # Run report
        report_file = service.reports().run(profileId=profile_id,
                                            reportId=report_id[0]).execute()
        print('3. File with ID %s has been created' % report_file['id'])
        print()

        # Wait for the report file to finish processing.
        # An exponential backoff strategy is used to conserve request quota.
        sleep = 0
        start_time = time.time()
        while True:
            report_file = service.files().get(
                reportId=report_id[0], fileId=report_file['id']).execute()

            status = report_file['status']
            if status == 'REPORT_AVAILABLE':
                print('5. File status is %s, ready to download.' % status)
                ####
                # Prepare a local file to download the report contents to.
                print('hi')
                out_file = io.FileIO(generate_file_name(report_file),
                                     mode='wb')

                # Create a get request.
                request = service.files().get_media(reportId=report_id[0],
                                                    fileId=report_file['id'])

                # Create a media downloader instance.
                # Optional: adjust the chunk size used when downloading the file.
                downloader = http.MediaIoBaseDownload(out_file,
                                                      request,
                                                      chunksize=CHUNK_SIZE)

                # Execute the get request and download the file.
                download_finished = False
                while download_finished is False:
                    _, download_finished = downloader.next_chunk()

                print('File %s downloaded to %s' %
                      (report_file['id'], os.path.realpath(out_file.name)))
                ####
                return
            elif status != 'PROCESSING':
                print('5. File status is %s, processing failed.' % status)
                return
            elif time.time() - start_time > MAX_RETRY_ELAPSED_TIME:
                print('5. File processing deadline exceeded.')
                return

            sleep = next_sleep_interval(sleep)
            print('4. File status is %s, sleeping for %d seconds.' %
                  (status, sleep))
            time.sleep(sleep)

    except client.AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')
示例#37
0
def gconnect():

    if request.args.get('state') != login_session['state']:

        response = make_response(json.dumps('Invalid state parameter'), 401)

        response.headers['Content-Type'] = 'application/json'

        return response

    code = request.data

    try:
        """Upgrade the authorization code into a credentials object"""

        oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')

        oauth_flow.redirect_uri = 'postmessage'

        credentials = oauth_flow.step2_exchange(code)

    except FlowExchangeError:

        response = make_response(
            json.dumps('Failed to upgrade the authorization code.'), 401)

        response.headers['Content-Type'] = 'application/json'

        return response
    """Check that access token is valid"""

    access_token = credentials.access_token

    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' %
           access_token)

    h = httplib2.Http()

    result = json.loads(h.request(url, 'GET')[1])
    """If there was an error in the access token info, abort"""

    if result.get('error') is not None:

        response = make_response(json.dumps(result.get('error')), 500)

        response.headers['Content-Type'] = 'application/json'

        return response
    """Verify that the access token is used for the intended user"""

    gplus_id = credentials.id_token['sub']

    if result['user_id'] != gplus_id:

        response = make_response(
            json.dumps("Token's user ID doesn't match given user ID"), 401)

        response.headers['Content-Type'] = 'application/json'

        return response
    """Verify that the access token is valid for this app"""

    if result['issued_to'] != CLIENT_ID:

        response = make_response(
            json.dumps("Token's client ID doesn't match app's"), 401)

        response.headers['Content-Type'] = 'application/json'

        return response
    """Check to see if user is already logged in"""

    stored_access_token = login_session.get('access_token')

    stored_gplus_id = login_session.get('gplus_id')

    if stored_access_token is not None and gplus_id == stored_gplus_id:

        response = make_response(
            json.dumps('Current user is already connected'), 200)

        response.headers['Content-Type'] = 'application/json'

        return response
    """Store the access token in the session for later use"""

    login_session['access_token'] = credentials.access_token

    login_session['gplus_id'] = gplus_id
    """Get user info and store in login session for later use"""

    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"

    params = {'access_token': credentials.access_token, 'alt': 'json'}

    answer = requests.get(userinfo_url, params=params)

    data = json.loads(answer.text)

    login_session['username'] = data['name']

    login_session['picture'] = data['picture']

    login_session['email'] = data['email']
    """See if user exists, if it doesn't make a new one"""

    user_id = getUserID(login_session['email'])

    if not user_id:

        user_id = createUser(login_session)

    login_session['user_id'] = user_id
    """Render welcome message if user logged in successfully"""

    output = ''

    output += '<h1>Welcome, '

    output += login_session['username']

    output += '!</h1>'

    output += '<img src="'

    output += login_session['picture']

    output += ' " style = "width: 300px; height: 300px;border-radius: 150px;-webkit-border-radius: 150px;-moz-border-radius: 150px;"> '

    flash("You Are Now Logged In As %s" % login_session['username'])

    print "done!"

    return output
示例#38
0
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

SCOPES = ""
CLIENT_SECRET = "client_secret.json"

store = file.Storage("storage.json")
credz = store.get()
if not credz or credz.invalid:
    flow = client.flow_from_clientsecrets(CLIENT_SECRET)
    credz = tools.run(flow, store)

SERVICE = build(API, VERSION, http=credz.authorize(Http()))
示例#39
0
def gConnect(response=response):
    if request.args.get('state') != login_session['state']:
        response.make_response(json.dumps('Invalid State paramenter'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Obtain authorization code

    code = request.data
    try:

        # Upgrade the authorization code into a credentials object

        oauth_flow = flow_from_clientsecrets('client_secret.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = make_response(
            json.dumps("""Failed to upgrade the
        authorisation code"""), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Check that the access token is valid.

    access_token = credentials.access_token
    url = \
        'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' \
        % access_token
    header = httplib2.Http()
    result = json.loads(header.request(url, 'GET')[1])

    # If there was an error in the access token info, abort.

    if result.get('error') is not None:
        response = make_response(json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is used for the intended user.

    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = make_response(
            json.dumps("""Token's user ID does not
                            match given user ID."""), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is valid for this app.

    if result['issued_to'] != CLIENT_ID:
        response = make_response(
            json.dumps("""Token's client ID
            does not match app's."""), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Store the access token in the session for later use.

    stored_credentials = login_session.get('credentials')
    stored_gplus_id = login_session.get('gplus_id')
    if stored_credentials is not None and gplus_id == stored_gplus_id:
        response = \
            make_response(json.dumps('Current user is already connected.'),
                          200)
        response.headers['Content-Type'] = 'application/json'
        return response

    login_session['credentials'] = access_token
    login_session['id'] = gplus_id

    # Get user info

    userinfo_url = 'https://www.googleapis.com/oauth2/v1/userinfo'
    params = {'access_token': access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)

    data = answer.json()

    # ADD PROVIDER TO LOGIN SESSION

    login_session['name'] = data['name']
    login_session['img'] = data['picture']
    login_session['email'] = data['email']
    login_session['provider'] = 'google'
    if not check_user():
        createUser()
    return jsonify(name=login_session['name'],
                   email=login_session['email'],
                   img=login_session['img'])
示例#40
0
def gconnect():
    """Login (and register on the fly) via Google OAUTH2 authentication"""
    # Validate state token protect against cross-site reference forgery attacks
    if request.args.get('state') != session['state']:
        response = make_response(json.dumps('Invalid state parameter.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Obtain authorization code
    # This is the one-time code that Google+ API had sent to the client
    code = request.data

    try:
        # Upgrade the authorization code into a credentials object:
        # ask google+ api server for a credentials object, using the one-time
        # code that was provided to the client and passed on via the AJAX
        # request to this gconnect function.
        file = current_app.config['GOOGLE_OAUTH2_FILE']

        oauth_flow = flow_from_clientsecrets(file, scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = make_response(
            json.dumps('Failed to upgrade the authorization code.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # check that all is OK with credentials, and if not, return message
    response = check_google_credentials(credentials)
    if response is not None:
        return response

    # Store the access token in the session for later use.
    # For now, we don't stay connected to google, so not needed to store this
    # session['access_token'] = credentials.access_token
    # session['gplus_id'] = gplus_id

    # Get user info
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)

    data = answer.json()

    # session['username'] = data['name']
    # session['picture'] = data['picture']
    # session['email'] = data['email']

    user = User.query.filter_by(email=data['email']).first()
    if user:
        # check if account is blocked
        if user.blocked:
            return redirect(url_for('auth.blocked_account'))
    else:
        user = User.create_user(email=data['email'],
                                password=None,
                                first_name=data['given_name'],
                                last_name=data['family_name'],
                                confirmed=True,  # email is confirmed
                                with_google=True,
                                profile_pic_url=data['picture'])

    # when we get here, all is kosher with google login
    # login with Flask_Login
    login_user(user, remember=True)
    next_page = request.args.get('next')
    if not next_page or url_parse(next_page).netloc != '':
        next_page = url_for('catalog.categories')

    return next_page
示例#41
0
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None
SCOPES = 'https://www.googleapis.com/auth/drive'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Drive API Python Quickstart'

cwd_dir = os.getcwd()
credential_dir = os.path.join(cwd_dir, '.credentials')
if not os.path.exists(credential_dir):
    os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir, 'google-drive-credentials.json')
store = 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)
http = credentials.authorize(httplib2.Http())
drive_service = discovery.build('drive', 'v3', http=http)


def listFiles(size):
    results = drive_service.files().list(
        pageSize=size, fields="nextPageToken, files(id, name)").execute()
    items = results.get('files', [])
    if not items:
示例#42
0
def gconnect():
    """Validate state token"""
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state parameter.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    """Obtain authorization code"""
    code = request.data

    """Upgrade the authorization code into a credentials object"""
    try:
        oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = make_response(
            json.dumps('Failed to upgrade the authorization code.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    """Check that the access token is valid"""
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'
           % access_token)
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])
    """If there was an error in the access token info, abort"""
    if result.get('error') is not None:
        response = make_response(json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'
        return response

    """Verify that the access token is used for the intended user"""
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = make_response(
            json.dumps("Token's user ID doesn't match given user ID."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    """Verify that the access token is valid for this app"""
    if result['issued_to'] != CLIENT_ID:
        response = make_response(
            json.dumps("Token's client ID does not match app's."), 401)
        print "Token's client ID does not match app's."
        response.headers['Content-Type'] = 'application/json'
        return response

    stored_access_token = login_session.get('access_token')
    stored_gplus_id = login_session.get('gplus_id')
    if stored_access_token is not None and gplus_id == stored_gplus_id:
        response = make_response(json.dumps(
            'Current user is already connected.'),
            200)
        response.headers['Content-Type'] = 'application/json'
        return response

    """Store the access token in the session for later use"""
    login_session['access_token'] = credentials.access_token
    login_session['gplus_id'] = gplus_id

    """Get user info"""
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)

    data = answer.json()

    login_session['username'] = data['name']
    login_session['picture'] = data['picture']
    login_session['email'] = data['email']

    user_id = getUserID(data["email"])
    """If logged in Username is not Registered, Then create an account."""
    if not user_id:
        user_id = createUser(login_session)
    login_session['user_id'] = user_id
    """Display Welcome Message
    and Google Account Pic
    while redirecting user to homepage."""

    output = ''
    output += '<h1>Welcome, '
    output += login_session['username']
    output += '!</h1>'
    output += '<img src="'
    output += login_session['picture']
    output += (' " style = "width: 300px; height: 300px;"' +
               '"border-radius: 150px;-webkit-border-radius: 150px;"' +
               '"-moz-border-radius: 150px;">')
    flash("you are now logged in as %s" % login_session['username'])
    print "done!"
    return output
示例#43
0
# is missing.
MISSING_CLIENT_SECRETS_MESSAGE = """
WARNING: Please configure OAuth 2.0

To make this sample run you will need to populate the client_secrets.json file
found at:

   %s

with information from the APIs Console <https://code.google.com/apis/console>.

""" % os.path.join(os.path.dirname(__file__), CLIENT_SECRETS)

# Set up a Flow object to be used if we need to authenticate.
FLOW = flow_from_clientsecrets(
    CLIENT_SECRETS,
    scope='https://www.googleapis.com/auth/gan.readonly',
    message=MISSING_CLIENT_SECRETS_MESSAGE)

# The gflags module makes defining command-line options easy for
# applications. Run this program with the '--help' argument to see
# all the flags that it understands.
gflags.DEFINE_enum('logging_level', 'DEBUG',
                   ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
                   'Set the level of logging detail.')

gflags.DEFINE_enum("output_type", 'STDOUT', ['BOTH', 'HTML', 'STDOUT'],
                   'Set how to output the results received from the API')

gflags.DEFINE_string('credentials_filename',
                     '../credentials.dat',
                     'File to store credentials in',
示例#44
0
def main(argv):
    """Demos the setting of the access properties by the Groups Settings API."""
    usage = 'usage: %prog [options]'
    parser = OptionParser(usage=usage)
    parser.add_option('--groupId', help='Group email address')
    parser.add_option('--whoCanInvite',
                      help='Possible values: ALL_MANAGERS_CAN_INVITE, '
                      'ALL_MEMBERS_CAN_INVITE')
    parser.add_option('--whoCanJoin',
                      help='Possible values: ALL_IN_DOMAIN_CAN_JOIN, '
                      'ANYONE_CAN_JOIN, CAN_REQUEST_TO_JOIN, '
                      'CAN_REQUEST_TO_JOIN')
    parser.add_option('--whoCanPostMessage',
                      help='Possible values: ALL_IN_DOMAIN_CAN_POST, '
                      'ALL_MANAGERS_CAN_POST, ALL_MEMBERS_CAN_POST, '
                      'ANYONE_CAN_POST, NONE_CAN_POST')
    parser.add_option('--whoCanViewGroup',
                      help='Possible values: ALL_IN_DOMAIN_CAN_VIEW, '
                      'ALL_MANAGERS_CAN_VIEW, ALL_MEMBERS_CAN_VIEW, '
                      'ANYONE_CAN_VIEW')
    parser.add_option('--whoCanViewMembership',
                      help='Possible values: ALL_IN_DOMAIN_CAN_VIEW, '
                      'ALL_MANAGERS_CAN_VIEW, ALL_MEMBERS_CAN_VIEW, '
                      'ANYONE_CAN_VIEW')
    (options, args) = parser.parse_args()

    if options.groupId is None:
        print 'Give the groupId for the group'
        parser.print_help()
        return

    settings = {}

    if (options.whoCanInvite or options.whoCanJoin or options.whoCanPostMessage
            or options.whoCanPostMessage
            or options.whoCanViewMembership) is None:
        print 'No access parameters given in input to update access permissions'
        parser.print_help()
    else:
        settings = {
            'whoCanInvite': options.whoCanInvite,
            'whoCanJoin': options.whoCanJoin,
            'whoCanPostMessage': options.whoCanPostMessage,
            'whoCanViewGroup': options.whoCanViewGroup,
            'whoCanViewMembership': options.whoCanViewMembership
        }

    # Set up a Flow object to be used if we need to authenticate.
    FLOW = flow_from_clientsecrets(
        CLIENT_SECRETS,
        scope='https://www.googleapis.com/auth/apps.groups.settings',
        message=MISSING_CLIENT_SECRETS_MESSAGE)

    storage = Storage('groupsettings.dat')
    credentials = storage.get()

    if credentials is None or credentials.invalid:
        print 'invalid credentials'
        # Save the credentials in storage to be used in subsequent runs.
        credentials = run(FLOW, storage)

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

    service = build('groupssettings', 'v1', http=http)

    access_settings(service=service,
                    groupId=options.groupId,
                    settings=settings)
示例#45
0
文件: catalog.py 项目: juvern/catalog
def gconnect():
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state parameters'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    code = request.data
    try:
        # Upgrade the authorisation code into a credentials object
        oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        # Exchanges the authorisation object into a credentials object
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = make_response(
            json.dumps('Failed to upgrade authorisation code'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    # Check that the access token is valid
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' %
           access_token)
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])
    # If there was an error in the access token info, abort
    if result.get('error') is not None:
        response = make_response(json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'
        return response
    # Verify that the access token is for the intended user
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = make_response(
            json.dumps('Token user ID does not match the given user ID'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    # Verify that the access token is valid for this app
    if result['issued_to'] != CLIENT_ID:
        response = make_response(
            json.dumps("Token's client ID does not match the app"), 401)
        print("Token's client ID does not match the app")
        response.headers['Content-Type'] = 'application/json'
        return response
    # Check to see if the user is already logged in
    stored_access_token = login_session.get('access_token')
    stored_gplus_id = login_session.get('gplus_id')
    if stored_access_token is not None and gplus_id == stored_gplus_id:
        response = make_response(json.dumps("Current user already connected."),
                                 200)
        response.headers['Content-Type'] = 'application/json'

    # Store the access token in the session for later use
    login_session['access_token'] = credentials.access_token
    login_session['gplus_id'] = gplus_id

    # Get user info
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)

    data = answer.json()

    login_session['username'] = data['name']
    login_session['picture'] = data['picture']
    login_session['email'] = data['email']

    # check if a user exists. otherwise, create a new user
    user_id = getUserId(login_session['email'])
    if not user_id:
        user_id = createUser(login_session)
    login_session['user_id'] = user_id

    output = ''
    output += '<h1>Welcome, '
    output += login_session['username']
    output += '!</h1>'
    output += '<img src="'
    output += login_session['picture']
    output += ' "style = "width: 300px; height: 300px;"> '
    flash("You are now logged in as %s" % login_session['username'])
    return output
示例#46
0
文件: geoviz.py 项目: m-lab/analysis
gflags.DEFINE_string('color_field',
                     'minrtt',
                     'Field to use to color the pixels',
                     short_name='c')
gflags.RegisterValidator(
    'color_field',
    lambda value: value == 'minrtt' or value == 'packetloss',
    message='--color_field must be \'minrtt\' or \'packetloss\'')

logging.basicConfig(format='[%(asctime)s] %(levelname)s: %(message)s',
                    level=logging.DEBUG)

PROJECT_ID = 'measurement-lab'
DATASET_ID = 'm_lab'
FLOW = flow_from_clientsecrets(
    'client_secrets.json', scope='https://www.googleapis.com/auth/bigquery')

# The MinRTT pixel is coloured based on the following constants. MinRTT outside
# of the range described by these constants are ignored.
MINRTT_BLUE = 0
MINRTT_GREEN = 80
MINRTT_RED = 1000

# The Packet Loss pixel is coloured based on the following constants. Packet
# Loss outside of the range described is ignored.
PACKETLOSS_GREEN = 0
PACKETLOSS_RED = 1.0

# Set the GAMMA to a higher number to boost the color of high packet loss.
PACKETLOSS_GAMMA = 4.0
示例#47
0
def gconnect():
    if isLogged():
        flash('You are Logged in already!', 'error')
        return redirect(url_for('displayCatalog'))
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('invalid state parameter'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    code = request.data
    try:
        oauth_flow = flow_from_clientsecrets('client_secret.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = make_response(
                        json.dumps(
                            'Failed to upgrade the authorization code.',
                            401,
                        )
                    )
        response.headers['Content-Type'] = 'application/json'
        return response

    access_token = credentials.access_token
    url = 'https://www.googleapis.com/oauth2/v1/tokeninfo?'
    url += 'token_type=Bearer&expires_in=604800&access_token=%s' % access_token

    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])
    if result.get('error') is not None:
        response = make_response(json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'
        return response

    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = make_response(
            json.dumps("Token's user ID doesn't match given user ID."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    if result['issued_to'] != CLIENT_ID:
        response = make_response(
            json.dumps("Token's client ID does not match app's."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    stored_access_token = login_session.get('access_token')
    stored_gplus_id = login_session.get('gplus_id')
    if stored_access_token is not None and gplus_id == stored_gplus_id:
        response = make_response(
                json.dumps('Current user is already connected.'), 200
            )
        response.headers['Content-Type'] = 'application/json'
        return response

    login_session['access_token'] = credentials.access_token
    login_session['gplus_id'] = gplus_id

    # User
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json"
    userinfo_url += "&access_token=%s" % credentials.access_token
    answer = requests.get(userinfo_url)

    data = answer.json()

    login_session['username'] = data['name']
    login_session['picture'] = data['picture']
    login_session['email'] = data['email']

    user_id = getUserID(data['email'])
    if not user_id:
        createUser()
    login_session['user_id'] = user_id

    output = '<div class="d-flex mb-3 align-items-center">'
    output += '<h5 class="p-2 display-5">Welcome, '
    output += login_session['username']
    output += ' &hearts;!</h5>'
    output += '<img class="ml-auto p-2" src="'
    output += login_session['picture']
    output += '" style = "width: 100px; height: 100px;border-radius: 150px;" '
    output += 'alt"profile image" '
    output += '-webkit-border-radius: 150px;-moz-border-radius: 150px;">'
    output += '</div>'
    flash("you are now logged in as %s" % login_session['username'], "success")
    return output
示例#48
0
def gconnect():
    # Validate anti-forgery state token
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state parameter.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Obtain authorization code
    code = request.data

    try:
        oauth_flow = flow_from_clientsecrets('client_secret_GOOGLE.json',
                                             scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = make_response(
            json.dumps('Failed to upgrade the authorization code.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Check that the access token is valid.
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' %
           access_token)
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])

    # If there was an error in the access token info, abort.
    if result.get('error') is not None:
        response = make_response(json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is used for the intended user.
    google_id = credentials.id_token['sub']
    if result['user_id'] != google_id:
        response = make_response(
            json.dumps("Token's user ID doesn't match given user ID."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is valid for this app.
    if result['issued_to'] != GOOGLE_CLIENT_ID:
        response = make_response(
            json.dumps("Token's client ID does not match app's."), 401)
        print "Token's client ID does not match app's."
        response.headers['Content-Type'] = 'application/json'
        return response

    stored_access_token = login_session.get('access_token')
    stored_google_id = login_session.get('google_id')

    if stored_access_token is not None and google_id == stored_google_id:
        response = make_response(
            json.dumps('Current user is already connected.'), 200)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Store the access token in the session for later use.
    login_session['access_token'] = credentials.access_token
    login_session['google_id'] = google_id

    # Get user info
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)

    data = answer.json()
    login_session['logged_in'] = True
    login_session['provider'] = 'google'
    login_session['username'] = data['name']
    login_session['picture'] = data['picture']
    login_session['email'] = data['email']

    # See if user exists
    user_id = getUserID(data["email"])
    if not user_id:
        user_id = createUser(login_session)
    login_session['user_id'] = user_id
    return render_template('login-success.html',
                           username=login_session['username'],
                           img_url=login_session['picture'])
示例#49
0
                                    'config.json')
    keyditc_json_path = os.path.join(
        os.path.abspath(os.path.dirname(__file__)), 'keydict.json')
    CONFIG = json.load(open(config_json_path))
    KEYDICT = json.load(open(keyditc_json_path))

    credentials_path = "credentials.json"
    if os.path.exists(credentials_path):
        # 認証済み
        store = Storage(credentials_path)
        credentials = store.get()
    else:
        # 認証処理
        f = "client.json"
        scope = "https://www.googleapis.com/auth/youtube.readonly"
        flow = client.flow_from_clientsecrets(f, scope)
        flow.user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36"
        credentials = tools.run_flow(flow, Storage(credentials_path))

    http = credentials.authorize(httplib2.Http())
    url_get_livestremingVideoID = "https://www.googleapis.com/youtube/v3/search?part=id&channelId=UCwBkMy_K3XrQoWqQkXZvZiA&eventType=live&type=video&key="
    url_get_livestremingVideoID += CONFIG['YoutubeAPIkey']
    res, receivedata = http.request(url_get_livestremingVideoID)
    data = json.loads(receivedata.decode())
    video_id = data["items"][0]["id"]["videoId"]

    # argsにlive_idを指定
    client = Process(target=run_client, args=(video_id, ))
    # クライアント(専ら送信側)スタート
    client.start()
示例#50
0
def main():
    """Shows basic usage of the Drive v3 API.
	Prints the names and ids of the first 10 files the user has access to.
	"""
    store = file.Storage('token.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
        creds = tools.run_flow(flow, store)
    drive_service = build('drive', 'v3', http=creds.authorize(Http()))

    counter = 0
    page_token = None
    list_of_tuples = []
    #dups_dict = collections.defaultdict(int)
    dups_dict = collections.defaultdict(list)

    while True:
        counter = counter + 1
        #check here for the values spaces can have: https://developers.google.com/drive/api/v3/reference/files/list

        #from api v2, but could still work. Nothing for file deletions in v3 API
        # try:
        # service.files().delete(fileId=file_id).execute()
        # except errors.HttpError, error:
        # print ('An error occurred: %s') % error

        #response = drive_service.files().list(q="mimeType!='audio/au'", spaces='drive', fields='nextPageToken, files(id, name)', pageToken=page_token).execute()
        response = drive_service.files().list(
            spaces='drive',
            pageSize=500,
            fields='nextPageToken, files(id, name, md5Checksum, parents)',
            pageToken=page_token).execute()

        for f in response.get('files', []):
            # Process change

            list_of_tuples.append((f.get('md5Checksum'), f.get('name')))
            #dups_dict[f.get('md5Checksum')] += 1

            print('Found file: %s (%s) %s' %
                  (f.get('name'), f.get('id'), f.get('md5Checksum')))
        page_token = response.get('nextPageToken', None)

        #remove this IF if you want to scan through everything
        if counter >= 10:
            break

        if page_token is None:
            print("this many:" + str(counter))
            break

    for k, v in list_of_tuples:
        dups_dict[k].append(v)

    print("\r\n\r\n")
    print("here are the duplicates")

    for key in dups_dict:
        if len(dups_dict[key]) > 1 and "-checkpoint" not in str(
                dups_dict[key]):
            print(dups_dict[key])
示例#51
0
Created on Tue Sep 15 16:16:33 2020

@author: pasq
"""
from __future__ import print_function
import os
from googleapiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools
from apiclient.http import MediaFileUpload, MediaIoBaseDownload

SCOPES = 'https://www.googleapis.com/auth/drive'
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets(
        '/Users/pasq/Documents/ML/git/credentials.json', SCOPES)
    creds = tools.run_flow(flow, store)
DRIVE = discovery.build('drive', 'v3', http=creds.authorize(Http()))


#Create a new file in the specified folder, root otherwise
def uploadFile(local_file_name, upload_name, folder=None):
    file_metadata = {"name": upload_name, "mimeType": "*/*"}
    if folder is not None:
        file_metadata["parents"] = [folder]

    media = MediaFileUpload(local_file_name, mimetype='*/*', resumable=True)
    file = DRIVE.files().create(body=file_metadata,
                                media_body=media,
                                fields='id').execute()
    print('File ID: ' + file.get('id'))
def login():
        flow = flow_from_clientsecrets("client_secrets.json", scope = scope, redirect_uri = redirect_uri, prompt = 'select_account')
        uri = flow.step1_get_authorize_url()
        redirect(str(uri))
示例#53
0
def gconnect():
    # Validate state token
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('invalid state parameter'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    # Obtain authorization code
    code = request.data

    try:
        # Upgrade the authorization code into a credentials object
        oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        # exchange an authorization code for  credentials object
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = make_response(
            json.dumps('failed to upgrade the authorization code.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    # check that the access token is valid
    access_token = credentials.access_token
    # to verify that it is a valid token for you from google
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' %
           access_token)
    # create json get request containing the url
    # and access token and store the result
    # in variable called result
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])

    # if the result contains any error,
    # If there was an error in the access token info, abort.
    if result.get('error') is not None:
        response = make_response(json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'

    # verify that the access token is used for the intended user
    # gplus ---> google plus
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = make_response(
            json.dumps('Tokens user ID doesnot match given user ID.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # verify that the access token is valid for this app
    if result['issued_to'] != CLIENT_ID:
        response = make_response(
            json.dumps('Tokens user ID doesnot match app ID.'), 401)
        print "Tokens user ID doesnot match app ID."
        response.headers['Content-Type'] = 'application/json'
        return response

    # check if the user is already logged in
    stored_credentials = login_session.get('credentials')
    stored_gplus_id = login_session.get('gplus_id')
    if stored_credentials is not None and gplus_id == stored_gplus_id:
        response = make_response(
            json.dumps('current user is already connected.'), 200)
        response.headers['Content-Type'] = 'application/json'

    # store the access token in the session for later user
    login_session['access_token'] = credentials.access_token
    login_session['gplus_id'] = gplus_id

    # get user info
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)
    data = json.loads(answer.text)

    login_session['username'] = data["name"]
    login_session['picture'] = data["picture"]
    login_session['email'] = data["email"]

    # see if user exists, if it doesn't make a new one
    user_id = getUserID(login_session['email'])
    if not user_id:
        user_id = createUser(login_session)
    login_session['user_id'] = user_id

    username = login_session['username']
    picture = login_session['picture']

    print "done!"
    return redirect(url_for('catalog'))
示例#54
0
import datetime
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import xlrd

start = ['08:00', '09:50', '11:40', '14:00', '15:45', '17:30']
end = ['09:35', '11:25', '13:15', '15:35', '17:20', '19:05']

book = xlrd.open_workbook('imi2018.xls')
it4 = book.sheet_by_index(8)

store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_id.json', SCOPES)
    creds = tools.run_flow(flow, store)
service = build('calendar', 'v3', http=creds.authorize(Http()))

# Call the Calendar API

for i in range(3, 39):
    if it4.cell(i, 8).value == "":
        continue
    para = it4.cell(i, 8).value
    l_pr = it4.cell(i, 9).value
    room = it4.cell(i, 10).value
    print(start[(i - 3) % 6], end[(i - 3) % 6], para, l_pr, room)

    event = {
        'summary': para,
示例#55
0
To make this sample run you will need to populate the client_secrets.json file
found at:

   %s

with information from the APIs Console <https://code.google.com/apis/console>.

""" % os.path.join(os.path.dirname(__file__), CLIENT_SECRETS)

setdir = os.path.abspath('.')
file = setdir + '\\client_secrets.json'

# Set up a Flow object to be used if we need to authenticate.
FLOW = flow_from_clientsecrets(
    file,
    scope='https://www.googleapis.com/auth/analytics.readonly',
    redirect_uri=OOB_CALLBACK_URN)

# The gflags module makes defining command-line options easy for applications.
# Run this program with the '--help' argument to see all the flags that it
# understands.
gflags.DEFINE_enum('logging_level', 'ERROR',
                   ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
                   'Set the level of logging detail.')

# Name of file that will store the access and refresh tokens to access
# the API without having to login each time. Make sure this file is in
# a secure place.
TOKEN_FILE_NAME = setdir + '\\analytics.dat'

示例#56
0
def gconnect():
    # Validates state token passed to login page.
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state parameter.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    # Obtain authorization code.
    code = request.data

    try:
        # stores credentials object
        oauth_flow = flow_from_clientsecrets('uday.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = make_response(
            json.dumps('Failed to upgrade the authorization code.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # validates access token.
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' %
           access_token)
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])
    # if error occurs passes 500 as status and aborts.
    if result.get('error') is not None:
        response = make_response(json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify access token.
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = make_response(
            json.dumps("Token's user ID doesn't match given user ID."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # valdates access token for this app.
    if result['issued_to'] != CLIENT_ID:
        response = make_response(
            json.dumps("Token's client ID does not match app's."), 401)
        print "Token's client ID does not match app's."
        response.headers['Content-Type'] = 'application/json'
        return response
    #if user already logged in then sends status as 200.
    stored_credentials = login_session.get('credentials')
    stored_gplus_id = login_session.get('gplus_id')
    if stored_credentials is not None and gplus_id == stored_gplus_id:
        response = make_response(
            json.dumps('Current user is already connected.'), 200)
        response.headers['Content-Type'] = 'application/json'
        flash("you are now logged in as %s" % login_session['user_id'])
        return response

    # Store credentials in the session for later use.
    login_session['credentials'] = credentials
    login_session['gplus_id'] = gplus_id

    # Store user info
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)

    data = answer.json()

    login_session['username'] = data['name']
    login_session['picture'] = data['picture']
    login_session['email'] = data['email']
    #cheks if user is already in user database. If not it stores user info in User database.
    useremail = getUserID(login_session['email'])
    if not useremail:
        useremaail = createUser(login_session)
        login_session['user_id'] = useremaail
    else:
        login_session['user_id'] = useremail

    #Creates an output for user and sends successful state 200.
    output = ''
    output += '<h1>Welcome, '
    output += login_session['username']
    output += '!</h1>'
    output += '<img src="'
    output += login_session['picture']
    output += ' " style = "width: 150px; height: 150px;border-radius: 100px;-webkit-border-radius: 100px;-moz-border-radius: 100px;margin-top:20px;"> '
    flash("you are now logged in as %s" % login_session['username'])
    print "done"
    response = make_response(json.dumps(output), 200)
    response.headers['Content-Type'] = 'application/json'
    return response
示例#57
0
def gconnect():
    # Gathers data from Google Sign In API and places it inside a session variable.
    # Validate state token
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state parameter.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    # Obtain authorization code
    code = request.data

    try:
        # Upgrade the authorization code into a credentials object
        oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
        oauth_flow.redirect_uri = 'postmessage'
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = make_response(
            json.dumps('Failed to upgrade the authorization code.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Check that the access token is valid.
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'
           % access_token)
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])
    # If there was an error in the access token info, abort.
    if result.get('error') is not None:
        response = make_response(json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'

    # Verify that the access token is used for the intended user.
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = make_response(
            json.dumps("Token's user ID doesn't match given user ID."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is valid for this app.
    if result['issued_to'] != CLIENT_ID:
        response = make_response(
            json.dumps("Token's client ID does not match app's."), 401)
        print "Token's client ID does not match app's."
        response.headers['Content-Type'] = 'application/json'
        return response

    stored_credentials = login_session.get('credentials')
    stored_gplus_id = login_session.get('gplus_id')
    if stored_credentials is not None and gplus_id == stored_gplus_id:
        response = make_response(json.dumps(
            'Current user is already connected.'), 200)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Store the access token in the session for later use.
    login_session['provider'] = 'google'
    login_session['credentials'] = credentials.to_json()
    login_session['gplus_id'] = gplus_id

    # Get user info
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)

    data = answer.json()

    login_session["username"] = data['name']
    login_session["picture"] = data['picture']
    login_session["email"] = data['email']

    user_id = getUserID(login_session['email'])
    if not user_id:
        user_id = createUser(login_session)

    output = ''
    output += '<h1>Welcome, '
    output += login_session['username']
    output += '!</h1>'
    output += '<img src="'
    output += login_session['picture']
    output += ' " style = "width: 300px; height: 300px;border-radius: 150px;'+
                                '-webkit-border-radius: 150px;-moz-border-radius: 150px;"> '
示例#58
0
文件: ibc.py 项目: PER22/InboxCleaner
def main():
    #Google's OAuth2 code
    store = file.Storage('token.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
        creds = tools.run_flow(flow, store)
    service = build('gmail', 'v1', http=creds.authorize(Http()))
    #end of Google's code

    deleteKeywordsAndUsers = set()
    keepKeywordsAndUsers = set()
    user_input = ""
    delete_filename = "default.dltkeys"
    keep_filename = "default.kpkeys"

    #Ask to load from delete kywds file, should only be using delete* variables until otherwise stated.
    while (user_input != "yes") and (user_input != "no"):
        if user_input != "":
            print("Invalid response. Try again. \n\n")
        user_input = raw_input(
            "Do you want to load delete keywords from the file?\nType yes or no: "
        )

    if user_input == "yes":

        #Get file name and verify.
        delete_filename = raw_input(
            "\nEnter the name of your file. Delete Files should end in .dltkeys:   "
        )
        deleteKeywordsAndUsers |= loadFileToSet(delete_filename, "dltkeys",
                                                "delete")
    #Ask to load from preserve keywrods file, only use keep* variables until otherwise stated.

    #dont allow escape without valid input
    user_input = ""
    while (user_input != "yes") and (user_input != "no"):
        if user_input != "":
            print("Invalid response. Try again. \n\n")
        user_input = raw_input(
            "Do you want to load preservation keywords from the file?\nType yes or no: "
        )

    if user_input == "yes":
        #Get file name and verify.
        keep_filename = raw_input(
            "\nEnter the name of your file. Keep key files should end in .kpkeys:   "
        )
        keepKeywordsAndUsers |= loadFileToSet(keep_filename, ".kpkeys",
                                              "preservation")

    #remove all preserve kywds from the list of delete kywds, in place so no accidents happen
    deleteKeywordsAndUsers -= keepKeywordsAndUsers

    #Collect new keywords from user
    deleteKeywordsAndUsers |= collectDeleteKeywordsAndUsers()
    keepKeywordsAndUsers |= collectKeepKeywordsAndUsers()

    #remove any mistakes again in the safest way possible
    deleteKeywordsAndUsers -= keepKeywordsAndUsers

    #clear screen and output the lists thus far
    print('\033c')
    print("Deletion keywords and addresses:\n")
    for each in deleteKeywordsAndUsers:
        print(each)
    print("\n\nKeeping messages that have these terms or addresses:\n\n")
    for each in keepKeywordsAndUsers:
        print(each)

    #Begin Collecting the Message IDs to delete via API call
    setOfMessageIDsToDelete = set()
    setOfMessageIDsToKeep = set()
    #Collect all deleteable Message IDs
    for keyword in deleteKeywordsAndUsers:
        setOfMessageIDsToDelete |= setOfMessagesMatchingQuery(
            service, "me", keyword)
    #Collect all preservable Message IDs
    for keyword in keepKeywordsAndUsers:
        setOfMessageIDsToKeep |= setOfMessagesMatchingQuery(
            service, "me", keyword)
    #Remove any messages that are in both in safest way possible
    setOfMessageIDsToDelete -= setOfMessageIDsToKeep
    #declare a variable to count them and make a readable output
    i = 0
    for msg in setOfMessageIDsToDelete:
        i += 1
        print(str(i) + ". " + str(msg))

    #Confirm And Warn User
    user_accept = ""
    while (user_accept != "DELETE") and (user_accept != "CANCEL"):
        if user_accept != "":
            print("\n\nInvalid response. Try again.")
        user_accept = raw_input(
            "You are about to delete " + str(i) +
            " messages.\n This could be a large inconvenience if you've made a mistake.\nType DELETE to continue or CANCEL to cancel: "
        )

    if user_accept == "DELETE":
        deleteMessagesFromIDSet(setOfMessageIDsToDelete)
    else:
        print("Deletion Cancelled.")

    #ask about saving delete file
    user_input = ""
    user_input = raw_input(
        "Do you want to save the changes you made to the delete keyword file? Type save, or any key to continue without saving.    "
    )
    if user_input == "save":
        saveSetToFile(deleteKeywordsAndUsers, delete_filename)
#ask about saving preserve file
    user_input = ""
    user_input = raw_input(
        "Do you want to save the changes you made to the preserve keyword file? Type save, or any key to continue without saving.   "
    )
    if user_input == "save":
        saveSetToFile(keepKeywordsAndUsers, keep_filename)
示例#59
0
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

#global variables
IP_WEBSITE = "http://myip.xname.org" #this is the url i am using to get the public IP
FILENAME = 'IP-Log.txt' #name or path of log file if not in current directory
NUMLOGS = 100 #number of logs to keep before deleting file (to conserve space/prevent the file from getting too big)
SCOPES = 'https://www.googleapis.com/auth/drive.file' #the scope of google drive permissions to grant this application. (https://developers.google.com/drive/v3/web/about-auth)
MANUAL = "FALSE" #switch var to enable manual running regardless if there is a change in ip address. Defualt: "FALSE" set to "TRUE" if you want to run manually

#authorize with REST OAuth 2.0 (If this is the first time running the application should open a google sign in page in your defualt browser)
creds = store.get()
if not creds or creds.invalid:
	flow = client.flow_from_clientsecrets('client_secret.json', scope = SCOPES)
	creds = tools.run_flow(flow, store, flags) \
			if flags else tools.run(flow, store)
DRIVE = build('drive', 'v3', http = creds.authorize(Http())) #create drive api object

def getDriveInfo(): #this method gets the files named 'IP-Log.txt' not in the trash and gets the ID of the newest one by creation date 
	query = "name = 'IP-Log.txt' and trashed = false" #var for easy query input
	res = DRIVE.files().list(q=query, fields = "files(id, name, createdTime)", orderBy = 'createdTime').execute() #request files named 'IP-Log.txt' not in the trash based on query input
	items = res.get('files')#store info in list called items. Make note that API returns lists when searching. 
    	if not items:
		ident = "null" #if no items found id is set to null
   	else:
        	for item in items[0:1]: #get the id, name, and created time of the newest created file. Name and created time are for debugging. 
			name = item['name']
			ident = item['id'] #id var
			createdTime = item['createdTime']
示例#60
0
import datetime

from google.appengine.ext import ndb
from google.appengine.api import users

from models.user import UserModel
from models.user import UserCredentials

import jinja2
import webapp2

from oauth2client import client
from google.appengine.api import memcache

flow = client.flow_from_clientsecrets(
    'client_secrets.json',
    scope='https://www.googleapis.com/auth/userinfo.email',
    redirect_uri='http://*****:*****@gmail.com')
    query = UserModel.query(UserModel.email == email).fetch()
    logging.info('LEN '+str(len(query)))