public/Add-VPASAccountRequest.ps1

<#
.Synopsis
   CREATE A NEW ACCOUNT REQUEST
   CREATED BY: Vadim Melamed, EMAIL: vmelamed5@gmail.com
.DESCRIPTION
   USE THIS FUNCTION TO CREATE A NEW ACCOUNT REQUEST THAT UTILIZES DUAL CONTROL
.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 safe
   Safe name that will be used to query for the target account if no AcctID is passed
.PARAMETER username
   Username that will be used to query for the target account if no AcctID is passed
.PARAMETER platform
   PlatformID that will be used to query for the target account if no AcctID is passed
.PARAMETER address
   Address that will be used to query for the target account if no AcctID is passed
.PARAMETER AcctID
   Unique ID that maps to a single account, passing this variable will skip any query functions
.PARAMETER Reason
   Purpose for opening this account request
.PARAMETER MultipleAccess
   MultipleAccess type request gives the ability to use the account multiple times within a requested time frame
.PARAMETER FromDateTime
   Start of the date range for the account request
   Value should follow this format: MM/dd/yyyy HH:mm:ss
.PARAMETER ToDateTime
   End of the date range for the account request
   Value should follow this format: MM/dd/yyyy HH:mm:ss
.PARAMETER UseConnect
   Gives this account request the ability to connect via PSM if approved
.PARAMETER ConnectionComponent
   Specify the connection component that will be used if UseConnect is enabled
   Example value: PSM-RDP, PSM-SSH, PSM-vSphere
.PARAMETER Hostname
   Specify the hostname that will be connected to if the account request is for a domain account
   This value will populate the PSMRemoteMachine parameter
.EXAMPLE
   $AddAccountRequestJSON = Add-VPASAccountRequest -AcctID {ACCTID VALUE} -Reason {REASON VALUE} -MultipleAccess -FromDateTime "03/12/2024 9:00:00" -ToDateTime "03/12/2024 13:00:00" -UseConnect -ConnectionComponent PSM-RDP
.EXAMPLE
  $AddAccountRequestJSON = Add-VPASAccountRequest -AcctID {ACCTID VALUE} -Reason {REASON VALUE}
.OUTPUTS
   If successful:
   {
        "RequestID": "VPASRequestSafe_19",
        "SafeName": "VPASRequestSafe",
        "RequestorUserName": "vadim@vman.com",
        "RequestorReason": "(ConnectionClient=PSM-RDP) Testing Account Request",
        "UserReason": "Testing Account Request",
        "CreationDate": 1723776151,
        "Operation": "Connect to VPASDualControl-DomainAdmin011-vman.com",
        "ExpirationDate": 1726368151,
        "OperationType": 4,
        "AccessType": "ManyTimes",
        "ConfirmationsLeft": 1,
        "AccessFrom": 1723813200,
        "AccessTo": 1723827600,
        "Status": 1,
        "StatusTitle": "Waiting: 1 more user(s) must confirm the request",
        "InvalidRequestReason": 0,
        "CurrentConfirmationLevel": 1,
        "RequiredConfirmersCountLevel2": 1,
        "TicketingSystemProperties": {
                                          "Name": null,
                                          "Number": null,
                                          "Status": null
                                      },
        "AdditionalInfo": {
 
                           },
        "AccountDetails": {
                               "AccountID": "120_3",
                               "Properties": {
                                                  "Address": "vman.com",
                                                  "Safe": "VPASRequestSafe",
                                                  "Folder": "Root",
                                                  "Name": "Operating System-VPASDualControl-vman.com-DomainAdmin01",
                                                  "PolicyID": "VPASDualControl",
                                                  "PlatformName": "VPASDualControl",
                                                  "DeviceType": "Operating System",
                                                  "LastModifiedDate": "1715222718000",
                                                  "LastModifiedBy": "vadim@vman.pam",
                                                  "LastUsedDate": "1715222731000",
                                                  "LastUsedBy": "vadim@vman.com",
                                                  "UserName": "DomainAdmin011",
                                                  "LockedBy": "",
                                                  "CPMDisabled": "",
                                                  "CPMStatus": "NoAction",
                                                  "ManagedByCPM": "True",
                                                  "DeletedBy": "",
                                                  "DeletionDate": "0",
                                                  "ImmediateCPMTask": "NoTask",
                                                  "LastCPMTask": "NoTask",
                                                  "CreationDate": "1715222718",
                                                  "IsSSHKey": "False",
                                                  "IsIrregularPlatform": "False",
                                                  "CreationMethod": "PVWA"
                                              }
                           },
        "Confirmers": [
                           {
                               "Type": 1,
                               "ID": 41,
                               "Name": "vadim@vman.com",
                               "Action": 2,
                               "Reason": "",
                               "ActionDate": 0,
                               "AdditionalDetails": "@{fullname=Vadim Melamed; email=vadim@vman.com; phone=1234567890}",
                               "Members": null
                           }
                       ]
   }
   ---
   $false if failed
#>

function Add-VPASAccountRequest{
    [OutputType([bool])]
    [CmdletBinding()]
    Param(

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=0)]
        [String]$safe,

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=1)]
        [String]$platform,

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=2)]
        [String]$username,

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=3)]
        [String]$address,

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=4)]
        [String]$AcctID,

        [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,HelpMessage="Enter reason for requesting the account (for example: I need this account to access the database to view the transaction logs)",Position=5)]
        [String]$Reason,

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=6)]
        [Switch]$MultipleAccess,

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=7)]
        [String]$FromDateTime,

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=8)]
        [String]$ToDateTime,

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=9)]
        [switch]$UseConnect,

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=10)]
        [String]$ConnectionComponent,

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=11)]
        [String]$Hostname,

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

    Begin{
        $tokenval,$sessionval,$PVWA,$Header,$ISPSS,$IdentityURL,$EnableTextRecorder,$AuditTimeStamp,$NoSSL,$VaultVersion,$HideWarnings,$AuthenticatedAs,$SubDomain = Get-VPASSession -token $token
        $CommandName = $MyInvocation.MyCommand.Name
        $log = Write-VPASTextRecorder -inputval $CommandName -token $token -LogType COMMAND
    }
    Process{
        Write-Verbose "SUCCESSFULLY PARSED PVWA VALUE"
        Write-Verbose "SUCCESSFULLY PARSED TOKEN VALUE"

        try{

            $params = @{}

            if([String]::IsNullOrEmpty($AcctID)){
                Write-Verbose "NO ACCTID SUPPLIED, INVOKING ACCTID HELPER"
                $AcctID = Get-VPASAccountIDHelper -token $token -safe $safe -platform $platform -username $username -address $address
                write-verbose "ADDING ACCTID: $AcctID TO API PARAMETERS"
                $params += @{accountId = "$AcctID"}
            }
            else{
                Write-Verbose "ACCTID SUPPLIED, SKIPPING ACCOUNTID HELPER"
                Write-Verbose "ADDING ACCTID: $AcctID TO API PARAMETERS"
                $params += @{accountId = "$AcctID"}
            }

            if(![String]::IsNullOrEmpty($FromDateTime) -and ![String]::IsNullOrEmpty($ToDateTime)){
                $FromDateTimeObj = $FromDateTime -as [DateTime]
                if(!$FromDateTimeObj){
                    $log = Write-VPASTextRecorder -inputval "INVALID FromTime, SHOULD BE - MM/dd/yyyy HH:mm:ss" -token $token -LogType MISC
                    $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
                    write-verbose "INVALID FromTime, SHOULD BE - MM/dd/yyyy HH:mm:ss...RETURNING FALSE"
                    Write-VPASOutput -str "INVALID FromTime, SHOULD BE - MM/dd/yyyy HH:mm:ss...RETURNING FALSE" -type E
                    return $false
                }
                else{
                    $FromTimeEpoch = [int][double]::Parse((Get-Date ($FromDateTimeObj).touniversaltime() -UFormat %s))
                    $params += @{FromDate = $FromTimeEpoch}
                }

                $ToDateTimeObj = $ToDateTime -as [DateTime]
                if(!$ToDateTimeObj){
                    $log = Write-VPASTextRecorder -inputval "INVALID ToTime, SHOULD BE - MM/dd/yyyy HH:mm:ss" -token $token -LogType MISC
                    $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
                    write-verbose "INVALID ToTime, SHOULD BE - MM/dd/yyyy HH:mm:ss...RETURNING FALSE"
                    Write-VPASOutput -str "INVALID ToTime, SHOULD BE - MM/dd/yyyy HH:mm:ss...RETURNING FALSE" -type E
                    return $false
                }
                else{
                    $ToTimeEpoch = [int][double]::Parse((Get-Date ($ToDateTimeObj).touniversaltime() -UFormat %s))
                    $params += @{ToDate = $ToTimeEpoch}
                }
            }

            $connectionparams = @{}
            $params += @{
                reason = "$Reason"
            }

            if($MultipleAccess){
                $params += @{MultipleAccessRequired = $true}
            }
            if($UseConnect){
                $params += @{UseConnect = $true}
            }
            if(![String]::IsNullOrEmpty($ConnectionComponent)){
                $params += @{ConnectionComponent = $ConnectionComponent}
            }
            if(![String]::IsNullOrEmpty($Hostname)){
                $connectionparams += @{
                    PSMRemoteMachine = @{
                        value = $Hostname
                    }
                }
            }
            $params += @{
                ConnectionParams = $connectionparams
            }

            $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://$PVWA/PasswordVault/API/MyRequests"
            }
            else{
                Write-Verbose "SSL ENABLED BY DEFAULT, USING HTTPS"
                $uri = "https://$PVWA/PasswordVault/API/MyRequests"
            }

            $log = Write-VPASTextRecorder -inputval $uri -token $token -LogType URI
            $log = Write-VPASTextRecorder -inputval "POST" -token $token -LogType METHOD
            write-verbose "MAKING API CALL TO CYBERARK"

            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"
            }
            $outputlog = $response
            $log = Write-VPASTextRecorder -inputval $outputlog -token $token -LogType RETURN
            Write-Verbose "RETURNING REQUEST DETAILS"
            return $response
        }catch{
            $log = Write-VPASTextRecorder -inputval $_ -token $token -LogType ERROR
            $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
            Write-Verbose "UNABLE TO CREATE AN APPROVAL REQUEST"
            Write-VPASOutput -str $_ -type E
            return $false
        }
    }
    End{
        $log = Write-VPASTextRecorder -inputval $CommandName -token $token -LogType DIVIDER
    }
}