Esempio n. 1
0
def get_authenticated_service():
    credentials = None

    if os.path.exists(TOKEN_PICKLE_FILE):
        print('Loading credentials from file...')
        with open(TOKEN_PICKLE_FILE, 'rb') as token:
            credentials = pickle.load(token)

    # If there are no valid credentials available, then either refresh the token or log in.
    if not credentials or not credentials.valid:
        if credentials and credentials.expired and credentials.refresh_token:
            print('Refreshing access token...')
            credentials.refresh(Request())
        else:
            print('Fetching new tokens...')
            flow = InstalledAppFlow.from_client_secrets_file(
                CLIENT_SECRETS_FILE, scopes=SCOPES)

            flow.run_local_server(port=8999,
                                  prompt='consent',
                                  authorization_prompt_message='')
            credentials = flow.credentials

            # Save the credentials for the next run
            with open(TOKEN_PICKLE_FILE, 'wb') as f:
                print('Saving credentials for future use...')
                pickle.dump(credentials, f)

    return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)
Esempio n. 2
0
def deploy():
    with credential.Cred(credential.Cred.Kind.ClientSecret) as client_secret:
        if client_secret is None:
            print("cannot find client secret, input:")
            client_secret = json.loads(input())
            credential.Cred.set(credential.Cred.Kind.ClientSecret,
                                client_secret)

        flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_config(
            client_secret, scopes=USER_SCOPES)
        flow.run_local_server(port=0)
        credential.Cred.set(credential.Cred.Kind.Credential, flow.credentials)
def get_id_token(client_secrets_file, extra_args):
    """Obtains credentials from the user using OAuth 2.0 and then returns the
    ID token from those credentials."""

    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes=['openid', 'email', 'profile'])

    # Run the OAuth 2.0 flow to obtain credentials from the user.
    flow.run_local_server()

    # The credentials have both an access token and an ID token. Cloud
    # Endpoints uses the ID Token.
    id_token = flow.oauth2session.token['id_token']

    return id_token
def get_id_token(client_secrets_file, extra_args):
    """Obtains credentials from the user using OAuth 2.0 and then returns the
    ID token from those credentials."""

    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes=['openid', 'email', 'profile'])

    # Run the OAuth 2.0 flow to obtain credentials from the user.
    flow.run_local_server()

    # The credentials have both an access token and an ID token. Cloud
    # Endpoints uses the ID Token.
    id_token = flow.oauth2session.token['id_token']

    return id_token
def init_google_photos_api(credentials_path, db):
    try:
        from googleapiclient import discovery
        from google_auth_oauthlib import flow
        from google.auth.transport import requests
    except ImportError:
        logger.critical(
            'extra requirements needed for working with google photo.\n'
            '  python3 -m pip install -r requirements-google-photo.txt')
        return None, None

    creds = None
    token_res = db.execute('select token from gphotos_token').fetchone()

    if token_res:
        creds = pickle.loads(token_res[0])

    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(requests.Request())
        else:
            flow = flow.InstalledAppFlow.from_client_secrets_file(
                credentials_path, GOOGLE_PHOTOS_SCOPES)
            creds = flow.run_local_server()
        db.execute('delete from gphotos_token')
        db.execute('insert into gphotos_token (token) values(?)',
                   (pickle.dumps(creds), ))

    return creds, discovery.build('photoslibrary', 'v1', credentials=creds)
Esempio n. 6
0
def main():
    # Get credentials and create an API client
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            credentials = pickle.load(token)
    else:
        scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]
        flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
            "cred.json", scopes)
        credentials = flow.run_local_server()
        with open('token.pickle', 'wb') as token:
            pickle.dump(credentials, token)

    youtube = googleapiclient.discovery.build("youtube",
                                              "v3",
                                              credentials=credentials)

    for dirname in os.listdir("."):
        if not os.path.isdir(dirname):
            continue
        for fname in os.listdir(dirname):
            if fname.endswith(".new"):
                path = os.path.join(dirname, fname)
                status_path = path.replace(".new", ".status")
                if os.path.exists(status_path):
                    continue
                vid = fname.split("captions-")[1].split(".")[0]
                print(vid, path)
                upload_cc(youtube, vid, path)
                with open(status_path, "w") as f:
                    f.write("uploaded")
Esempio n. 7
0
def main():
    # Get credentials and create an API client
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            credentials = pickle.load(token)
    else:
        scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]
        flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
            "cred.json", scopes)
        credentials = flow.run_local_server()
        with open('token.pickle', 'wb') as token:
            pickle.dump(credentials, token)

    youtube = googleapiclient.discovery.build("youtube",
                                              "v3",
                                              credentials=credentials)

    for dirname in os.listdir("."):
        readme = os.path.join(dirname, "README.md")
        if os.path.exists(readme):
            print(readme)
            with open(readme) as f:
                for line in f:
                    m = re.search(r"youtu.be/(.*?)\)", line)
                    if m:
                        vid = m.group(1)
                        orig_file = os.path.join(dirname,
                                                 "captions-" + vid + ".orig")
                        print(orig_file)
                        if not os.path.exists(orig_file):
                            download_cc(youtube, vid, orig_file)
def get_goog_oathcreds(token_txt_dir, creds_json_dir):
    if not os.path.exists(token_txt_dir):
        flow = InstalledAppFlow.from_client_secrets_file(
            creds_json_dir,
            scopes=["https://www.googleapis.com/auth/youtube.readonly"],
            redirect_uri=r"http://localhost/")

        oathcreds = flow.run_local_server()

        with open(token_txt_dir, 'w+') as f:
            json.dump({"refresh_token": oathcreds._refresh_token, "expiry": oathcreds.expiry, \
                        "token": oathcreds.token, "id_token": oathcreds.id_token}, f, indent=4, sort_keys=True, default=str)
    else:
        temp = json.loads(open(token_txt_dir, 'r').read())
        mysecret = json.loads(open(creds_json_dir, 'r').read())['installed']
        oathcreds = gcred.Credentials(
            temp['token'],
            refresh_token=temp['refresh_token'],
            id_token=temp['id_token'],
            token_uri=mysecret['token_uri'],
            client_id=mysecret['client_id'],
            client_secret=mysecret['client_secret'],
            scopes=["https://www.googleapis.com/auth/youtube.readonly"],
        )
        tmpexpiry = temp['expiry'].split('.')[0]
        oathcreds.expiry = datetime.datetime.strptime(tmpexpiry,
                                                      '%Y-%m-%d %H:%M:%S')
        request = google.auth.transport.requests.Request()
        if oathcreds.expired:
            oathcreds.refresh(request)
    return oathcreds
Esempio n. 9
0
def Create_Service(client_secret_file, api_name, api_version, *scopes):
    CLIENT_SECRET_FILE = client_secret_file
    API_SERVICE_NAME = api_name
    API_VERSION = api_version
    SCOPES = [scope for scope in scopes[0]]

    cred = None
    pickle_file = f'token_{API_SERVICE_NAME}_{API_VERSION}.pickle'

    if os.path.exists(pickle_file):
        with open(pickle_file, 'rb') as token:
            cred = pickle.load(token)

    if not cred or not cred.valid:
        if cred and cred.expired and cred.refresh_token:
            cred.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                CLIENT_SECRET_FILE, SCOPES)
            cred = flow.run_local_server()

        with open(pickle_file, 'wb') as token:
            pickle.dump(cred, token)
    service = build(API_SERVICE_NAME, API_VERSION, credentials=cred)
    try:
        service = build(API_SERVICE_NAME, API_VERSION, credentials=cred)
        return service
    except:
        return None
Esempio n. 10
0
    def auth(self):
        # Disable OAuthlib's HTTPS verification when running locally.
        # *DO NOT* leave this option enabled in production.
        os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

        scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]
        creds = None
        # The file token.pickle stores the user's access and refresh tokens, and is
        # created automatically when the authorization flow completes for the first
        # time.
        if os.path.exists('token.pickle'):
            with open('token.pickle', 'rb') as token:
                creds = pickle.load(token)
        # If there are no (valid) credentials available, let the user log in.
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    'client_secret.json', scopes)
                creds = flow.run_local_server(port=0)
            # Save the credentials for the next run
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)

        api_service_name = "youtube"
        api_version = "v3"

        self.youtube = googleapiclient.discovery.build(api_service_name,
                                                       api_version,
                                                       credentials=creds)
Esempio n. 11
0
def get_cred(client_secrets_file, client_token_file, scopes):
    '''
    Returns the credentials for google calendar api

    @return service: (googleapiclient.discovery.Resource) le service passé
    '''
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists(client_token_file):
        with open(client_token_file, 'rb') as token:
            creds = pickle.load(token)
            # print("get_authenticated_service : creds found !")
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        # print("get_authenticated_service, creds not found or invalid")
        if creds and creds.expired and creds.refresh_token:
            # print("get_authenticated_service, creds expired ! refreshing...")
            creds.refresh(Request())
        else:
            # print("get_authenticated_service, creating creds...")
            flow = InstalledAppFlow.from_client_secrets_file(
                client_secrets_file, scopes)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open(client_token_file, 'wb') as token:
            pickle.dump(creds, token)
        # print("get_authenticated_service, creds saved to", client_token_file)
    return creds
    def get_youtube_api(project_id, client_id, client_secret):
        try:
            credentials = google.oauth2.credentials.Credentials.from_authorized_user_file(
                os.path.join(os.path.dirname(__file__),
                             'ftc-match-uploader-token.json'))
        except FileNotFoundError:
            client_config = {
                'installed': {
                    **oauth_client,
                    'project_id': project_id,
                    'client_id': client_id,
                    'client_secret': client_secret,
                }
            }
            flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_config(
                client_config,
                ['https://www.googleapis.com/auth/youtubepartner'])
            credentials = flow.run_local_server()
            with open(
                    os.path.join(os.path.dirname(__file__),
                                 'ftc-match-uploader-token.json'),
                    'w') as token:
                token.write(credentials.to_json())

        return googleapiclient.discovery.build('youtube',
                                               'v3',
                                               credentials=credentials)
Esempio n. 13
0
def get_classroom_service_from_json():
    """Shows basic usage of the Classroom API.
    Prints the names of the first 10 courses the user has access to.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('classroom', 'v1', credentials=creds)

    return service
Esempio n. 14
0
    def __init__(self, config):
        scopes = [
            'https://www.googleapis.com/auth/youtube.readonly',
            'https://www.googleapis.com/auth/youtube.upload',
            'https://www.googleapis.com/auth/youtube.force-ssl'
        ]
        api_service_name = 'youtube'
        api_version = 'v3'
        client_secrets_file = config['client_secrets_file']
        credentials_file = config['credentials_file']

        credentials = None
        # The file token.pickle stores the user's access and refresh tokens, and is
        # created automatically when the authorization flow completes for the first
        # time.
        if os.path.exists(credentials_file):
            with open(credentials_file, 'rb') as token:
                credentials = pickle.load(token)
        # If there are no (valid) credentials available, let the user log in.
        if not credentials or not credentials.valid:
            if credentials and credentials.expired and credentials.refresh_token:
                credentials.refresh(google.auth.transport.requests.Request())
            else:
                flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
                    client_secrets_file, scopes)
                credentials = flow.run_local_server()
            # Save the credentials for the next run
            with open(credentials_file, 'wb') as token:
                pickle.dump(credentials, token)

        self.youtube = googleapiclient.discovery.build(api_service_name,
                                                       api_version,
                                                       credentials=credentials,
                                                       cache_discovery=False)
Esempio n. 15
0
def get_employee():
    """Shows basic usage of the Sheets API.
    Prints values from a sample spreadsheet.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('sheets', 'v4', credentials=creds)

    # Call the Sheets API
    SAMPLE_RANGE_NAME = 'TT_NhanVien!A2:E'
    sheet = service.spreadsheets()
    result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                                range=SAMPLE_RANGE_NAME).execute()
    values = result.get('values', [])
    if values:
        res = values[0]
        push_notification(res[1],'Co khach hang de lai thong tin tu van. Vui long truy cap he thong')
Esempio n. 16
0
 def auth(self, client_secret_filename, scopes):
     creds = None
     # The file token.pickle stores the user's access and refresh tokens, and is
     # created automatically when the authorization flow completes for the first
     # time.
     if os.path.exists(
             '/home/monkey/Desktop/pioneiras/UpdatePioneers/token.pickle'):
         with open(
                 '/home/monkey/Desktop/pioneiras/UpdatePioneers/token.pickle',
                 'rb') as token:
             creds = pickle.load(token)
     # If there are no (valid) credentials available, let the user log in.
     if not creds or not creds.valid:
         if creds and creds.expired and creds.refresh_token:
             creds.refresh(Request())
         else:
             flow = InstalledAppFlow.from_client_secrets_file(
                 client_secret_filename, scopes)
             creds = flow.run_local_server()
         # Save the credentials for the next run
         with open(
                 '/home/monkey/Desktop/pioneiras/UpdatePioneers/token.pickle',
                 'wb') as token:
             pickle.dump(creds, token)
     return creds
Esempio n. 17
0
def credentials_flow_interactive(client_secrets_path):
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_path, scopes=[ASSISTANT_OAUTH_SCOPE])
    if 'DISPLAY' in os.environ:
        credentials = flow.run_local_server()
    else:
        credentials = flow.run_console()
    return credentials
Esempio n. 18
0
    def oauth2():
        """
    Calls the Youtube API using OAuth 2.0 
    Requirements:
      token.pickle - stores login credentials (will be created if not present)
      client_secrets.json - OAuth 2.0 client ID (Will fail if not present)
    """
        credentials = None
        scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]
        #for debug mode
        '''
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file('client_secrets.json', scopes=scopes)
    flow.run_local_server(port=8080, prompt='consent', authorization_prompt_message='')
    credentials = flow.credentials
    print(credentials.to_json())
    return googleapiclient.discovery.build(youtube_api.api_service_name, youtube_api.api_version, credentials=credentials)
    '''
        # token.pickle stores the user's credentials from previously successful logins
        if os.path.exists('token.pickle'):
            print('Loading Credentials From File...')
            with open('token.pickle', 'rb') as token:
                credentials = pickle.load(token)

        # If there are no valid credentials available, then either refresh the token or log in.
        if not credentials or not credentials.valid:
            if credentials and credentials.expired and credentials.refresh_token:
                print('Refreshing Access Token...')
                credentials.refresh(Request())
            else:
                print('Fetching New Tokens...')
                flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
                    'client_secrets.json', scopes=scopes)
                flow.run_local_server(port=8080,
                                      prompt='consent',
                                      authorization_prompt_message='')
                credentials = flow.credentials

                # Save the credentials for the next run
                with open('token.pickle', 'wb') as f:
                    print('Saving Credentials for Future Use...')
                    pickle.dump(credentials, f)

        return googleapiclient.discovery.build(youtube_api.api_service_name,
                                               youtube_api.api_version,
                                               credentials=credentials)
Esempio n. 19
0
def get_service_with_auth():
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        _config["client_secrets_file"], _config["scopes"])
    credentials = flow.run_local_server()

    youtube = googleapiclient.discovery.build(_config["api_service_name"],
                                              _config["api_version"],
                                              credentials=credentials)
    return youtube
Esempio n. 20
0
def _credentials_flow_interactive(client_secrets_path):
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_path,
        scopes=[_ASSISTANT_OAUTH_SCOPE])
    if 'DISPLAY' in os.environ:
        credentials = flow.run_local_server()
    else:
        credentials = flow.run_console()
    return credentials
def get_authenticated_service():
    flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE,
                                                     SCOPES)
    credentials = flow.run_local_server()
    with open('refresh.token', 'w+') as f:
        f.write(credentials._refresh_token)
    print('Refresh Token:', credentials._refresh_token)
    print('Saved Refresh Token to file: refresh.token')
    return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)
Esempio n. 22
0
def build_register_client():
    """
    Register app with credentials from client_secret.json. REQUIRED
    """
    flow = InstalledAppFlow.from_client_secrets_file(
        client_secrets_file=CLIENT_SECRET_FILE, scopes=SCOPES)
    credentails = flow.run_local_server()
    return build(YOUTUBE_API_SERVICE_NAME,
                 YOUTUBE_API_VERSION,
                 credentials=credentails)
Esempio n. 23
0
def get_token_json():
    global youtube

    # Get credentials and create an API client
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    # credentials = flow.run_console()
    credentials = flow.run_local_server()
    youtube = googleapiclient.discovery.build(api_service_name,
                                              api_version,
                                              credentials=credentials)
Esempio n. 24
0
def credentials_flow_interactive(client_secrets_path, scopes):
    """Initiate an interactive OAuth2InstalledApp flow.

    - If an X server is running: Run a browser based flow.
    - If not: Run a console based flow.

    Args:
      client_secrets_file: The path to the client secrets JSON file.
      scopes: The list of scopes to request during the flow.
    Returns:
      google.oauth2.credentials.Credentials: new OAuth2 credentials authorized
        with the given scopes.
    """
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_path, scopes=scopes)
    if 'DISPLAY' in os.environ:
        flow.run_local_server()
    else:
        flow.run_console()
    return flow.credentials
Esempio n. 25
0
def get_authenticated_service():
    flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE,
                                                     SCOPES)
    #credentials = flow.run_console()
    credentials = flow.run_local_server(
        host='localhost',
        port=8080,
        authorization_prompt_message='Please visit this URL: {url}',
        success_message='The auth flow is complete; you may close this window.',
        open_browser=True)
    return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)
Esempio n. 26
0
def update_credentials():
    global credentials
    if not credentials or not credentials.valid:
        if credentials and credentials.expired and credentials.refresh_token:
            printBetter('Refreshing Access Token...')
            credentials.refresh(Request())
        else:
            printBetter('Fetching New Tokens...')
            flow = InstalledAppFlow.from_client_secrets_file(
                'client_secrets.json', scopes)

            flow.run_local_server(port=8080,
                                  prompt='consent',
                                  authorization_prompt_message='')
            credentials = flow.credentials

            # Save the credentials for the next run
            with open('token.pickle', 'wb') as f:
                printBetter('Saving Credentials for Future Use...')
                pickle.dump(credentials, f)
Esempio n. 27
0
def youtube_liked_videos():

    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtube"
    api_version = "v3"
    client_secrets_file = "client_secret.json"

    # Get credentials and create an API client
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    credentials = flow.run_local_server(host="localhost")
    youtube = googleapiclient.discovery.build(api_service_name,
                                              api_version,
                                              credentials=credentials)

    # Get the first 50 liked videos

    request = youtube.videos().list(part="snippet,contentDetails,statistics",
                                    maxResults=50,
                                    myRating="like")

    response = request.execute()
    global g
    g = {}

    page_token = response['nextPageToken']
    for item in response["items"]:
        video_name = item["snippet"]["title"]
        video_id = item["id"]
        g[video_name] = video_id

    while page_token:
        fem = youtube.videos().list(part="snippet,contentDetails,statistics",
                                    maxResults=50,
                                    myRating="like",
                                    pageToken=page_token).execute()

        for item in fem["items"]:
            video_name1 = item["snippet"]["title"]
            video_id1 = item["id"]
            g[video_name1] = video_id1

        if 'nextPageToken' in fem:
            page_token = fem['nextPageToken']
        else:
            break

    num_of_liked_videos = len(g)
    print("The number of liked video is {}".format(str(num_of_liked_videos)))

    return g
Esempio n. 28
0
def _credentials_flow_interactive(client_secrets_path):
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_path,
        scopes=[_ASSISTANT_OAUTH_SCOPE])
    if 'DISPLAY' in os.environ:
        # Use chromium-browser by default. Raspbian Stretch uses Epiphany by
        # default but that seems to cause issues:
        # https://github.com/google/aiyprojects-raspbian/issues/269
        webbrowser.register('chromium-browser', None, webbrowser.Chrome('chromium-browser'), -1)
        credentials = flow.run_local_server()
    else:
        credentials = flow.run_console()
    return credentials
Esempio n. 29
0
def _credentials_flow_interactive(client_secrets_path):
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_path, scopes=[_ASSISTANT_OAUTH_SCOPE])
    if 'DISPLAY' in os.environ:
        # Use chromium-browser by default. Raspbian Stretch uses Epiphany by
        # default but that seems to cause issues:
        # https://github.com/google/aiyprojects-raspbian/issues/269
        webbrowser.register('chromium-browser', None,
                            webbrowser.Chrome('chromium-browser'), -1)
        credentials = flow.run_local_server()
    else:
        credentials = flow.run_console()
    return credentials
Esempio n. 30
0
def make_creds():
    """Need to automate this, but this is the basis for creating credentials to interact with the
    google sheets api"""
    # https://developers.google.com/sheets/api/quickstart/python
    scopes = "https://www.googleapis.com/auth/spreadsheets"
    # flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file("credentials.json", scopes=scopes)
    flow = InstalledAppFlow.from_client_secrets_file('credentials.json',
                                                     scopes)
    creds = flow.run_local_server()
    # Save the credentials for the next run
    with open('token.pickle', 'wb') as token:
        pickle.dump(creds, token)
    return creds
def runAuth():
    # webbrowser.open_new_tab('')  # For convenience.
    # Get credentials and create an API client
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        CLIENT_SECRETS_FILE, scopes)
    if deployOAuthServ:
        credentials = flow.run_local_server()
    else:
        credentials = flow.run_console()
    youtube = googleapiclient.discovery.build(api_service_name,
                                              api_version,
                                              credentials=credentials)
    return youtube
Esempio n. 32
0
def get_authenticated_service(args):
    credentials = None
    file = f"{args['cred']}"

    #Load creds if available
    if os.path.exists(file):
        print("[+]  Credentials found. Using it to authenticate...")
        try:
            with open(file, 'rb') as f:
                credentials = pickle.load(f)
        except:
            print(
                "[+]  Error in credential file...Removing and re-authenticating..."
            )
            os.remove(file)
            return get_authenticated_service(args)

    if not credentials or not credentials.valid:
        if credentials and credentials.expired and credentials.refresh_token:
            print("[+]  Refreshing access token...")
            credentials.refresh(Request())

        else:
            print(f"[+]  Fetching new tokens for ...Please authenticate..")
            flow = InstalledAppFlow.from_client_secrets_file(
                args['CLIENT_SECRETS_FILE'], SCOPES)
            flow.run_local_server(port=9999,
                                  prompt="consent",
                                  authorization_prompt_message="")
            print("[+]  Waiting for port to be released from service...")
            while not os.system("fuser -i 9999/tcp"):
                time.sleep(1)

            credentials = flow.credentials
            with open(file, 'wb') as f:
                print("[+]  Saving credentials...")
                pickle.dump(credentials, f)

    return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)
Esempio n. 33
0
def main(client_secrets, scope, save, credentials, headless):
    """Command-line tool for obtaining authorization and credentials from a user.

    This tool uses the OAuth 2.0 Authorization Code grant as described
    in section 1.3.1 of RFC6749:
    https://tools.ietf.org/html/rfc6749#section-1.3.1

    This tool is intended for assist developers in obtaining credentials
    for testing applications where it may not be possible or easy to run a
    complete OAuth 2.0 authorization flow, especially in the case of code
    samples or embedded devices without input / display capabilities.

    This is not intended for production use where a combination of
    companion and on-device applications should complete the OAuth 2.0
    authorization flow to get authorization from the users.

    """

    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets,
        scopes=scope
    )

    if not headless:
        creds = flow.run_local_server()
    else:
        creds = flow.run_console()

    creds_data = {
        'token': creds.token,
        'refresh_token': creds.refresh_token,
        'token_uri': creds.token_uri,
        'client_id': creds.client_id,
        'client_secret': creds.client_secret,
        'scopes': creds.scopes
    }

    if save:
        del creds_data['token']

        config_path = os.path.dirname(credentials)
        if config_path and not os.path.isdir(config_path):
            os.makedirs(config_path)

        with open(credentials, 'w') as outfile:
            json.dump(creds_data, outfile)

        click.echo('credentials saved: %s' % credentials)

    else:
        click.echo(json.dumps(creds_data))
Esempio n. 34
0
def Init():
    cwd = sys.path[0] + "/"
    scopes = ["https://www.googleapis.com/auth/youtube"]
    #change youtube.readonly to just youtube
    credentials_file = cwd + "json/credentials.json"
    #make this come from config file? also encrypt it?

    # Disable OAuthlib's HTTPS verification when running locally.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
    # *DO NOT* leave this option enabled in production.

    api_service_name = "youtube"
    api_version = "v3"
    client_secrets_file = cwd + "json/client_secret_915368223513-6bt98h496rv56tj4r2uq57te33i7he3p.apps.googleusercontent.com.json"

    # Get client key and secrets and create an API client
    #flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
    #client_secrets_file, scopes);

    if (not os.path.isfile(credentials_file)):  # no credentials file?
        flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
            client_secrets_file, scopes)
        credentials = flow.run_local_server()
        #credentials = flow.run_console();
        cred_json = credentials.to_json()
        print("cred_json:\n", cred_json)
        f = open(cwd + "json/credentials.json", "w")
        f.write(cred_json)
        f.close()

    #get credentials/tokens from file
    credentials = google.oauth2.credentials.Credentials.from_authorized_user_file(
        credentials_file, scopes)

    if (credentials.expired
        ):  #refresh access token if expired and save to json
        credentials.refresh(google.auth.transport.requests.Request())
        # does none need to be there?
        cred_json = credentials.to_json()
        #print("cred_json:\n", cred_json);
        f = open(cwd + "json/credentials.json", "w")
        f.write(cred_json)
        f.close()

    #actual youtube object from which data is retrieved
    youtube = googleapiclient.discovery.build(api_service_name,
                                              api_version,
                                              credentials=credentials)

    return youtube