コード例 #1
0
def get_user_creds():
    try:
        user_creds = google_creds.Credentials(**flask.session['credentials'])
        return user_creds
    except KeyError:
        app.logger.debug('[authorization.get_user_creds] no credentials found')
        return None
コード例 #2
0
ファイル: controller.py プロジェクト: kss2153/hubspot-mr
def create_doc():
    if not session.get('goog_credentials'):
        return redirect(url_for('goog_oauth.authorize_goog'))

    file_id = request.args.get('file_id')
    if file_id is None:
        session['msg_red'] = 'no file id given'
        return redirect(url_for('.main_app'))

    credentials = g_cred.Credentials(**session['goog_credentials'])
    session['goog_credentials'] = credentials_to_dict(credentials)
    try:
        drive_service = build('drive', 'v3', credentials=credentials)
        drive_response = drive_service.files().copy(fileId=file_id).execute()
        document_copy_id = drive_response.get('id')
    except:
        session['msg_red'] = 'failed to copy template'
        return redirect(url_for('.main_app'))

    try:
        service = build('docs', 'v1', credentials=credentials)
        params = get_params()
        requests = list(map(lambda x: get_replace_request(x), params))
        if len(requests) > 0:
            service.documents().batchUpdate(documentId=document_copy_id,
                                            body={
                                                'requests': requests
                                            }).execute()
    except:
        session['msg_red'] = 'failed to replace variables'
        return redirect(url_for('.main_app'))

    session.pop('crm_params', None)
    session['msg_green'] = 'successfully created doc'
    return redirect(url_for('.main_app'))
コード例 #3
0
    def __init__(self, file_path):
        """Initializes a refresh token credential from the specified JSON file.

        Args:
          file_path: File path to a refresh token JSON file.

        Raises:
          IOError: If the specified file doesn't exist or cannot be read.
          ValueError: If the refresh token file is invalid.
        """
        super(RefreshToken, self).__init__()
        with open(file_path) as json_keyfile:
            json_data = json.load(json_keyfile)
        if json_data.get('type') != self._CREDENTIAL_TYPE:
            raise ValueError(
                'Invalid refresh token file: "{0}". File must contain a '
                '"type" field set to "{1}".'.format(file_path,
                                                    self._CREDENTIAL_TYPE))
        try:
            client_id = json_data['client_id']
            client_secret = json_data['client_secret']
            refresh_token = json_data['refresh_token']
        except KeyError as error:
            raise ValueError(
                'Failed to initialize a refresh token credential from file "{0}". '
                'Caused by: "{1}"'.format(file_path, error))
        self._g_credential = credentials.Credentials(
            token=None,
            refresh_token=refresh_token,
            token_uri='https://accounts.google.com/o/oauth2/token',
            client_id=client_id,
            client_secret=client_secret,
            scopes=_scopes)
コード例 #4
0
ファイル: credentials.py プロジェクト: jaegeral/timesketch
    def from_bytes(self, data):
        """Deserialize a credential object from bytes.

        Args:
            data (bytes): serialized credential object.

        Raises:
            TypeError: if the data is not in bytes.
        """
        if not isinstance(data, bytes):
            raise TypeError("Data needs to be bytes.")

        try:
            token_dict = json.loads(data.decode("utf-8"))
        except ValueError as exc:
            raise TypeError("Unable to parse the byte string.") from exc

        self._credential = credentials.Credentials(
            token=token_dict.get("token"),
            refresh_token=token_dict.get("_refresh_token"),
            id_token=token_dict.get("_id_token"),
            token_uri=token_dict.get("_token_uri"),
            client_id=token_dict.get("_client_id"),
            client_secret=token_dict.get("_client_secret"),
        )
コード例 #5
0
def result():
    creds = credentials.Credentials(**session['creds'])
    print(creds)
    service = build('calendar', 'v3', credentials=creds)

    # check available and create calendar/events
    if request.method == 'POST':
        title = request.form['Task Name']
        timezone = request.form['Timezone']
        length = request.form['Duration']
        frequency = request.form['Frequency']
        earliest_time = request.form['Earliest']
        latest_time = request.form['Latest']

        cal_id = create_calendar(service, title, timezone)

        vacant = vacancy_based_on_freq(service, int(length), int(frequency),
                                       int(earliest_time), int(latest_time),
                                       timezone)

        for index, value in vacant.items():
            available_start = vacant[index][0]
            start = (available_start + timedelta(minutes=15)).isoformat()
            end = (available_start +
                   timedelta(minutes=(15 + int(length)))).isoformat()
            result = create_event(service, cal_id, start, end, title,
                                  frequency, length, timezone)

    # session['creds'] = creds_dict(creds)

    return render_template('result.html')
コード例 #6
0
ファイル: connections.py プロジェクト: chrisp-data/all_data
    def get_bigquery_credentials(cls, profile_credentials):
        method = profile_credentials.method
        creds = GoogleServiceAccountCredentials.Credentials

        if method == BigQueryConnectionMethod.OAUTH:
            credentials, _ = get_bigquery_defaults(scopes=cls.SCOPE)
            return credentials

        elif method == BigQueryConnectionMethod.SERVICE_ACCOUNT:
            keyfile = profile_credentials.keyfile
            return creds.from_service_account_file(keyfile, scopes=cls.SCOPE)

        elif method == BigQueryConnectionMethod.SERVICE_ACCOUNT_JSON:
            details = profile_credentials.keyfile_json
            return creds.from_service_account_info(details, scopes=cls.SCOPE)

        elif method == BigQueryConnectionMethod.OAUTH_SECRETS:
            return GoogleCredentials.Credentials(
                token=profile_credentials.token,
                refresh_token=profile_credentials.refresh_token,
                client_id=profile_credentials.client_id,
                client_secret=profile_credentials.client_secret,
                token_uri=profile_credentials.token_uri,
                scopes=cls.SCOPE
            )

        error = ('Invalid `method` in profile: "{}"'.format(method))
        raise FailedToConnectException(error)
コード例 #7
0
 def credentials_fixture(self):
     self.credentials = credentials.Credentials(
         token=None,
         refresh_token=self.REFRESH_TOKEN,
         token_uri=self.TOKEN_URI,
         client_id=self.CLIENT_ID,
         client_secret=self.CLIENT_SECRET)
コード例 #8
0
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
コード例 #9
0
    def form_valid(self, form):
        file_name = form.cleaned_data['video'].temporary_file_path()
        print(file_name)
        credentials_dict = model_to_dict(
            GoogleOAuthCredential.objects.get(
                client_secret=settings.YT_CLIENT_SECRET))
        credential = credentials.Credentials(**credentials_dict)
        youtube = build('youtube', 'v3', credentials=credential)
        body = {
            'snippet': {
                'title': 'Video uploaded using django',
                'description':
                'This video has been uploaded using Django and Youtube Data API.',
                'tags': 'django,api',
                'categoryId': '27'
            },
            'status': {
                'privacyStatus': 'unlisted'
            }
        }

        insert_request = youtube.videos().insert(part=','.join(body.keys()),
                                                 body=body,
                                                 media_body=MediaFileUpload(
                                                     file_name,
                                                     chunksize=-1,
                                                     resumable=True))
        response = insert_request.execute()

        return HttpResponse('<h1>Hooray! It worked!</h1>')
コード例 #10
0
    def test_credentials_with_scopes_requested_refresh_success(
            self, unused_utcnow, refresh_grant):
        scopes = ["email", "profile"]
        default_scopes = ["https://www.googleapis.com/auth/cloud-platform"]
        token = "token"
        new_rapt_token = "new_rapt_token"
        expiry = _helpers.utcnow() + datetime.timedelta(seconds=500)
        grant_response = {
            "id_token": mock.sentinel.id_token,
            "scope": "email profile"
        }
        refresh_grant.return_value = (
            # Access token
            token,
            # New refresh token
            None,
            # Expiry,
            expiry,
            # Extra data
            grant_response,
            # rapt token
            new_rapt_token,
        )

        request = mock.create_autospec(transport.Request)
        creds = credentials.Credentials(
            token=None,
            refresh_token=self.REFRESH_TOKEN,
            token_uri=self.TOKEN_URI,
            client_id=self.CLIENT_ID,
            client_secret=self.CLIENT_SECRET,
            scopes=scopes,
            default_scopes=default_scopes,
            rapt_token=self.RAPT_TOKEN,
        )

        # Refresh credentials
        creds.refresh(request)

        # Check jwt grant call.
        refresh_grant.assert_called_with(
            request,
            self.TOKEN_URI,
            self.REFRESH_TOKEN,
            self.CLIENT_ID,
            self.CLIENT_SECRET,
            scopes,
            self.RAPT_TOKEN,
        )

        # Check that the credentials have the token and expiry
        assert creds.token == token
        assert creds.expiry == expiry
        assert creds.id_token == mock.sentinel.id_token
        assert creds.has_scopes(scopes)
        assert creds.rapt_token == new_rapt_token

        # Check that the credentials are valid (have a token and are not
        # expired.)
        assert creds.valid
コード例 #11
0
ファイル: deploy.py プロジェクト: anjensan/bigflow
def create_storage_client(auth_method: str, project_id: str, vault_endpoint: str, vault_secret: str):
    if auth_method == 'local_account':
        return storage.Client(project=project_id)
    elif auth_method == 'vault':
        oauthtoken = get_vault_token(vault_endpoint, vault_secret)
        return storage.Client(project=project_id, credentials=credentials.Credentials(oauthtoken))
    else:
        raise ValueError('unsupported auth_method: ' + auth_method)
コード例 #12
0
ファイル: gdrive.py プロジェクト: pierreGouedard/datalab
    def init_drive_service(creds):
        creds = credentials.Credentials(None,
                                        refresh_token=creds['refresh_token'],
                                        token_uri=creds['token_uri'],
                                        client_id=creds['client_id'],
                                        client_secret=creds['client_secret'])

        return build('drive', 'v3', credentials=creds)
コード例 #13
0
    def test_refresh_no_refresh_token(self):
        request = mock.create_autospec(transport.Request)
        credentials_ = credentials.Credentials(token=None, refresh_token=None)

        with pytest.raises(exceptions.RefreshError, match="necessary fields"):
            credentials_.refresh(request)

        request.assert_not_called()
コード例 #14
0
 def make_credentials(cls):
     return credentials.Credentials(
         token=None,
         refresh_token=cls.REFRESH_TOKEN,
         token_uri=cls.TOKEN_URI,
         client_id=cls.CLIENT_ID,
         client_secret=cls.CLIENT_SECRET,
     )
コード例 #15
0
def make_credentials():
    return credentials.Credentials(
        token=None,
        refresh_token='refresh',
        token_uri='token_uri',
        client_id='client_id',
        client_secret='client_secret',
    )
コード例 #16
0
 def testGetAuthorizationState_authorized(self):
     """Tests detecting hooks requiring authorization and with credentials."""
     action = ndb_models.TestRunAction(
         name='Test',
         hook_class_name='oauth2',
         credentials=authorized_user.Credentials(None),
     )
     self.assertEqual(ndb_models.AuthorizationState.AUTHORIZED,
                      test_run_hook.GetAuthorizationState(action))
コード例 #17
0
    def test_credentials_with_scopes_refresh_failure_raises_refresh_error(
        self, unused_utcnow, refresh_grant
    ):
        scopes = ["email", "profile"]
        scopes_returned = ["email"]
        token = "token"
        expiry = _helpers.utcnow() + datetime.timedelta(seconds=500)
        grant_response = {
            "id_token": mock.sentinel.id_token,
            "scopes": " ".join(scopes_returned),
        }
        refresh_grant.return_value = (
            # Access token
            token,
            # New refresh token
            None,
            # Expiry,
            expiry,
            # Extra data
            grant_response,
        )

        request = mock.create_autospec(transport.Request)
        creds = credentials.Credentials(
            token=None,
            refresh_token=self.REFRESH_TOKEN,
            token_uri=self.TOKEN_URI,
            client_id=self.CLIENT_ID,
            client_secret=self.CLIENT_SECRET,
            scopes=scopes,
        )

        # Refresh credentials
        with pytest.raises(
            exceptions.RefreshError, match="Not all requested scopes were granted"
        ):
            creds.refresh(request)

        # Check jwt grant call.
        refresh_grant.assert_called_with(
            request,
            self.TOKEN_URI,
            self.REFRESH_TOKEN,
            self.CLIENT_ID,
            self.CLIENT_SECRET,
            scopes,
        )

        # Check that the credentials have the token and expiry
        assert creds.token == token
        assert creds.expiry == expiry
        assert creds.id_token == mock.sentinel.id_token
        assert creds.has_scopes(scopes)

        # Check that the credentials are valid (have a token and are not
        # expired.)
        assert creds.valid
コード例 #18
0
ファイル: sdk_test_base.py プロジェクト: bopopescu/gcloud_cli
 def _FakeAuthCredential(self, use_google_auth):
   if use_google_auth:
     return credentials.Credentials(self.FakeAuthAccessToken(),
                                    'refresh_token', 'id_token', 'token_uri',
                                    'client_id')
   return client.OAuth2Credentials(
       self.FakeAuthAccessToken(), 'client_id', 'client_secret',
       'refresh_token', self.FakeAuthExpiryTime(), 'token_uri',
       self.FakeAuthUserAgent())
コード例 #19
0
ファイル: export.py プロジェクト: PhilInTheGaps/gdocs-export
def get_credentials():
    with open(CREDENTIALS_FILE, 'r', encoding='utf-8') as f:
        data = json.load(f)
        return credentials.Credentials(data['token'], data["refresh_token"],
                                       data["id_token"], data["token_uri"],
                                       data["client_id"],
                                       data["client_secret"], data["scopes"])

    return None
コード例 #20
0
def _convert_oauth(credentials):
    return oauth2.Credentials(
        credentials.access_token,
        credentials.refresh_token,
        credentials.id_token,
        credentials.token_uri,
        credentials.client_id,
        credentials.client_secret,
        credentials.scopes,
    )
コード例 #21
0
def make_credentials_my():
    return credentials.Credentials(
        token=
        'ya29.a0AfH6SMA_XZN9uqR6ShnPdAHXgoNxXzblmw7rqfZYS_2cxB6Q5ylcF6t1atfUkrmZbJ2dcHehwDJShan83WkNLIkNOIhhuMi1zUSDgXnWfWqSHrqJoSoKv7r5KZLesNyPl5QSmeLx7uXuTXx66QaFhLkH4UOWga9ZdQfOSMp35xYx',
        refresh_token=
        '1//06DpNb1ABrvveCgYIARAAGAYSNwF-L9IrNeIMPi0fmyBNP_O_C3epXaaiqLKWmZ5pK9rs8oYHM__-8A4yaLQc_igCvH268v6q6C8',
        token_uri='https://www.googleapis.com/oauth2/v4/token',
        client_id='32555940559.apps.googleusercontent.com',
        client_secret='ZmssLNjJy2998hD4CTg2ejr2',
    )
コード例 #22
0
def GetFakeCredGoogleAuth():
  return google_auth_creds.Credentials(
      token='fake-token',
      refresh_token='file-token',
      id_token='fake-id-token',
      token_uri='fake-token-uri',
      client_id='foo.apps.googleusercontent.com',
      client_secret='file-secret',
      scopes=['scope1', 'scope2'],
  )
コード例 #23
0
 def setUp(self, api_class=test_run_action_api.TestRunActionApi):
     super(TestRunActionApiTest, self).setUp(api_class)
     self.test_run_actions = [
         self._CreateTestRunAction(name='one', hook_class_name='simple'),
         self._CreateTestRunAction(name='two', hook_class_name='oauth2'),
         self._CreateTestRunAction(
             name='three',
             hook_class_name='oauth2',
             credentials=authorized_user.Credentials(None))
     ]
コード例 #24
0
 def testValidate(self):
     """Tests that the credentials type is validated."""
     prop = oauth2_util.CredentialsProperty()
     # None is allowed
     prop._validate(None)
     # User authorization and service accounts are allowed
     prop._validate(authorized_user.Credentials(None))
     prop._validate(service_account.Credentials(None, None, None))
     # Anything else is forbidden
     with self.assertRaises(TypeError):
         prop._validate({})
コード例 #25
0
 def testUnauthorize(self):
     """Tests that a build channel can be unauthorized."""
     config = self._CreateMockBuildChannel(name='android',
                                           provider='Android')
     config.credentials = authorized_user.Credentials(None)
     config.put()
     # Verify that credentials were removed
     self.app.delete('/_ah/api/mtt/v1/build_channels/%s/auth' %
                     config.key.id())
     config = ndb_models.BuildChannelConfig.get_by_id(config.key.id())
     self.assertIsNone(config.credentials)
コード例 #26
0
 def testOauth2client(self):
     google_auth_cred = google_auth_creds.Credentials('google_auth_token')
     oauth2client_cred = client.Credentials()
     oauth2client_cred.access_token = 'oauth2client_token'
     self.c_store_refresh = self.StartObjectPatch(c_store,
                                                  'Refresh',
                                                  autospec=True,
                                                  return_value=None)
     self.AssertEqual('google_auth_token',
                      iap_tunnel._GetAccessTokenCallback(google_auth_cred))
     self.AssertEqual('oauth2client_token',
                      iap_tunnel._GetAccessTokenCallback(oauth2client_cred))
コード例 #27
0
    def test_apply_with_no_quota_project_id(self):
        creds = credentials.Credentials(
            token="token",
            refresh_token=self.REFRESH_TOKEN,
            token_uri=self.TOKEN_URI,
            client_id=self.CLIENT_ID,
            client_secret=self.CLIENT_SECRET,
        )

        headers = {}
        creds.apply(headers)
        assert "x-goog-user-project" not in headers
コード例 #28
0
    def testExecuteHook_withContextVariables(self, mock_init, mock_log,
                                             mock_execute):
        """Tests that a hook can be constructed and executed."""
        test = ndb_models.Test(name='test', command='command')
        test.put()
        test_run = ndb_models.TestRun(
            test=test,
            test_run_config=ndb_models.TestRunConfig(test_key=test.key),
            test_resources=[
                ndb_models.TestResourceObj(
                    name='device_image',
                    url='mtt:///android_ci/branch/target/build_id/image.zip',
                    test_resource_type=ndb_models.TestResourceType.DEVICE_IMAGE
                )
            ])
        test_run.put()
        mock_init.return_value = None
        hook_context = mock.MagicMock()
        hook_context.test_run = test_run
        credentials = authorized_user.Credentials(None)
        action = ndb_models.TestRunAction(
            name='Test',
            hook_class_name='simple',
            options=[
                ndb_models.NameValuePair(name='ham', value='eggs'),
                ndb_models.NameValuePair(name='test_run_id',
                                         value='${MTT_TEST_RUN_ID}'),
                ndb_models.NameValuePair(name='device_image_url',
                                         value='${MTT_DEVICE_IMAGE_URL}'),
                ndb_models.NameValuePair(name='device_image_branch',
                                         value='${MTT_DEVICE_IMAGE_BRANCH}'),
                ndb_models.NameValuePair(name='device_image_target',
                                         value='${MTT_DEVICE_IMAGE_TARGET}'),
                ndb_models.NameValuePair(name='device_image_build_id',
                                         value='${MTT_DEVICE_IMAGE_BUILD_ID}'),
            ],
            credentials=credentials,
        )

        test_run_hook._ExecuteHook(action, hook_context)

        mock_init.assert_called_with(
            _credentials=credentials,
            ham='eggs',
            test_run_id=str(test_run.key.id()),
            device_image_url=
            'mtt:///android_ci/branch/target/build_id/image.zip',
            device_image_branch='branch',
            device_image_target='target',
            device_image_build_id='build_id')
        mock_log.assert_called()
        mock_execute.assert_called_with(hook_context)
コード例 #29
0
ファイル: utils.py プロジェクト: alexyu0/gspread
def test_api_request():
    if 'credentials' not in flask.session:
        return flask.redirect('authorize')

    # Load credentials from the session.
    credentials = oauth2_creds.Credentials(**flask.session['credentials'])
    credentials = _credentials_to_dict(credentials)

    # TODO maybe save these credentials in a persistent database instead.
    flask.session['credentials'] = credentials
    pp.pprint(credentials)

    return flask.jsonify(credentials)
コード例 #30
0
    def test_apply_with_quota_project_id(self):
        creds = credentials.Credentials(
            token="token",
            refresh_token=self.REFRESH_TOKEN,
            token_uri=self.TOKEN_URI,
            client_id=self.CLIENT_ID,
            client_secret=self.CLIENT_SECRET,
            quota_project_id="quota-project-123",
        )

        headers = {}
        creds.apply(headers)
        assert headers["x-goog-user-project"] == "quota-project-123"
        assert "token" in headers["authorization"]