Salesforce IAM

Integrate with Salesforce's services to perform Identity Lifecycle Management operations.

Identity and Access Management · Salesforce

Details

IDSalesforce IAM
ProviderSalesforce
CategoryIdentity and Access Management
From Version6.0.0
Docker Imagedemisto/python3:3.12.13.10116658
Supported ModulesAgentix XSIAM EDR Cortex Cloud Cloud Runtime Security

README

Note: This integration should be used along with our IAM premium pack. For further details, visit our IAM pack documentation.

Integrate with Salesforce’s services to perform Identity Lifecycle Management operations.
For more information, please refer to the Identity Lifecycle Management article.

Configure Salesforce IAM in Cortex

Required Fields in Create User Command

When creating a user in Salesforce there are mandatory fields that need to be set. Some of them are set with default values in the integration parameters:
Default Local Sid Key, Default Email Encoding Key and Default Language Locale Key.
ProfileId and Timezone Sid Key are also required, but are filled using the Salesforce mapper in the following manner:
Duplicate the GenerateProfileId and the GenerateTimeZone automations, edit them according to your needs, and use them as transformers in the User Profile - Salesforce (Outgoing) mapper under the ProfileId and TimeZoneSidKey fields respectively.
This configuration ensures that the user being created is created with the right permissions and settings in Salesforce.

Parameter Description Required
Salesforce url (Eg: https://domain.salesforce.com/)   True
User name   True
Password   True
Consumer Key   False
Consumer Secret   False
Trust any certificate (not secure)   False
Use system proxy settings   False
Allow creating users   False
Allow updating users   False
Allow enabling users   False
Allow disabling users   False
Automatically create user if not found in update and enable commands   False
Incoming Mapper   True
Outgoing Mapper Cortex XSOAR only parameter. False
Default Local Sid Key Used when creating a new user. True
Default Email Encoding Key Used when creating a new user. True
Default Language Locale Key Used when creating a new user. True

Commands

You can execute these commands from the CLI, as part of an automation, or in a playbook.
After you successfully execute a command, a DBot message appears in the War Room with the command details.

iam-create-user


Creates a user with specific settings and permissions in Salesforce, according to the configuration of the Salesforce integration and mapper - as explained in the “Required Fields in Create User Command” section.

Base Command

iam-create-user

Input

Argument Name Description Required
user-profile User Profile indicator details. Required
allow-enable When set to true, after the command execution the status of the user in the 3rd-party integration will be active. Possible values are: true, false. Default is true. Optional

Context Output

Path Type Description
IAM.Vendor.active Boolean If true the employee’s status is active, otherwise false.
IAM.Vendor.brand String Name of the integration.
IAM.Vendor.details string Gives the user information if the API was successful, otherwise error information.
IAM.Vendor.email String The employee’s email address.
IAM.Vendor.errorCode Number HTTP error response code.
IAM.Vendor.errorMessage String Reason why the API failed.
IAM.Vendor.id String The employee’s user ID in the app.
IAM.Vendor.instanceName string Name of the integration instance.
IAM.Vendor.success Boolean If true, the command was executed successfully, otherwise false.
IAM.Vendor.username String The employee’s username in the app.

Command Example

!iam-create-user user-profile=`{"email":"testdemisto2@paloaltonetworks.com", "givenname":"Test","surname":"Demisto”,”timezonesidkey": "Asia/Tokyo",“localesidkey": "en_US",“profileid": “012345678912345”}`

Human Readable Output

brand instanceName success active id email details
Salesforce IAM Salesforce IAM_instance_1 true true edab746f1b142410042611b4bd4bcb23 testdemisto2@paloaltonetworks.com  

iam-update-user


Updates an existing user with the data passed in the user-profile argument.

Base Command

iam-update-user

Input

Argument Name Description Required
user-profile A User Profile indicator. Required
allow-enable When set to true, after the command execution the status of the user in the 3rd-party integration will be active. Possible values are: true, false. Default is true. Optional

Context Output

Path Type Description
IAM.Vendor.active Boolean If true the employee’s status is active, otherwise false.
IAM.Vendor.brand String Name of the integration.
IAM.Vendor.details string Gives the user information if the API was successful, otherwise error information.
IAM.Vendor.email String The employee’s email address.
IAM.Vendor.errorCode Number HTTP error response code.
IAM.Vendor.errorMessage String Reason why the API failed.
IAM.Vendor.id String The employee’s user ID in the app.
IAM.Vendor.instanceName string Name of the integration instance.
IAM.Vendor.success Boolean If true, the command was executed successfully, otherwise false.
IAM.Vendor.username String The employee’s username in the app.

Command Example

!iam-update-user user-profile=`{"email":"testdemisto2@paloaltonetworks.com", "givenname":"Test","surname":"Demisto_updated"}`

Human Readable Output

brand instanceName success active id email details
Salesforce IAM Salesforce IAM_instance_1 true true edab746f1b142410042611b4bd4bcb23 testdemisto2@paloaltonetworks.com  

iam-get-user


Retrieves a single user resource.

Base Command

iam-get-user

Input

Argument Name Description Required
user-profile A User Profile indicator. Required

Context Output

Path Type Description
IAM.Vendor.active Boolean If true the employee’s status is active, otherwise false.
IAM.Vendor.brand String Name of the integration.
IAM.Vendor.details string Gives the user information if the API was successful, otherwise error information.
IAM.Vendor.email String The employee’s email address.
IAM.Vendor.errorCode Number HTTP error response code.
IAM.Vendor.errorMessage String Reason why the API failed.
IAM.Vendor.id String The employee’s user ID in the app.
IAM.Vendor.instanceName string Name of the integration instance.
IAM.Vendor.success Boolean If true, the command was executed successfully, otherwise false.
IAM.Vendor.username String The employee’s username in the app.

Command Example

!iam-get-user user-profile=`{"email":"testdemisto2@paloaltonetworks.com"}`

Human Readable Output

brand instanceName success active id email details
Salesforce IAM Salesforce IAM_instance_1 true true edab746f1b142410042611b4bd4bcb23 testdemisto2@paloaltonetworks.com “AboutMe”: null, “AccountId”: null, “Address”: null, “Alias”: “testdemi”, “BadgeText”: “”, “BannerPhotoUrl”: “/profilephoto/”, “CallCenterId”: null, “City”: null, “CommunityNickname”: “User1”, “CompanyName”: null, “ContactId”: null, “Country”: null, “CreatedById”: “123”, “CreatedDate”: “2020-12-29T09:07:00.000+0000”, “DefaultGroupNotificationFrequency”: “N”, “DelegatedApproverId”: null, “Department”: null, “DigestFrequency”: “D”, “Division”: null, “Email”: “testdemisto2@paloaltonetworks.com”, “EmailEncodingKey”: “ISO-8859-1”, “EmailPreferencesAutoBcc”: true, “EmailPreferencesAutoBccStayInTouch”: false, “EmailPreferencesStayInTouchReminder”: true, “EmployeeNumber”: null, “Extension”: null, “Fax”: null, “FederationIdentifier”: null, “FirstName”: “test”, “ForecastEnabled”: false, “FullPhotoUrl”: “https://profilephoto/”, “GeocodeAccuracy”: null, “Id”: “123”, “IndividualId”: null, “IsActive”: true, “IsExtIndicatorVisible”: false, “IsProfilePhotoActive”: false, “JigsawImportLimitOverride”: null, “LanguageLocaleKey”: “en_US”, “LastLoginDate”: null, “LastModifiedById”: “0054K000001WwcuQAC”, “LastModifiedDate”: “2021-01-03T13:53:24.000+0000”,”LastName”: “test2”, “LastPasswordChangeDate”: null, “LastReferencedDate”: “2021-01-03T14:14:00.000+0000”, “LastViewedDate”: “2021-01-03T14:14:00.000+0000”, “Latitude”: null, “LocaleSidKey”: “en_US”, “Longitude”: null, “ManagerId”: null, “MediumBannerPhotoUrl”: “/profilephoto/”, “MediumPhotoUrl”: “https:/profilephoto/”, “MobilePhone”: null, “Name”: “test”, “OfflinePdaTrialExpirationDate”: null, “OfflineTrialExpirationDate”: null, “OutOfOfficeMessage”: “”, “Phone”: null, “PostalCode”: null, “ProfileId”: “012345678912345”, “ReceivesAdminInfoEmails”: false, “ReceivesInfoEmails”: false, “SenderEmail”: null, “SenderName”: null, “Signature”: null, “SmallBannerPhotoUrl”: “/profilephoto/”, “SmallPhotoUrl”: “profilephoto”, “State”: null, “StayInTouchNote”: null, “StayInTouchSignature”: null, “StayInTouchSubject”: null, “Street”: null, “SystemModstamp”: “2021-01-03T13:53:24.000+0000”, “TimeZoneSidKey”: “Asia/Tokyo”, “Title”: null, “UserPermissionsCallCenterAutoLogin”: false, “UserPermissionsInteractionUser”: false, “UserPermissionsJigsawProspectingUser”: false, “UserPermissionsKnowledgeUser”: false, “UserPermissionsMarketingUser”: false, “UserPermissionsMobileUser”: false, “UserPermissionsOfflineUser”: false, “UserPermissionsSFContentUser”: true, “UserPermissionsSiteforceContributorUser”: false, “UserPermissionsSiteforcePublisherUser”: false, “UserPermissionsSupportUser”: false, “UserPermissionsWorkDotComUserFeature”: false, “UserPreferencesActivityRemindersPopup”: true, “UserPreferencesApexPagesDeveloperMode”: false, “UserPreferencesCacheDiagnostics”: false, “UserPreferencesContentEmailAsAndWhen”: false, “UserPreferencesContentNoEmail”: false, “UserPreferencesCreateLEXAppsWTShown”: false, “UserPreferencesDisCommentAfterLikeEmail”: false, “UserPreferencesDisMentionsCommentEmail”: false, “UserPreferencesDisProfPostCommentEmail”: false, “UserPreferencesDisableAllFeedsEmail”: false, “UserPreferencesDisableBookmarkEmail”: false, “UserPreferencesDisableChangeCommentEmail”: false, “UserPreferencesDisableEndorsementEmail”: false, “UserPreferencesDisableFeedbackEmail”: false, “UserPreferencesDisableFileShareNotificationsForApi”: false, “UserPreferencesDisableFollowersEmail”: false, “UserPreferencesDisableLaterCommentEmail”: false, “UserPreferencesDisableLikeEmail”: true, “UserPreferencesDisableMentionsPostEmail”: false, “UserPreferencesDisableMessageEmail”: false, “UserPreferencesDisableProfilePostEmail”: false, “UserPreferencesDisableSharePostEmail”: false, “UserPreferencesDisableWorkEmail”: false, “UserPreferencesEnableAutoSubForFeeds”: false, “UserPreferencesEventRemindersCheckboxDefault”: true, “UserPreferencesExcludeMailAppAttachments”: false, “UserPreferencesFavoritesShowTopFavorites”: false, “UserPreferencesFavoritesWTShown”: false, “UserPreferencesGlobalNavBarWTShown”: false, “UserPreferencesGlobalNavGridMenuWTShown”: false, “UserPreferencesHasCelebrationBadge”: false, “UserPreferencesHideBiggerPhotoCallout”: false, “UserPreferencesHideCSNDesktopTask”: false, “UserPreferencesHideCSNGetChatterMobileTask”: false, “UserPreferencesHideChatterOnboardingSplash”: false, “UserPreferencesHideEndUserOnboardingAssistantModal”: false, “UserPreferencesHideLightningMigrationModal”: false, “UserPreferencesHideS1BrowserUI”: false, “UserPreferencesHideSecondChatterOnboardingSplash”: false, “UserPreferencesHideSfxWelcomeMat”: true, “UserPreferencesJigsawListUser”: false, “UserPreferencesLightningExperiencePreferred”: true, “UserPreferencesNewLightningReportRunPageEnabled”: false, “UserPreferencesPathAssistantCollapsed”: false, “UserPreferencesPipelineViewHideHelpPopover”: false, “UserPreferencesPreviewCustomTheme”: false, “UserPreferencesPreviewLightning”: false, “UserPreferencesRecordHomeReservedWTShown”: false, “UserPreferencesRecordHomeSectionCollapseWTShown”: false, “UserPreferencesReminderSoundOff”: false, “UserPreferencesShowCityToExternalUsers”: false, “UserPreferencesShowCityToGuestUsers”: false, “UserPreferencesShowCountryToExternalUsers”: false, “UserPreferencesShowCountryToGuestUsers”: false, “UserPreferencesShowEmailToExternalUsers”: false, “UserPreferencesShowEmailToGuestUsers”: false, “UserPreferencesShowFaxToExternalUsers”: false, “UserPreferencesShowFaxToGuestUsers”: false, “UserPreferencesShowManagerToExternalUsers”: false, “UserPreferencesShowManagerToGuestUsers”: false, “UserPreferencesShowMobilePhoneToExternalUsers”: false, “UserPreferencesShowMobilePhoneToGuestUsers”: false, “UserPreferencesShowPostalCodeToExternalUsers”: false, “UserPreferencesShowPostalCodeToGuestUsers”: false, “UserPreferencesShowProfilePicToGuestUsers”: false, “UserPreferencesShowStateToExternalUsers”: false, “UserPreferencesShowStateToGuestUsers”: false, “UserPreferencesShowStreetAddressToExternalUsers”: false, “UserPreferencesShowStreetAddressToGuestUsers”: false, “UserPreferencesShowTitleToExternalUsers”: true, “UserPreferencesShowTitleToGuestUsers”: false, “UserPreferencesShowWorkPhoneToExternalUsers”: false, “UserPreferencesShowWorkPhoneToGuestUsers”: false, “UserPreferencesSortFeedByComment”: true, “UserPreferencesSuppressEventSFXReminders”: false, “UserPreferencesSuppressTaskSFXReminders”: false, “UserPreferencesTaskRemindersCheckboxDefault”: true, “UserPreferencesUserDebugModePref”: false, “UserRoleId”: null, “UserType”: “Standard”, “Username”: “testdemisto2@paloaltonetworks.com”,

iam-disable-user


Disable an active user.

Base Command

iam-disable-user

Input

Argument Name Description Required
user-profile A User Profile indicator. Required

Context Output

Path Type Description
IAM.Vendor.active Boolean If true the employee’s status is active, otherwise false.
IAM.Vendor.brand String Name of the integration.
IAM.Vendor.details string Gives the user information if the API was successful, otherwise error information.
IAM.Vendor.email String The employee’s email address.
IAM.Vendor.errorCode Number HTTP error response code.
IAM.Vendor.errorMessage String Reason why the API failed.
IAM.Vendor.id String The employee’s user ID in the app.
IAM.Vendor.instanceName string Name of the integration instance.
IAM.Vendor.success Boolean If true, the command was executed successfully, otherwise false.
IAM.Vendor.username String The employee’s username in the app.

Command Example

!iam-disable-user user-profile=`{"email":"testdemisto2@paloaltonetworks.com"}`

Human Readable Output

brand instanceName success active id email details
Salesforce IAM Salesforce IAM_instance_1 true false edab746f1b142410042611b4bd4bcb23 testdemisto2@paloaltonetworks.com  

get-mapping-fields


Retrieves a User Profile schema which holds all of the user fields within the application. Used for outgoing-mapping through the Get Schema option.

Base Command

get-mapping-fields

Input

There are no input arguments for this command.

Context Output

There is no context output for this command.

Configuration parameters

  • url — Salesforce url (Eg: https://<domain>.salesforce.com/) (required)
  • credentials — User name (required)
  • consumer_key — Consumer Key
  • consumer_secret — Consumer Secret
  • credentials_consumer — Consumer Key
  • insecure — Trust any certificate (not secure)
  • proxy — Use system proxy settings
  • create_user_enabled — Allow creating users
  • update_user_enabled — Allow updating users
  • enable_user_enabled — Allow enabling users
  • disable_user_enabled — Allow disabling users
  • create_if_not_exists — Automatically create user if not found in update and enable commands
  • mapper_in — Incoming Mapper (required)
  • mapper_out — Outgoing Mapper
  • localesidkey — Default Local Sid Key (required)
  • emailencodingkey — Default Email Encoding Key (required)
  • languagelocalekey — Default Language Locale Key (required)

Commands (5)

  • get-mapping-fields

    Retrieves a User Profile schema which holds all of the user fields within the application. Used for outgoing-mapping through the Get Schema option.

  • iam-create-user

    Creates a user.

  • iam-disable-user

    Disable an active user.

  • iam-get-user

    Retrieves a single user resource.

  • iam-update-user

    Updates an existing user with the data passed in the user-profile argument.

import demistomock as demisto
import urllib3
from CommonServerPython import *

# Disable insecure warnings
urllib3.disable_warnings()


DEFAULT_OUTGOING_MAPPER = "User Profile - Salesforce (Outgoing)"
DEFAULT_INCOMING_MAPPER = "User Profile - Salesforce (Incoming)"
URI_PREFIX = "/services/data/v44.0/"
GENERATE_TOKEN_URL = "https://login.salesforce.com/services/oauth2/token"

# setting defaults for mandatory fields
DEFAULT_FIELDS = ["localesidkey", "emailencodingkey", "languagelocalekey"]


class Client(BaseClient):
    """
    Client will implement the service API, and should not contain any Demisto logic.
    Should only do requests and return data.
    """

    def __init__(
        self,
        demisto_params,
        base_url,
        conn_client_id,
        conn_client_secret,
        conn_username,
        conn_password,
        ok_codes,
        verify=True,
        proxy=False,
    ):
        super().__init__(base_url, verify=verify, proxy=proxy, ok_codes=ok_codes)
        self._conn_client_id = conn_client_id
        self._conn_client_secret = conn_client_secret
        self._conn_username = conn_username
        self._conn_password = conn_password
        self.token = None
        use_ucp_auth = False
        try:
            use_ucp_auth = should_use_ucp_auth()
        except NameError:
            use_ucp_auth = False
        if not use_ucp_auth:
            self.token = self.get_access_token_()
        self.demisto_params = demisto_params

    def get_access_token_(self):
        params = {
            "client_id": self._conn_client_id,
            "client_secret": self._conn_client_secret,
            "username": self._conn_username,
            "password": self._conn_password,
            "grant_type": "password",
        }
        res = self._http_request(method="POST", full_url=GENERATE_TOKEN_URL, params=params)
        token = res.get("access_token")

        headers = {"content-type": "application/json", "Authorization": f"Bearer {token}"}

        self._headers = headers
        return token

    def get_user(self, user_term):
        uri = URI_PREFIX + f"sobjects/User/{user_term}"
        return self._http_request(method="GET", url_suffix=uri)

    def search_user_profile(self, user_term, user_where):
        uri = URI_PREFIX + "parameterizedSearch/"
        params = {
            "q": user_term,
            "sobject": "User",
            "User.where": user_where,
            "User.fields": "Id, IsActive, FirstName, LastName, Email, Username",
        }
        return self._http_request(method="GET", url_suffix=uri, params=params)

    def get_user_id_and_activity_by_mail(self, email):
        # check for errors, what id no user is found?
        user_id = ""
        active = ""
        user_where = f"Email='{email}'"
        res = self.search_user_profile(email, user_where)

        search_records = res.get("searchRecords")
        if len(search_records) > 0:
            for search_record in search_records:
                user_id = search_record.get("Id")
                active = search_record.get("IsActive") == "true"

        return user_id, active

    def create_user(self, data):
        uri = URI_PREFIX + "sobjects/User"
        return self._http_request(method="POST", url_suffix=uri, json_data=data)

    def update_user(self, user_term, data):
        uri = URI_PREFIX + f"sobjects/User/{user_term}"
        params = {"_HttpMethod": "PATCH"}
        return self._http_request(method="POST", url_suffix=uri, params=params, json_data=data, resp_type="text")

    def get_all_users(self):
        uri = URI_PREFIX + "parameterizedSearch/"
        params = {
            "q": "User",
            "sobject": "User",
        }
        return self._http_request(method="GET", url_suffix=uri, params=params)


def handle_exception(e):
    if e.__class__ is DemistoException and hasattr(e, "res") and e.res is not None:
        error_code = e.res.status_code
        error_message = e.res.text
    else:
        error_code = ""
        error_message = str(e)

    demisto.error(traceback.format_exc())
    return error_message, error_code


def test_module(client):
    """
    Returning 'ok' indicates that the integration works like it is supposed to. Connection to the service is successful.

    Args:
        client: SalesforceITAdmin client
        args  : SalesforceITAdmin arguments passed

    Returns:
        'ok' if test passed, anything else will fail the test.
    """
    client.get_user_id_and_activity_by_mail("test@test.com")
    return "ok"


def get_user_command(client, args, mapper_in, mapper_out):
    try:
        user_profile = args.get("user-profile")
        iam_user_profile = IAMUserProfile(
            user_profile=user_profile, mapper=mapper_out, incident_type=IAMUserProfile.UPDATE_INCIDENT_TYPE
        )

        email = iam_user_profile.get_attribute("email")
        user_id, _ = client.get_user_id_and_activity_by_mail(email)

        if not user_id:
            error_code, error_message = IAMErrors.USER_DOES_NOT_EXIST
            iam_user_profile.set_result(
                success=False, error_message=error_message, error_code=error_code, action=IAMActions.GET_USER
            )
        else:
            # unlike query with email, getting a user by id will bring back all the attributes
            github_user = client.get_user(user_id)
            iam_user_profile.update_with_app_data(github_user, mapper_in)

            iam_user_profile.set_result(
                success=True,
                iden=github_user.get("Id"),
                email=github_user.get("Email"),
                username=github_user.get("Username"),
                action=IAMActions.GET_USER,
                details=github_user,
                active=github_user.get("IsActive") == "true",
            )

        return iam_user_profile

    except Exception as e:
        message, code = handle_exception(e)
        iam_user_profile.set_result(success=False, error_message=message, error_code=code, action=IAMActions.GET_USER)
        return iam_user_profile


def create_user_command(client, args, mapper_out, is_create_enabled, is_update_enabled, is_enable_enabled):
    try:
        user_profile = args.get("user-profile")
        iam_user_profile = IAMUserProfile(
            user_profile=user_profile, mapper=mapper_out, incident_type=IAMUserProfile.CREATE_INCIDENT_TYPE
        )

        if not is_create_enabled:
            iam_user_profile.set_result(action=IAMActions.CREATE_USER, skip=True, skip_reason="Command is disabled.")

        else:
            email = iam_user_profile.get_attribute("email")
            user_id, _ = client.get_user_id_and_activity_by_mail(email)

            if user_id:
                create_if_not_exists = False
                iam_user_profile = update_user_command(
                    client, args, mapper_out, is_update_enabled, is_enable_enabled, is_create_enabled, create_if_not_exists
                )

            else:
                salesforce_user = iam_user_profile.map_object(
                    mapper_name=mapper_out, incident_type=IAMUserProfile.CREATE_INCIDENT_TYPE
                )
                # Removing empty elements from salesforce_user
                salesforce_user = {key: value for key, value in salesforce_user.items() if value is not None}
                salesforce_user = check_and_set_manndatory_fields(salesforce_user, client.demisto_params)
                res = client.create_user(salesforce_user)
                iam_user_profile.set_result(
                    success=True,
                    iden=res.get("id"),
                    email=salesforce_user.get("email"),
                    username=salesforce_user.get("userName"),
                    action=IAMActions.CREATE_USER,
                    details=res,
                    active=True,
                )

        return iam_user_profile

    except Exception as e:
        message, code = handle_exception(e)
        iam_user_profile.set_result(success=False, error_message=message, error_code=code, action=IAMActions.CREATE_USER)
        return iam_user_profile


def update_user_command(
    client, args, mapper_out, is_command_enabled, is_enable_enabled, is_create_user_enabled, create_if_not_exists
):
    try:
        iam_user_profile = IAMUserProfile(
            user_profile=args.get("user-profile"), mapper=mapper_out, incident_type=IAMUserProfile.UPDATE_INCIDENT_TYPE
        )
        allow_enable = args.get("allow-enable") == "true"

        if not is_command_enabled:
            iam_user_profile.set_result(action=IAMActions.UPDATE_USER, skip=True, skip_reason="Command is disabled.")
        else:
            email = iam_user_profile.get_attribute("email")
            user_id, active = client.get_user_id_and_activity_by_mail(email)

            if not user_id:
                # user doesn't exists
                if create_if_not_exists:
                    iam_user_profile = create_user_command(client, args, mapper_out, is_create_user_enabled, False, False)
                else:
                    error_code, error_message = IAMErrors.USER_DOES_NOT_EXIST
                    iam_user_profile.set_result(
                        action=IAMActions.UPDATE_USER, error_code=error_code, skip=True, skip_reason=error_message
                    )
            else:
                salesforce_user = iam_user_profile.map_object(
                    mapper_name=mapper_out, incident_type=IAMUserProfile.UPDATE_INCIDENT_TYPE
                )
                salesforce_user = {key: value for key, value in salesforce_user.items() if value is not None}
                if allow_enable and is_enable_enabled:
                    salesforce_user["IsActive"] = True

                res = client.update_user(user_term=user_id, data=salesforce_user)

                iam_user_profile.set_result(success=True, iden=user_id, active=True, action=IAMActions.UPDATE_USER, details=res)

        return iam_user_profile

    except Exception as e:
        message, code = handle_exception(e)
        iam_user_profile.set_result(success=False, error_message=message, error_code=code, action=IAMActions.UPDATE_USER)
        return iam_user_profile


def disable_user_command(client, args, mapper_out, is_command_enabled):
    try:
        user_profile = args.get("user-profile")
        iam_user_profile = IAMUserProfile(
            user_profile=user_profile, mapper=mapper_out, incident_type=IAMUserProfile.DISABLE_INCIDENT_TYPE
        )

        if not is_command_enabled:
            user_profile.set_result(action=IAMActions.DISABLE_USER, skip=True, skip_reason="Command is disabled.")

        else:
            email = iam_user_profile.get_attribute("email")
            user_id, _ = client.get_user_id_and_activity_by_mail(email)

            if not user_id:
                error_code, error_message = IAMErrors.USER_DOES_NOT_EXIST
                iam_user_profile.set_result(
                    action=IAMActions.DISABLE_USER, error_code=error_code, skip=True, skip_reason=error_message
                )
            else:
                salesforce_user = iam_user_profile.map_object(
                    mapper_name=mapper_out, incident_type=IAMUserProfile.UPDATE_INCIDENT_TYPE
                )
                salesforce_user["IsActive"] = False
                salesforce_user = {key: value for key, value in salesforce_user.items() if value is not None}
                res = client.update_user_profile(user_term=user_id, data=salesforce_user)

                iam_user_profile.set_result(success=True, iden=user_id, active=False, action=IAMActions.DISABLE_USER, details=res)

        return iam_user_profile

    except Exception as e:
        message, code = handle_exception(e)
        iam_user_profile.set_result(success=False, error_message=message, error_code=code, action=IAMActions.DISABLE_USER)
        return iam_user_profile


def check_and_set_manndatory_fields(salesforce_user, demisto_params):
    for field in DEFAULT_FIELDS:
        if not salesforce_user.get(field):
            salesforce_user[field] = demisto_params.get(field)

    return salesforce_user


def get_all_user_attributes(client):
    """
    This command gets all users, chooses the first
    then, run a second get command that returns all the users attributes
    """
    user_id = ""
    attributes = []

    all_users = client.get_all_users()
    users_list = all_users.get("searchRecords")
    if isinstance(users_list, list):
        user = users_list[0]
        user_id = user.get("Id")

    if user_id:
        user_data = client.get_user(user_id)
        attributes = list(user_data.keys())
    return attributes


def get_mapping_fields_command(client):
    scheme = get_all_user_attributes(client)
    incident_type_scheme = SchemeTypeMapping(type_name=IAMUserProfile.DEFAULT_INCIDENT_TYPE)

    for field in scheme:
        incident_type_scheme.add_field(field, "Field")

    return GetMappingFieldsResponse([incident_type_scheme])


def main():
    params = demisto.params()
    args = demisto.args()
    command = demisto.command()

    # get the service API url
    base_url = params.get("url")
    # checks for '/' at the end url, if it is not available add it
    if base_url[-1] != "/":
        base_url += "/"

    username = ""
    password = ""
    client_id = ""
    client_secret = ""
    use_ucp_auth = False
    try:
        use_ucp_auth = should_use_ucp_auth()
    except NameError:
        use_ucp_auth = False
    if not use_ucp_auth:
        demisto.debug("Using basic auth")
        username = params.get("credentials").get("identifier")
        password = params.get("credentials").get("password")
        client_id = params.get("credentials_consumer", {}).get("identifier") or params.get("consumer_key")
        client_secret = params.get("credentials_consumer", {}).get("password") or params.get("consumer_secret")
        if not (client_id and client_secret):
            return_error("Consumer Key and Consumer Secret must be provided.")
    else:
        demisto.debug("[UCP][Salesforce_IAM.py] Using UCP auth")

    verify_certificate = not params.get("insecure", False)
    proxy = params.get("proxy", False)

    mapper_in = params.get("mapper-in", DEFAULT_INCOMING_MAPPER)
    mapper_out = params.get("mapper-out", DEFAULT_OUTGOING_MAPPER)

    is_create_enabled = params.get("create_user_enabled")
    is_update_enabled = demisto.params().get("update_user_enabled")
    is_disable_enabled = demisto.params().get("disable_user_enabled")
    is_enable_enabled = demisto.params().get("enable_user_enabled")
    create_if_not_exists = demisto.params().get("create_if_not_exists")

    LOG(f"Command being called is {command}")

    try:
        client = Client(
            demisto_params=params,
            base_url=base_url,
            conn_client_id=client_id,
            conn_client_secret=client_secret,
            conn_username=username,
            conn_password=password,
            ok_codes=(200, 201, 204),
            verify=verify_certificate,
            proxy=proxy,
        )

        if command == "test-module":
            return_results(test_module(client))

        elif command == "iam-get-user":
            user_profile = get_user_command(client, args, mapper_in, mapper_out)
            return_results(user_profile)

        elif command == "iam-create-user":
            user_profile = create_user_command(client, args, mapper_out, is_create_enabled, is_update_enabled, is_enable_enabled)
            return_results(user_profile)

        elif command == "iam-update-user":
            user_profile = update_user_command(
                client, args, mapper_out, is_update_enabled, is_enable_enabled, is_create_enabled, create_if_not_exists
            )
            return_results(user_profile)

        elif command == "iam-disable-user":
            user_profile = disable_user_command(client, args, mapper_out, is_disable_enabled)
            return_results(user_profile)

        elif command == "get-mapping-fields":
            return_results(get_mapping_fields_command(client))

    except Exception as e:
        return_error(f"Failed to execute {command} command. Error: {e}.")


from IAMApiModule import *  # noqa: E402

if __name__ in ("__main__", "__builtin__", "builtins"):
    main()