Exemplo n.º 1
0
def google_info_from_token(token):
    idinfo = id_token.verify_token(token, settings.GOOGLE_CLIENT_ID)
    if idinfo['aud'] != settings.GOOGLE_CLIENT_ID:
        raise GoogleAuthError('aud dont match')
    if idinfo['iss'] not in [
            'accounts.google.com', 'https://accounts.google.com'
    ]:
        raise GoogleAuthError("Wrong issuer.")
    return idinfo
Exemplo n.º 2
0
def complete_google_auth(request):
    """Admin view that handles the redirect from Google after completing Google auth"""
    if not settings.FEATURES.get("COUPON_SHEETS"):
        raise Http404
    state = request.session.get("state")
    if not state:
        raise GoogleAuthError(
            "Could not complete Google auth - 'state' was not found in the session"
        )
    flow = Flow.from_client_config(generate_google_client_config(),
                                   scopes=REQUIRED_GOOGLE_API_SCOPES,
                                   state=state)
    flow.redirect_uri = urljoin(settings.SITE_BASE_URL,
                                reverse("complete-google-auth"))
    flow.code_verifier = request.session["code_verifier"]
    flow.fetch_token(code=request.GET.get("code"))

    # Store credentials
    credentials = flow.credentials
    with transaction.atomic():
        google_api_auth, _ = GoogleApiAuth.objects.select_for_update(
        ).get_or_create()
        google_api_auth.requesting_user = request.user
        google_api_auth.access_token = credentials.token
        google_api_auth.refresh_token = credentials.refresh_token
        google_api_auth.save()

    return redirect("{}?success=auth".format(reverse("sheets-admin-view")))
    def test_invalid_id_token(self, mock_verify_token):
        mock_verify_token.side_effect = GoogleAuthError("Invalid token")

        with self.app.test_client() as test_client:
            response = test_client.get(
                "/api/experimental/pools",
                headers={"Authorization": "bearer JWT_TOKEN"})

        self.assertEqual(403, response.status_code)
        self.assertEqual("Forbidden", response.data.decode())
Exemplo n.º 4
0
 def client(self):
     """bigquery.Client: Cached method of grabbing a BigQuery client. We do this to avoid credential errors during
     the __init__ lifecycle, but prior to making any API calls.
     """
     if not self._client:
         try:
             credentials = service_account.Credentials.from_service_account_info(
                 self.account_info,
                 scopes=self.scopes,
             )
         except ValueError:
             raise GoogleAuthError(
                 'Provided service account credentials are invalid.')
         self._client = bigquery.Client(credentials=credentials,
                                        project=self.project)
     return self._client
Exemplo n.º 5
0
    def project(self) -> str:
        """Default project."""
        if self._project:
            return self._project

        project_not_found_exception_str = (
            "Unable to find your project. Please provide a project ID by:"
            "\n- Passing a constructor argument"
            "\n- Using aiplatform.init()"
            "\n- Setting a GCP environment variable")

        try:
            _, project_id = google.auth.default()
        except GoogleAuthError:
            raise GoogleAuthError(project_not_found_exception_str)

        if not project_id:
            raise ValueError(project_not_found_exception_str)

        return project_id
Exemplo n.º 6
0
    def project(self) -> str:
        """Default project."""
        if self._project:
            return self._project

        # Project is not set. Trying to get it from the environment.
        # See https://github.com/googleapis/python-aiplatform/issues/852
        # See https://github.com/googleapis/google-auth-library-python/issues/924
        # TODO: Remove when google.auth.default() learns the
        # CLOUD_ML_PROJECT_ID env variable or Vertex AI starts setting GOOGLE_CLOUD_PROJECT env variable.
        project_number = os.environ.get("CLOUD_ML_PROJECT_ID")
        if project_number:
            # Try to convert project number to project ID which is more readable.
            try:
                project_id = resource_manager_utils.get_project_id(
                    project_number=project_number,
                    credentials=self.credentials,
                )
                return project_id
            except Exception:
                logging.getLogger(__name__).warning(
                    "Failed to convert project number to project ID.", exc_info=True
                )
                return project_number

        project_not_found_exception_str = (
            "Unable to find your project. Please provide a project ID by:"
            "\n- Passing a constructor argument"
            "\n- Using aiplatform.init()"
            "\n- Setting a GCP environment variable"
        )

        try:
            _, project_id = google.auth.default()
        except GoogleAuthError:
            raise GoogleAuthError(project_not_found_exception_str)

        if not project_id:
            raise ValueError(project_not_found_exception_str)

        return project_id
Exemplo n.º 7
0
    def test_verify_connection_false(self, mock_list_datasets):
        """It should return false when a GoogleAuthError is raised.
        """
        mock_list_datasets.side_effect = GoogleAuthError('Bad credentials.')

        self.assertFalse(self.engine.verify_connection())