def refresh_oauth_token(self, keychain, connected_app=None):
        """Get a fresh access token and store it in the org config.

        If the SFDX_CLIENT_ID and SFDX_HUB_KEY environment variables are set,
        this is done using the Oauth2 JWT flow.

        Otherwise it is done using the Oauth2 Refresh Token flow using the connected app
        configured in the keychain's connected_app service.

        Also refreshes user and org info that is cached in the org config.
        """
        # invalidate memoized simple-salesforce client with old token
        self._client = None

        if not SKIP_REFRESH:
            SFDX_CLIENT_ID = os.environ.get("SFDX_CLIENT_ID")
            SFDX_HUB_KEY = os.environ.get("SFDX_HUB_KEY")
            if SFDX_CLIENT_ID and SFDX_HUB_KEY:
                info = jwt_session(SFDX_CLIENT_ID, SFDX_HUB_KEY, self.username,
                                   self.instance_url)
            else:
                info = self._refresh_token(keychain, connected_app)
            if info != self.config:
                self.config.update(info)
        self._load_userinfo()
        self._load_orginfo()
Example #2
0
    def delete_org(self, org_config=None):
        if org_config is None:
            org_config = self.get_org_config()

        try:
            # connect to SFDX Hub
            sfjwt = jwt_session(
                settings.SFDX_CLIENT_ID,
                settings.SFDX_HUB_KEY,
                settings.SFDX_HUB_USERNAME,
            )
            sf = sf_session(sfjwt)
            # query ActiveScratchOrg via OrgId
            asos = sf.query(
                f"SELECT ID FROM ActiveScratchOrg WHERE ScratchOrg='{self.sf_org_id}'"
            )
            if asos["totalSize"] > 0:
                aso = asos["records"][0]["Id"]
                # delete ActiveScratchOrg
                sf.ActiveScratchOrg.delete(aso)
            else:
                self.delete_error = "Org did not exist when deleted."
        except SalesforceError as e:
            self.delete_error = str(e)
            self.deleted = False
            self.save()
            return

        self.time_deleted = timezone.now()
        self.deleted = True
        self.save()
Example #3
0
 def get_jwt_based_session(self):
     config = json.loads(self.json)
     return jwt_session(
         settings.SFDX_CLIENT_ID,
         settings.SFDX_HUB_KEY,
         self.username,
         url=config.get("instance_url") or settings.SF_SANDBOX_LOGIN_URL,
         auth_url=settings.SF_SANDBOX_LOGIN_URL,
     )
Example #4
0
def is_org_good(org):
    config = org.config
    org_name = org.task.org_config_name
    try:
        org_config = OrgConfig(config, org_name)
        org_config.refresh_oauth_token = Mock()
        info = jwt_session(SF_CLIENT_ID, SF_CLIENT_KEY, org_config.username,
                           org_config.instance_url)
        return "access_token" in info
    except HTTPError:
        return False
Example #5
0
 def refresh_oauth_token(self, keychain, connected_app=None):
     SFDX_CLIENT_ID = os.environ.get("SFDX_CLIENT_ID")
     SFDX_HUB_KEY = os.environ.get("SFDX_HUB_KEY")
     if SFDX_CLIENT_ID and SFDX_HUB_KEY:
         info = jwt_session(SFDX_CLIENT_ID, SFDX_HUB_KEY, self.username,
                            self.instance_url)
     else:
         info = self._refresh_token(keychain, connected_app)
     if info != self.config:
         self.config.update(info)
     self._load_userinfo()
     self._load_orginfo()
Example #6
0
 def get_refreshed_org_config(self):
     org_config = OrgConfig(self.config, "dev")
     info = jwt_session(
         settings.SF_CLIENT_ID,
         settings.SF_CLIENT_KEY,
         org_config.username,
         org_config.instance_url,
     )
     org_config.config.update(info)
     org_config._load_userinfo()
     org_config._load_orginfo()
     return org_config
Example #7
0
def scratch_org_limits():
    cached = cache.get(ACTIVESCRATCHORGLIMITS_KEY, None)
    if cached:
        return cached

    sfjwt = jwt_session(settings.SFDX_CLIENT_ID, settings.SFDX_HUB_KEY,
                        settings.SFDX_HUB_USERNAME)
    limits = sf_session(sfjwt).limits()["ActiveScratchOrgs"]
    value = ActiveScratchOrgLimits(remaining=limits["Remaining"],
                                   max=limits["Max"])
    # store it for 65 seconds, enough til the next tick. we may want to tune this
    cache.set(ACTIVESCRATCHORGLIMITS_KEY, value, 65)
    return value
Example #8
0
def get_devhub_api(*, devhub_username):
    """
    Get an access token (session) for the specified dev hub username.
    This only works if the user has already authorized the connected app
    via an interactive login flow, such as the django-allauth login.
    """
    jwt = jwt_session(SF_CLIENT_ID, SF_CLIENT_KEY, devhub_username)
    return SimpleSalesforce(
        instance_url=jwt["instance_url"],
        session_id=jwt["access_token"],
        client_id="Metecho",
        version="47.0",
    )
Example #9
0
 def refresh_oauth_token(self, keychain, connected_app=None):
     SFDX_CLIENT_ID = os.environ.get("SFDX_CLIENT_ID")
     SFDX_HUB_KEY = os.environ.get("SFDX_HUB_KEY")
     if SFDX_CLIENT_ID and SFDX_HUB_KEY:
         login_url = (
             "https://test.salesforce.com"
             if self.is_sandbox
             else "https://login.salesforce.com"
         )
         info = jwt_session(SFDX_CLIENT_ID, SFDX_HUB_KEY, self.username, login_url)
     else:
         info = self._refresh_token(keychain, connected_app)
     if info != self.config:
         self.config.update(info)
     self._load_userinfo()
     self._load_orginfo()
Example #10
0
def _get_devhub_api(scratch_org=None):
    """Get an access token.

    Get an access token (session) using the global dev hub username.
    """
    if not settings.DEVHUB_USERNAME:
        raise ImproperlyConfigured(
            "You must set the DEVHUB_USERNAME to connect to a Salesforce organization."
        )
    try:
        jwt = jwt_session(SF_CLIENT_ID, SF_CLIENT_KEY, settings.DEVHUB_USERNAME)
        return SimpleSalesforce(
            instance_url=jwt["instance_url"],
            session_id=jwt["access_token"],
            client_id="MetaDeploy",
            version="49.0",
        )
    except HTTPError as err:
        _handle_sf_error(err, scratch_org=scratch_org)
Example #11
0
def refresh_access_token(*, config, org_name, scratch_org,
                         originating_user_id):
    """
    Construct a new OrgConfig because ScratchOrgConfig tries to use sfdx
    which we don't want now -- this is a total hack which I'll try to
    smooth over with some improvements in CumulusCI
    """
    try:
        org_config = OrgConfig(config, org_name)
        org_config.refresh_oauth_token = Mock()
        info = jwt_session(SF_CLIENT_ID, SF_CLIENT_KEY, org_config.username,
                           org_config.instance_url)
        org_config.config["access_token"] = info["access_token"]
        return org_config
    except HTTPError as err:
        if get_current_job():
            job_id = get_current_job().id
            # This error is user-facing, and so for makemessages to
            # pick it up correctly, we need it to be a single,
            # unbroken, string literal (even though adjacent string
            # literals should be parsed by the AST into a single
            # string literal and picked up by makemessages, but
            # that's a gripe for another day). We have relatively
            # few errors that propagate directly from the backend
            # like this, but when we do, this is the pattern we
            # should use.
            #
            # This is also why we repeat the first sentence.
            error_msg = _(
                f"Are you certain that the org still exists? If you need support, your job ID is {job_id}."  # noqa: B950
            )
        else:
            error_msg = _(
                f"Are you certain that the org still exists? {err.args[0]}")

        err = err.__class__(
            error_msg,
            *err.args[1:],
        )
        scratch_org.remove_scratch_org(err,
                                       originating_user_id=originating_user_id)
        raise err