public/Update-VPASIdentityRole.ps1

<#
.Synopsis
   UPDATE ROLE IN IDENTITY
   CREATED BY: Vadim Melamed, EMAIL: vpasmodule@gmail.com
.DESCRIPTION
   USE THIS FUNCTION TO ADD OR REMOVE USERS FROM AN EXISTING ROLE IN IDENTITY
.LINK
   https://vpasmodule.com/commands/Update-VPASIdentityRole
.PARAMETER token
   HashTable of data containing various pieces of login information (PVWA, LoginToken, HeaderType, etc).
   If -token is not passed, function will use last known hashtable generated by New-VPASToken
.PARAMETER RoleName
   Unique RoleName in Identity to query for target RoleID
.PARAMETER RoleID
   Target RoleID that maps the target Role in Identity
   Supply the RoleID to skip querying for the target Role
.PARAMETER Action
   Specify the action taken on the target Role
   Possible values: AddUser, RemoveUser, AddRole, RemoveRole, EditDescription
.PARAMETER ActionValue
   Value that will be updated on the target Role based on selected action
.PARAMETER InputParameters
   HashTable of values containing the parameters required to make the API call
.EXAMPLE
   $UpdateIdentityRole = Update-VPASIdentityRole -Name {NAME VALUE} -Action {ACTION VALUE} -User {USER Value}
.EXAMPLE
   $UpdateIdentityRole = Update-VPASIdentityRole -RoleID {ROLEID VALUE} -Action {ACTION VALUE} -User {USER Value}
.EXAMPLE
   $InputParameters = @{
        RoleName = "VmanTestRole1"
        Action = "AddUser"|"RemoveUser"|"AddRole"|"RemoveRole"|"EditDescription"
        ActionValue = "Adding a new role description"
   }
   $UpdateIdentityRole = Update-VPASIdentityRole -InputParameters $InputParameters
.EXAMPLE
   $InputParameters = @{
        RoleID = "aec52ec7-1234-abcd-efgh-5678d1fce0ae"
        Action = "AddUser"|"RemoveUser"|"AddRole"|"RemoveRole"|"EditDescription"
        ActionValue = "vman@cyberark.cloud.1234"
   }
   $UpdateIdentityRole = Update-VPASIdentityRole -InputParameters $InputParameters
.OUTPUTS
   $true if successful
   ---
   $false if failed
#>

function Update-VPASIdentityRole{
    [OutputType([bool])]
    [CmdletBinding(DefaultParameterSetName='Set1')]
    Param(

        [Parameter(Mandatory=$true,ParameterSetName='Set1',ValueFromPipelineByPropertyName=$true,HelpMessage="Unique role name of the target role (for example: VpasRole01)")]
        [String]$RoleName,

        [Parameter(Mandatory=$true,ParameterSetName='Set2',ValueFromPipelineByPropertyName=$true,HelpMessage="Unique role ID of the target role (for example: aec52ec7-1234-abcd-efgh-5678d1fce0ae)")]
        [String]$RoleID,

        [Parameter(Mandatory=$true,ParameterSetName='Set1',ValueFromPipelineByPropertyName=$true,HelpMessage="Enter target action (AddUser, RemoveUser, AddRole, RemoveRole, EditDescription)")]
        [Parameter(Mandatory=$true,ParameterSetName='Set2',ValueFromPipelineByPropertyName=$true,HelpMessage="Enter target action (AddUser, RemoveUser, AddRole, RemoveRole, EditDescription)")]
        [ValidateSet('AddUser','RemoveUser','AddRole','RemoveRole','EditDescription')]
        [String]$Action,

        [Parameter(Mandatory=$true,ParameterSetName='Set1',ValueFromPipelineByPropertyName=$true,HelpMessage="Enter value of the target action")]
        [Parameter(Mandatory=$true,ParameterSetName='Set2',ValueFromPipelineByPropertyName=$true,HelpMessage="Enter value of the target action")]
        [String]$ActionValue,

        [Parameter(Mandatory=$true,ParameterSetName='InputParameters',ValueFromPipelineByPropertyName=$true,HelpMessage="Hashtable of parameters required to make API call, refer to get-help -examples for valid inputs")]
        [hashtable]$InputParameters,

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)]
        [hashtable]$token
    )

    Begin{
        $tokenval,$sessionval,$PVWA,$Header,$ISPSS,$IdentityURL,$EnableTextRecorder,$AuditTimeStamp,$NoSSL,$VaultVersion,$HideWarnings,$AuthenticatedAs,$SubDomain,$EnableTroubleshooting = Get-VPASSession -token $token
        $CommandName = $MyInvocation.MyCommand.Name
        $log = Write-VPASTextRecorder -inputval $CommandName -token $token -LogType COMMAND
    }
    Process{
        try{
            if($PSCmdlet.ParameterSetName -eq "InputParameters"){
                $KeyHash = @{
                    set1 = @{
                        AcceptableKeys = @("RoleName","Action","ActionValue")
                        MandatoryKeys = @("RoleName","Action","ActionValue")
                    }
                    set2 = @{
                        AcceptableKeys = @("RoleID","Action","ActionValue")
                        MandatoryKeys = @("RoleID","Action","ActionValue")
                    }
                }
                $CheckSet = Test-VPASHashtableKeysHelper -InputHash $InputParameters -KeyHash $KeyHash

                if(!$CheckSet){
                    $log = Write-VPASTextRecorder -inputval "FAILED TO FIND TARGET PARAMETER SET" -token $token -LogType MISC
                    Write-Verbose "FAILED TO FIND TARGET PARAMETER SET"
                    Write-VPASOutput -str "FAILED TO FIND TARGET PARAMETER SET...VIEW EXAMPLES BELOW:" -type E
                    $examples = Write-VPASExampleHelper -CommandName $CommandName
                    return $false
                }
                else{
                    foreach($key in $InputParameters.Keys){
                        Set-Variable -Name $key -Value $InputParameters.$key
                    }
                }
            }
        }catch{
            $log = Write-VPASTextRecorder -inputval $_ -token $token -LogType ERROR
            $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
            Write-Verbose "FAILED TO UPDATE ROLE"
            Write-VPASOutput -str $_ -type E
            return $false
        }

        try{

            if(!$IdentityURL){
                $log = Write-VPASTextRecorder -inputval "LOGIN TOKEN WAS NOT GENERATED THROUGH IDENTITY" -token $token -LogType MISC
                $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
                Write-VPASOutput -str "LOGIN TOKEN WAS NOT GENERATED THROUGH IDENTITY, TERMINATING API CALL" -type E
                return $false
            }

            if([String]::IsNullOrEmpty($RoleID)){
                Write-Verbose "NO ROLE ID PASSED"
                Write-Verbose "INVOKING HELPER FUNCTION TO RETRIEVE ROLE ID"

                $RoleID = Get-VPASRoleIDIdentityHelper -token $token -RoleName $RoleName

                if($RoleID -eq -1){
                    $log = Write-VPASTextRecorder -inputval "MULTIPLE ROLE ENTRIES WERE RETURNED, ADD MORE TO NAME TO NARROW RESULTS" -token $token -LogType MISC
                    $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
                    Write-VPASOutput -str "MULTIPLE ROLE ENTRIES WERE RETURNED, ADD MORE TO NAME TO NARROW RESULTS" -type E
                    Write-VPASOutput -str "RETURNING FALSE" -type E
                    return $false
                }
                elseif($RoleID -eq -2){
                    $log = Write-VPASTextRecorder -inputval "NO ROLE ENTRIES WERE RETURNED" -token $token -LogType MISC
                    $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
                    Write-VPASOutput -str "NO ROLE ENTRIES WERE RETURNED" -type E
                    Write-VPASOutput -str "RETURNING FALSE" -type E
                    return $false
                }
                else{
                    Write-Verbose "FOUND UNIQUE ROLE ID"
                }
            }
            else{
                Write-Verbose "ROLE ID PASSED, SKIPPING HELPER FUNCTION"
            }


            Write-Verbose "CONSTRUCTING PARAMS"
            $params = @{
                Name = $RoleID
            }
            Write-Verbose "ADDING ROLE ID: $RoleID TO PARAMS"

            if($Action -eq "AddUser"){
                $UserParams = @{
                    Add = @($ActionValue)
                }

                $params += @{
                    Users = $UserParams
                }
            }
            elseif($Action -eq "RemoveUser"){
                $UserParams = @{
                    Delete = @($ActionValue)
                }

                $params += @{
                    Users = $UserParams
                }
            }
            elseif($Action -eq "AddRole"){
                $targetRoleID = ""
                Write-Verbose "INVOKING HELPER FUNCTION TO RETRIEVE ROLE ID"

                $RoleID = Get-VPASRoleIDIdentityHelper -token $token -RoleName $ActionValue

                if($RoleID -eq -1){
                    $log = Write-VPASTextRecorder -inputval "MULTIPLE ROLE ENTRIES WERE RETURNED, ADD MORE TO NAME TO NARROW RESULTS" -token $token -LogType MISC
                    $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
                    Write-VPASOutput -str "MULTIPLE ROLE ENTRIES WERE RETURNED, ADD MORE TO NAME TO NARROW RESULTS" -type E
                    Write-VPASOutput -str "RETURNING FALSE" -type E
                    return $false
                }
                elseif($RoleID -eq -2){
                    $log = Write-VPASTextRecorder -inputval "NO ROLE ENTRIES WERE RETURNED" -token $token -LogType MISC
                    $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
                    Write-VPASOutput -str "NO ROLE ENTRIES WERE RETURNED" -type E
                    Write-VPASOutput -str "RETURNING FALSE" -type E
                    return $false
                }
                else{
                    Write-Verbose "FOUND UNIQUE ROLE ID"
                    $targetRoleID = $RoleID
                }

                $RoleParams = @{
                    Add = @($targetRoleID)
                }

                $params += @{
                    Roles = $RoleParams
                }
            }
            elseif($Action -eq "RemoveRole"){
                $targetRoleID = ""
                Write-Verbose "INVOKING HELPER FUNCTION TO RETRIEVE ROLE ID"

                $RoleID = Get-VPASRoleIDIdentityHelper -token $token -RoleName $ActionValue

                if($RoleID -eq -1){
                    $log = Write-VPASTextRecorder -inputval "MULTIPLE ROLE ENTRIES WERE RETURNED, ADD MORE TO NAME TO NARROW RESULTS" -token $token -LogType MISC
                    $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
                    Write-VPASOutput -str "MULTIPLE ROLE ENTRIES WERE RETURNED, ADD MORE TO NAME TO NARROW RESULTS" -type E
                    Write-VPASOutput -str "RETURNING FALSE" -type E
                    return $false
                }
                elseif($RoleID -eq -2){
                    $log = Write-VPASTextRecorder -inputval "NO ROLE ENTRIES WERE RETURNED" -token $token -LogType MISC
                    $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
                    Write-VPASOutput -str "NO ROLE ENTRIES WERE RETURNED" -type E
                    Write-VPASOutput -str "RETURNING FALSE" -type E
                    return $false
                }
                else{
                    Write-Verbose "FOUND UNIQUE ROLE ID"
                    $targetRoleID = $RoleID
                }

                $RoleParams = @{
                    Delete = @($targetRoleID)
                }

                $params += @{
                    Roles = $RoleParams
                }
            }
            elseif($Action -eq "EditDescription"){
                $params += @{
                    Description = $ActionValue
                }
            }

            $log = Write-VPASTextRecorder -inputval $params -token $token -LogType PARAMS
            $params = $params | ConvertTo-Json

            if($NoSSL){
                Write-Verbose "NO SSL ENABLED, USING HTTP INSTEAD OF HTTPS"
                $uri = "http://$IdentityURL/roles/UpdateRole/"
            }
            else{
                Write-Verbose "SSL ENABLED BY DEFAULT, USING HTTPS"
                $uri = "https://$IdentityURL/roles/UpdateRole/"
            }
            $log = Write-VPASTextRecorder -inputval $uri -token $token -LogType URI
            $log = Write-VPASTextRecorder -inputval "POST" -token $token -LogType METHOD

            if($sessionval){
                $response = Invoke-RestMethod -Headers @{"Authorization"=$Header} -Uri $uri -Method POST -Body $params -ContentType "application/json" -WebSession $sessionval
            }
            else{
                $response = Invoke-RestMethod -Headers @{"Authorization"=$Header} -Uri $uri -Method POST -Body $params -ContentType "application/json"
            }

            if($response.success){
                $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: TRUE" -token $token -LogType MISC
                Write-Verbose "PARSING DATA FROM CYBERARK"
                Write-Verbose "RETURNING TRUE"
                return $true
            }
            else{
                $errstr = $response.Message
                $log = Write-VPASTextRecorder -inputval $errstr -token $token -LogType ERROR
                $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
                Write-Verbose "FAILED TO UPDATE ROLE IN IDENTITY"
                Write-VPASOutput -str "FAILED TO UPDATE ROLE IN IDENTITY: $errstr" -type E
                return $false
            }
        }catch{
            $log = Write-VPASTextRecorder -inputval $_ -token $token -LogType ERROR
            $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
            Write-Verbose "FAILED TO UPDATE ROLE FROM IDENTITY"
            Write-VPASOutput -str $_ -type E
            return $false
        }
    }
    End{
        $log = Write-VPASTextRecorder -inputval $CommandName -token $token -LogType DIVIDER
    }
}