def _get_credentials(self):
     if getattr(self, '_auth_token', None):
         # upgrade from gdata auth token structure
         creds = Credentials(
             token=self._auth_token.access_token,
             refresh_token=self._auth_token.refresh_token,
             token_uri=self._auth_token.token_uri,
             client_id=self._auth_token.client_id,
             client_secret=self._auth_token.client_secret,
         )
         self._update_credentials(creds)
         self._auth_token = None
     elif 'token' in self._state:
         CRED_ARGS = [
             'token', 'refresh_token', 'token_uri', 'client_id',
             'client_secret'
         ]
         creds = Credentials(
             **{
                 key: value
                 for key, value in self._state.items() if key in CRED_ARGS
             })
     else:
         creds = None
     return creds
Esempio n. 2
0
def _validate_user(service_account, customer_id, user_id):
    global _user_service
    global _group_service
    global _user_validation_cache
    global allow_groups
    if not _user_service:
        client = IAMCredentialsClient()
        name = 'projects/-/serviceAccounts/%s' % service_account
        response = client.generate_access_token(
            name=name,
            scope=[
                'https://www.googleapis.com/auth/admin.directory.user.readonly'
            ])
        credentials = Credentials(response.access_token)
        _user_service = build('admin', 'directory_v1', credentials=credentials)

    if not _group_service and allow_groups:
        client = IAMCredentialsClient()
        name = 'projects/-/serviceAccounts/%s' % service_account
        response = client.generate_access_token(
            name=name,
            scope=[
                'https://www.googleapis.com/auth/admin.directory.group.readonly'
            ])
        credentials = Credentials(response.access_token)
        _group_service = build('admin', 'directory_v1', credentials=credentials)

    _user_validation_cache[user_id] = False
    try:
        results = _user_service.users().get(userKey=user_id).execute()
        if isinstance(results, dict):
            _user_validation_cache[user_id] = True
    except googleapiclient.errors.Error as e:
        try:
            results = _user_service.users().list(customer=customer_id,
                                                 query='email=%s' %
                                                 user_id).execute()
            if 'users' in results:
                _user_validation_cache[user_id] = True
            else:
                raise googleapiclient.errors.Error('Pass to group handler')
        except googleapiclient.errors.Error as e:
            if allow_groups:
                try:
                    group = _group_service.groups().get(
                        groupKey=user_id).execute()
                    if 'id' in group:
                        _user_validation_cache[user_id] = True
                except googleapiclient.errors.Error as e:
                    pass
            else:
                pass
    return _user_validation_cache[user_id]
Esempio n. 3
0
def importPage(request):
    sheetUrl = request.POST.get('url')
    splitUrl = sheetUrl.split('/')
    sheetID = splitUrl[5]

    SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
    social_token = SocialToken.objects.get(account__user=request.user)
    creds = Credentials(token=social_token.token,
                        refresh_token=social_token.token_secret,
                        scopes=SCOPES,
                        client_id=social_token.app.client_id,
                        client_secret=social_token.app.secret)

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

    # Get the to-do list based off the URL the user provided, must be a To do list Google Sheet (for now)
    result = service.spreadsheets().values().get(
        spreadsheetId=sheetID, range='To do!B4:C',
        majorDimension='COLUMNS').execute()
    cols = result.get('values', [])

    # The import page will retrieve the list of lists of date and task name values
    context = {'input': cols}

    return render(request, 'import.html', context)
Esempio n. 4
0
def create_gcp_bucket(files, bucket_prefix, project_id, access_token):
    archive_file_path = _create_archive_directory(files, bucket_prefix)

    try:
        credentials = Credentials(access_token)
        client = storage.Client(project_id, credentials)

        bucket_name = '{0}-{1}'.format(bucket_prefix, uuid.uuid4())
        bucket = client.create_bucket(bucket_name)

    except GoogleAuthError as gae:
        print(gae)
        return 'Could not authenticate to GCP!'

    except BadRequest as br:
        print(br)
        return str(br)

    except ValueError as ve:
        print(ve)
        return str(ve)

    for d in ['config', 'content', 'software', 'license']:
        print('creating directory of type: {}'.format(d))
        d_dir_blob = bucket.blob('{}/'.format(d))
        d_dir_blob.upload_from_string(
            '', content_type='application/x-www-form-urlencoded;charset=UTF-8')
        d_dir = os.path.join(archive_file_path, d)
        for filename in os.listdir(d_dir):
            print('creating file: {0}'.format(filename))
            d_dir_file = bucket.blob('{0}/{1}'.format(d, filename))
            d_dir_file.upload_from_filename(os.path.join(d_dir, filename))

    print('all done')
    return 'GCP Bucket {} created successfully'.format(bucket_name)
def google_auth_installed(secret_file: str, token_file: str,
                          scopes: List[str]) -> Credentials:
    """Authenticate installed applications with Google"""
    try:
        with open(token_file, "rt") as token_file:
            token_data = json.load(token_file)
        credentials = Credentials(
            None,
            refresh_token=token_data.get("refresh_token"),
            token_uri=token_data.get("token_uri"),
            client_id=token_data.get("client_id"),
            client_secret=token_data.get("client_secret"),
        )
    except Exception as exc:
        logging.debug("Exception: %s", str(exc))
        flow = InstalledAppFlow.from_client_secrets_file(secret_file, scopes)
        credentials = flow.run_console()
        token_data = {
            "refresh_token": credentials.refresh_token,
            "token_uri": credentials.token_uri,
            "client_id": credentials.client_id,
            "client_secret": credentials.client_secret,
        }
        with open(token_file, "wt") as token_file:
            json.dump(token_data, token_file)
        logging.info("Credentials saved to %s", token_file)
    return credentials
Esempio n. 6
0
    def refresh_access_token(self, user_id: int, refresh_token: str):
        client = self.client_config["web"]
        user = self.get_user(user_id)
        credentials = Credentials(token=user["access_token"],
                                  refresh_token=user["refresh_token"],
                                  client_id=client["client_id"],
                                  client_secret=client["client_secret"],
                                  token_uri=client["token_uri"],
                                  scopes=YOUTUBE_SCOPES,
                                  expiry=user["token_expires"])
        try:
            credentials.refresh(Request())
        except RefreshError as error:
            # refresh error has error message as first arg and the actual error response from the api in the second arg
            error_body = error.args[1]
            if "error" in error_body and error_body["error"] == "invalid_grant":
                raise ExternalServiceInvalidGrantError(error_body)

            raise ExternalServiceAPIError(
                "Could not refresh API Token for Youtube user")
        external_service_oauth.update_token(
            user_id=user_id,
            service=self.service,
            access_token=credentials.token,
            refresh_token=credentials.refresh_token,
            expires_at=int(
                credentials.expiry.replace(tzinfo=timezone.utc).timestamp()))
        return self.get_user(user_id)
def is_user_youtube_auth_valid(
        credentials_from_db: Union[dict,
                                   Credentials]) -> Union[Credentials, bool]:
    if isinstance(credentials_from_db, dict):
        # TODO:::add saving after token refreshing
        if not credentials_from_db['token']:
            return False

        if 'id' in credentials_from_db:
            del credentials_from_db['id']
        if 'user' in credentials_from_db:
            del credentials_from_db['user']

        credentials_from_db['expiry'] = credentials_from_db[
            'expiry'].astimezone(pytz.UTC).replace(tzinfo=None)

        credentials = Credentials(**credentials_from_db)
    else:
        credentials = credentials_from_db

    if credentials.valid:
        return credentials

    if credentials.expired and credentials.refresh_token:
        credentials.refresh(Request())
        if credentials.valid:
            return credentials

    return False
Esempio n. 8
0
def load_dico(manulex_spreadsheet_id, refresh_token, client_id, client_secret):
    credentials = Credentials(
        None,
        refresh_token=refresh_token,
        client_id=client_id,
        client_secret=client_secret,
        scopes=['https://www.googleapis.com/auth/spreadsheets.readonly'],
        token_uri="https://accounts.google.com/o/oauth2/token")
    service = build('sheets', 'v4', credentials=credentials)

    sheet = service.spreadsheets()
    result = sheet.values().get(spreadsheetId=manulex_spreadsheet_id,
                                range='dico manulex!A1:E').execute()
    values = result.get('values', [])

    lines = []

    def format_line(line):
        word, phonetic, blending, relations = line

        return ({
            'word': word,
            'phonetic': phonetic,
            'blending': blending.split('-'),
            'relations': relations.split('.')
        })

    lines = list(map(format_line, values[1:-1]))

    dico = {line['word']: line['relations'] for line in lines}
    return dico
Esempio n. 9
0
def api_response():
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
    api_service_name = "youtube"
    api_version = "v3"
    client_secrets_file = r'C:\Users\edams\AppData\Roaming\Code\User\VSC_Workspace\.vscode\python\.vscode\client_secret_440876599079-lotmaj2kiqssjodtf8k31f98uee6gl7f.apps.googleusercontent.com.json'

    #USING TEXT FILE TO RETREIVE CREDENTIALS
    if os.path.isfile("credentials.json"):
        with open("credentials.json", "r") as f:
            creds_data = json.load(f)
            client_id = creds_data['client_id']
            client_secret = creds_data['client_secret']
            refresh_token = creds_data['refresh_token']
        access_token = refreshToken(client_id, client_secret, refresh_token)
        creds = Credentials(access_token)
    else:
        # Get credentials and create an API client
        flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
            client_secrets_file, scopes)
        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
        }
        with open("credentials.json",
                  'w') as outfile:  #WRITING CREDENTIALS TO FILE
            json.dump(creds_data, outfile)
    return build(api_service_name, api_version, credentials=creds)
Esempio n. 10
0
 def google_credentials(self):
     return Credentials(
         self._google_token,
         refresh_token=self._google_refresh_token,
         client_id=self._google_client_id,
         client_secret=self._google_client_secrete,
         token_uri='https://accounts.google.com/o/oauth2/token')
Esempio n. 11
0
 def __init__(self) -> None:
     self.flow = InstalledAppFlow.from_client_config(
         {
             'installed': {
                 'client_id':
                 get_key('client_id'),
                 'project_id':
                 get_key('project_id'),
                 'auth_uri':
                 get_key('auth_uri'),
                 'token_uri':
                 get_key('token_uri'),
                 'auth_provider_x509_cert_url':
                 get_key('auth_provider_x509_cert_url'),
                 'client_secret':
                 get_key('client_secret'),
             }
         },
         SCOPES,
         redirect_uri=get_key('redirect_uri'),
     )
     self.credentials = Credentials(
         None,
         refresh_token=get_key('refresh_token'),
         token_uri='https://accounts.google.com/o/oauth2/token',
         client_id=get_key('client_id'),
         client_secret=get_key('client_secret'),
     )
     self.build = generate_build(self.credentials)
     self.channel_id = channels_list_by_id(
         self.build,
         part='snippet,contentDetails,statistics',
         mine='True',
     )['items'][0]['id']
Esempio n. 12
0
def get_profile_info():
    credentials = Credentials(**session['credentials'])
    service = build('oauth2', 'v2', credentials=credentials)
    profile_info = service.userinfo().get().execute()
    session['credentials'] = utils.credentials_to_dict(credentials)

    return profile_info
Esempio n. 13
0
    def get(self, id):
        '''Get a group'''
        credentials = Credentials(
            token.get_access_token_for_scopes(self.config, [
                'https://www.googleapis.com/auth/admin.directory.group.readonly'
            ]))
        group_service = build('admin',
                              'directory_v1',
                              credentials=credentials,
                              cache=get_discovery_cache())
        try:
            group = group_service.groups().get(groupKey=id).execute()
        except Exception:
            logger.exception('Error fetching group', exc_info=True)
            api.abort(404, "Group {} doesn't exist".format(id))

        if 'id' in group:
            _group = {
                'id': group['id'],
                'email': group['email'],
                'name': group['name'],
                'description': group['description'],
            }
            return _group

        api.abort(404, "Group {} doesn't exist".format(id))
Esempio n. 14
0
def a_view(request):
    if 'credentials' not in request.session:
        request.session['endurl'] = _build_full_view_url(request, 'a_view')
        return HttpResponseRedirect('authorize')

    credentials = Credentials(**request.session['credentials'])
    service = build('calendar', 'v3', credentials=credentials)

    # Call the Calendar API
    now = datetime.datetime.utcnow().isoformat(
    ) + 'Z'  # 'Z' indicates UTC time
    print('Getting the upcoming 10 events')
    events_result = service.events().list(calendarId='primary',
                                          timeMin=now,
                                          maxResults=10,
                                          singleEvents=True,
                                          orderBy='startTime').execute()
    events = events_result.get('items', [])

    if not events:
        print('No upcoming events found.')
    for event in events:
        start = event['start'].get('dateTime', event['start'].get('date'))
        print(start, event['summary'])

    return Response({"message": "Hello, world!"})
Esempio n. 15
0
    def load_credentials(self, subject=None):
        #Load items from file
        with open(self.credentials_path, 'r') as f:
            creds = json.load(f)
        creds = creds['installed']
        client_id = creds['client_id']
        client_secret = creds['client_secret']
        redirect_uri = creds['redirect_uris'][0]
        token_uri = creds['token_uri']
        authorize_url = creds['auth_uri']

        #Create Authorized Session
        self.authsession = self.create_authsession(client_id, client_secret,
                                                   self.scopes, redirect_uri)

        #Get Authorization URL
        self.uri, self.state = self.authsession.authorization_url(
            authorize_url)

        #Open Authorization URL
        webbrowser.open(self.uri)

        #Get authorization Code
        code = input('Please enter code...')
        print('Using code ' + code)

        #Get access token
        self.token = self.authsession.fetch_access_token(
            url='https://www.googleapis.com/oauth2/v4/token', code=code)

        #Create Credentials Object
        self.creds = Credentials(self.token['access_token'])

        #Build Services
        self.drive_service = build('drive', 'v3', credentials=self.creds)
Esempio n. 16
0
def click(index: int):
    try:
        int(index)
    except ValueError:
        return "", 404
    if int(index) >= 5:
        return "", 404

    res = db.get(f"click:{index}")
    if res is not None:
        print("Cached")
        return redirect(
            res["value"],
            code=301)
    creds = Credentials(refresh_token, refresh_token=refresh_token,
                        token_uri="https://accounts.google.com/o/oauth2/token",
                        client_id=google_data["client_id"], client_secret=google_data["client_secret"])
    youtube = build(
        api_service_name, api_version, credentials=creds)
    vid_id = youtube.playlistItems().list(playlistId="LM", part="snippet").execute()
    vid_url = f'https://www.youtube.com/watch?v={vid_id["items"][int(index)]["snippet"]["resourceId"]["videoId"]}'
    db.put(vid_url, f"click:{index}", expire_at=datetime.datetime.now() + datetime.timedelta(hours=1))
    return redirect(
        vid_url,
        code=301)
Esempio n. 17
0
 def toCredentials(self, client_id, client_secret):
     return Credentials(
         None,  # No access token, must be refreshed.
         refresh_token=self.refresh_token,
         token_uri=self.token_uri,
         client_id=client_id,
         client_secret=client_secret)
Esempio n. 18
0
 def make_credentials():
     client_id = Env.get_environment('GOOGLE_CLIENT_ID')
     client_secret = Env.get_environment('GOOGLE_CLIENT_SECRET')
     refresh_token = Env.get_environment('GOOGLE_REFRESH_TOKEN')
     return Credentials(DUMMY_ACCESS_TOKEN, refresh_token, None,
                        "https://oauth2.googleapis.com/token", client_id,
                        client_secret, SCOPES)
Esempio n. 19
0
def lambda_handler(event, context):
    creds = Credentials(token=event['access_token'],
                        refresh_token=event['refresh_token'],
                        client_id=event['client_id'],
                        token_uri=event['token_uri'],
                        client_secret=event['client_secret'])
    service = build('calendar', 'v3', credentials=creds, cache_discovery=False)
    event = {
        'summary':
        event['calsumm'],
        'location':
        event['calloc'],
        'description':
        event['caldesc'],
        'attendees': [
            {
                'email': event['mail']['id1']
            },
            {
                'email': event['mail']['id2']
            },
        ],
    }
    event = service.events().patch(calendarId='primary',
                                   eventId=event['caleveid'],
                                   body=event).execute()

    return {'statusCode': 200, 'body': json.dumps('Success!')}
Esempio n. 20
0
    def authorize(self, token):
        from google.oauth2 import id_token
        from google.auth.transport import requests
        try:
            idinfo = id_token.verify_oauth2_token(token, requests.Request(),
                                                  self.google_client_id)
            if idinfo['iss'] not in [
                    'accounts.google.com', 'https://accounts.google.com'
            ]:
                raise ValueError('Wrong issuer.')

            # If auth request is from a G Suite domain:
            # if idinfo['hd'] != GSUITE_DOMAIN_NAME:
            #     raise ValueError('Wrong hosted domain.')

            # ID token is valid. Get the user's Google Account ID from the decoded token.
            userid = idinfo['sub']
        except ValueError:
            # Invalid token
            pass

        return Credentials(
            token=self.google_access_token,
            refresh_token=self.google_refresh_token,
            token_uri="https://accounts.google.com/o/oauth2/token",
            client_id=self.google_client_id,
            client_secret=self.google_client_secret,
        )
Esempio n. 21
0
def import_contacts(request):
    if 'google_credentials' in request.session:
        credentials = Credentials(**request.session['google_credentials'])
    else:
        return JsonResponse({'authorized': False})

    people = build('people', 'v1', credentials=credentials).people()

    # check if the token is good
    try:
        people.connections().list(resourceName='people/me',
                                  personFields='names').execute()
    except RefreshError:
        return JsonResponse({'authorized': False})

    contacts = []
    page_token = None

    while True:
        page, page_token = fetch_page(people, page_token)
        contacts += page
        if not page_token:
            break

    contacts.sort(key=lambda c: (c['last_name'], c['first_name']))
    return JsonResponse({'authorized': True, 'contacts': contacts})
Esempio n. 22
0
 def ee_init(self):
     """Loads the EE credentials and initializes the EE client."""
     if self.service_account_file:
         credentials = ee.ServiceAccountCredentials(
             self.client_email, self.service_account_file)
     elif self.account and self.private_key:
         credentials = ee.ServiceAccountCredentials(self.account,
                                                    self.private_key)
     elif self.refresh_token:
         credentials = Credentials(None,
                                   refresh_token=self.refresh_token,
                                   token_uri=ee.oauth.TOKEN_URI,
                                   client_id=ee.oauth.CLIENT_ID,
                                   client_secret=ee.oauth.CLIENT_SECRET,
                                   scopes=ee.oauth.SCOPES)
     else:
         credentials = 'persistent'
     # If a --project flag is passed into a command, it supercedes the one set
     # by calling the set_project command.
     project = self.project
     if self.project_override is not None:
         project = self.project_override
     ee.Initialize(credentials=credentials,
                   opt_url=self.url,
                   use_cloud_api=self.use_cloud_api,
                   cloud_api_key=self.cloud_api_key,
                   project=project)
Esempio n. 23
0
def _get_calendar_events(request, preferences):
    """Returns list of (event_id, event_name) tuples of calendar events for current day."""
    credentials = Credentials(**request.session['credentials'])
    ids_and_titles, event_map = get_events_current_day(credentials, preferences)
    request.session['credentials'] = _credentials_to_dict(credentials)
    request.session['event_map'] = event_map
    return ids_and_titles
Esempio n. 24
0
def request_google_calendar_api():
	if 'credentials' not in flask.session:
		print('credentials not in flask session')
		return flask.redirect(GOOGLE_CALENDAR_AUTH_ROUTE)

	credentials = Credentials(**flask.session['credentials'])
	if credentials.expired is False and credentials.valid is True:
		service = googleapiclient.discovery.build(API_SERVICE_NAME, API_VERSION, credentials=credentials)
		try:
			calendarList = service.calendarList().list().execute()
			primaryCal = next((filter(lambda cal: (cal.get('primary') == True), calendarList.get('items'))))
		except RefreshError as e:
			print(e)
			del flask.session['credentials']
			return flask.redirect(GOOGLE_CALENDAR_AUTH_ROUTE)
	else:
		flask.flash('Google account is not authorized.', 'danger')
		return flask.redirect(flask.url_for('home', _scheme=HTTP_SCHEME))
	
	if current_user.google_calendar_user:
		existing_user = GoogleCalendarUser.query.filter(GoogleCalendarUser.id == current_user.google_calendar_user.id).one_or_none()
		user = update_existing_user_creds(existing_user, credentials, primaryCal, current_user)
	else:
		user = add_new_user_creds(credentials, primaryCal, current_user)

	return flask.jsonify(get_credentials_dict(user))
Esempio n. 25
0
    def auth(self, scopes=None) -> Credentials:
        if scopes is None:
            scopes = oauth_scopes

        flow = InstalledAppFlow.from_client_secrets_file(self.config.secrets,
                                                         scopes=scopes,
                                                         redirect_uri='urn:ietf:wg:oauth:2.0:oob')

        refresh_token = self.config.refresh_token
        if refresh_token is not None:
            client_cfg = flow.client_config
            refresh_req = Request()

            fresh = Credentials(None,
                                refresh_token=refresh_token,
                                token_uri=client_cfg['token_uri'],
                                client_id=client_cfg['client_id'],
                                client_secret=client_cfg['client_secret'])
            fresh.refresh(refresh_req)
            if fresh.valid:
                return fresh

            print('cfg.user.refresh_token expired. ', end='', file=sys.stderr)

        credentials = flow.run_console(
            authorization_prompt_message='please login:\n\n\t{url}\n',
            authorization_code_message='auth code: ')
        return credentials
Esempio n. 26
0
    def check(self, emails_models_to_check):
        dispatchers_models = OperationsUsers.objects.filter(
            company=self._company_to_check)
        dispatchers_email = [{
            'nick': dispatcher.nick_name,
            'amount': 0
        } for dispatcher in dispatchers_models]
        self.info['boxes_to_check'] = len(emails_models_to_check)
        current_box = 0
        print(f"boxes to check {emails_models_to_check}")
        for email_model in emails_models_to_check:
            current_box += 1
            self.info['current_box_number'] = current_box
            self.info['current_message'] = f"Checking {email_model.email}"
            creds = Credentials(
                token=email_model.token,
                refresh_token=email_model.refresh_token,
                token_uri=google_config['token_uri'],
                client_id=google_config['client_id'],
                client_secret=google_config['client_secret'],
                scopes=['https://www.googleapis.com/auth/spreadsheets'])
            checker = CheckerEmails(creds, email_model.email, self.info)
            checker.check_emails_by_dispatchers(dispatchers_email, self._dates)

        self.info['dispatchers'] = dispatchers_email
        self.info['state'] = "finish"

        print('finish')
Esempio n. 27
0
 def __init__(self, current_user_id, folder_id=None, activity=False):
     self.folder_id = folder_id
     self.refresh = False
     if (FALLBACK_AUTH == True and EXTERNAL_AUTH_ALLOWED == False):
         self.current_user = UserProfile.objects.select_related('user').get(
             tags__contains=['fallback=1'])
         self.userList = [self.current_user.user.id]
     else:
         self.current_user = User.objects.get(id=int(current_user_id))
         self.userList = [current_user_id]
     credentials = None
     if (current_user_id == None and EXTERNAL_AUTH_ALLOWED == True):
         g_auth = json.loads(self.current_user.userprofile.gdrive_auth)
     elif (FALLBACK_AUTH == True and EXTERNAL_AUTH_ALLOWED == False):
         g_auth = json.loads(self.current_user.gdrive_auth)
     else:
         g_auth = json.loads(
             User.objects.select_related('userprofile').get(
                 id=current_user_id).userprofile.gdrive_auth)
     credentials = Credentials(token=g_auth['access_token'],
                               refresh_token=g_auth['refresh_token'],
                               token_uri=TOKEN_URL,
                               client_id=CLIENT_ID,
                               client_secret=CLIENT_SECRET)
     if (not credentials) or (not credentials.valid):
         if (credentials and credentials.expired
                 and credentials.refresh_token):
             credentials.refresh(Request())
     if (activity == False):
         self.service = build('drive', 'v3', credentials=credentials)
     elif (activity == True):
         self.service = build('driveactivity',
                              'v2',
                              credentials=credentials)
Esempio n. 28
0
def get_service(user):
    social = user.social_auth.get(provider='google-oauth2')
    ls = load_strategy()
    access_token = social.get_access_token(ls)
    credentials = Credentials(access_token)
    service = build('drive', 'v3', credentials=credentials)
    return service
Esempio n. 29
0
def get_google_token(access_token,
                     refresh_token,
                     client_id=os.environ.get('CLIENT_ID'),
                     client_secret=os.environ.get('SECRET_GOOGLE'),
                     uri=os.environ.get("REDIRECT_URI")):
    """
    Custom function responsible for generating credentials object
    based on the data provided by the user in request.
    """
    creds = Credentials(
        token=access_token,
        refresh_token=refresh_token,
        #token_uri=request.data["token_uri"],
        token_uri=uri,
        client_id=client_id,
        client_secret=client_secret,
        scopes=[
            "https://www.googleapis.com/auth/calendar.app.created",
            "https://www.googleapis.com/auth/calendar.events.freebusy",
            "https://www.googleapis.com/auth/calendar.freebusy",
            "https://www.googleapis.com/auth/calendar",
            "https://www.googleapis.com/auth/calendar.events",
            "https://www.googleapis.com/auth/calendar.events.owned",
            "https://www.googleapis.com/auth/calendar.calendarlist",
            "https://www.googleapis.com/auth/calendar.calendars",
            "https://www.googleapis.com/auth/calendar.acls"
        ])
    return creds
Esempio n. 30
0
def hello_world(index: int):
    try:
        int(index)
    except ValueError:
        return "", 404
    if int(index) >= 5:
        return "", 404
    res = db.get(f"pic:{index}")
    if res is not None:
        print("Cached")
        return Response(res["value"], mimetype="image/svg+xml")
    creds = Credentials(refresh_token, refresh_token=refresh_token,
                        token_uri="https://accounts.google.com/o/oauth2/token",
                        client_id=google_data["client_id"], client_secret=google_data["client_secret"])
    youtube = build(
        api_service_name, api_version, credentials=creds)
    vid_id = youtube.playlistItems().list(playlistId="LM", part="snippet").execute()
    # print(json.dumps(vid_id["items"][0]["snippet"]))
    thumbnail_url = vid_id["items"][int(index)]["snippet"]["thumbnails"]["default"]["url"]
    req = requests.get(thumbnail_url)
    # print(thumbnail_url)
    data = {
        "title": vid_id["items"][int(index)]["snippet"]["title"],
        "artist": vid_id["items"][int(index)]["snippet"]["videoOwnerChannelTitle"],
        "thumbnail": f"data:image/jpeg;base64,{base64.b64encode(req.content).decode('utf-8')}",
        "url": f'https://www.youtube.com/watch?v={vid_id["items"][int(index)]["snippet"]["resourceId"]["videoId"]}'
    }
    template = env.get_template("svg_template.jinja2")
    rendered_template = template.render(data)
    db.put(rendered_template, f"pic:{index}", expire_at=datetime.datetime.now() + datetime.timedelta(hours=1))
    return Response(rendered_template, mimetype="image/svg+xml")