Update-GreenRadiusTemporaryToken.ps1

function Update-GreenRadiusTemporaryToken {
    <#
        .SYNOPSIS
            Updates a temp token assigned to a user.
 
        .DESCRIPTION
            Utilizes the GreenRADIUS API to update a temp token assigned to a user. Relies on the
            user already having such a token assigned.
 
            This function always changes/resets the count of remaining uses on the token. The
            default value of -MaximumUses is 5.
 
        .OUTPUTS
            $true if successful, $false if not. If not successful, an explanation of the failure
            will also be passed to Write-Error.
 
        .PARAMETER Username
            The username of the user who has the token assigned to them. This is in username@domain
            format. This does NOT necessarily use the UPN of the user, but rather the actual domain
            name as configured in GreenRADIUS, independent of the individual user.
 
        .PARAMETER Token
            The text of the token to assign, if changing the actual token/password string. This must
            adhere to the length standard configured within GreenRADIUS, and the last 6 characters
            cannot be numeric, for some reason.
 
            If set to the exact string "NEW", a new password will be generated for you. This is
            preferred. In this version of this function, the password will be two alphanumeric
            characters, followed by 6 numeric characters.
 
            If this parameter is not specified, then the old token password will remain unchanged.
 
        .PARAMETER ExpireOn
            The date, in plain English, through which the token should be valid. The token will be
            valid until 11:59:59 PM on the date specified, in UTC time. This is a limitation of
            GreenRADIUS; temporary tokens must ALWAYS expire at 23:59:59 UTC.
 
            Format examples are:
                February 5, 2025 (it doesn't like "3rd" so just do the number)
                Feb 5, 2026
                2026-02-05
                03/04/2026
 
            For timezones "before" UTC, such as in the Americas, this means that tokens will expire
            on the previous day, and for timezones "after" UTC, such as Eastern Europe, they will
            expire some time during the specified day. For example, in Pacific Time, if a token is
            set to expire on February 3, 2026, then it will actually expire at around 4 or 5 PM on
            February 2nd instead, a full 7 or 8 hours before what is specfied.
 
            If left blank, then the expiry of the existing token will not be changed.
 
        .PARAMETER MaximumUses
            The number of times that the user is allowed to use the token going forward. Defaults to
            5.
 
        .PARAMETER RawRequest
            Variable name, without the dollar sign, in which to store the raw request which was
            created and sent to the API. This does not need to be a pre-existing variable. Mostly
            used for debugging this function. This uses the Global scope.
 
        .PARAMETER RawResponse
            Variable name, without the dollar sign, in which to store the raw response from the API.
            This does not need to be a pre-existing variable. Mostly used for debugging this
            function. This uses the Global scope.
 
        .NOTES
            Version 2026.02.11.1451
    #>


    <# LICENSE
 
    Copyright (c) 2026 Derek Howard and the City of Eureka, California
 
    Permission is hereby granted, free of charge, to any person obtaining a copy of this software
    and associated documentation files (the "Software"), to deal in the Software without
    restriction, including without limitation the rights to use, copy, modify, merge, publish,
    and/or distribute copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:
 
    The above copyright notice and this permission notice shall be included in all copies or
    substantial portions of the Software, and the original author shall be credited as having
    created the original work.
 
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
    BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
    DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    #>


    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$true)]
        [string]$Username,

        [string]$Token,

        [string]$ExpireOn,

        [int]$MaximumUses=5,

        [string]$RawRequest,

        [string]$RawResponse
    )

    if (-not $global:GreenRadiusApiSession) {
        Write-Error "You forgot to run Connect-GreenRadiusApi!"
        return $false;
    }

    $tokenInfo = @{
        username = $Username
        count_of_max_auth = $MaximumUses
    }

    if ($Token) {
        if ($Token -eq "NEW") {
            $alphaChars = 'abcdefghkmnprstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ@#$%&*=+?'
            $alphanumericChars = $alphaChars + '2345689'
            $tokenPart1 = -join (1..2 | ForEach-Object { $alphanumericChars[(Get-Random -Maximum $alphanumericChars.Length)] })
            $tokenPart2 = -join (1..6 | ForEach-Object { $alphaChars[(Get-Random -Maximum $alphaChars.Length)] })
            $Token = $tokenPart1 + $tokenPart2
        }
        $tokenInfo.temporary_token = $Token
    }

    if ($ExpireOn) {
        $endOfDay = $(Get-Date $ExpireOn -AsUTC).Date.AddDays(1).AddSeconds(-1)
        $expiryTimestamp = ([DateTimeOffset]$endOfDay).ToUnixTimeSeconds()
        $tokenInfo.expiry_date = $expiryTimestamp
    }

    $Body = @{
        temporary_tokens = @($tokenInfo)
    }


    $Params = @{
        Uri                  = "https://$($global:GreenRadiusApiSession.HostName)/gras-api/v2/mgmt/temporary-tokens"
        Method               = "Put"
        Credential           = $global:GreenRadiusApiSession.Credential
        Body                 = ($Body | ConvertTo-Json -Depth 5)
        ContentType          = "application/json"
    }

    if ($RawRequest) {
        Set-Variable -Name $RawRequest -Value $Body -Scope Global -Force
    }

    $apiResult = Invoke-RestMethod @Params
    if ($apiResult.GetType().Name -eq "String") {
        #This only seems necessary for the /tokenassignment api (used in Get-GreenRadiusTokenAssignments)
        #and even then only when no search parameters are specified, but here we go anyway
        $apiResult = $apiResult | ConvertFrom-Json -AsHashTable
    }
    if ($RawResponse) {
        Set-Variable -Name $RawResponse -Value $apiResult -Scope Global -Force
    }

    if ($apiResult.records_updated.Count -gt 0) {
        if ($Token) {
            $tokenText = " $newToken"
        }
        if ($ExpireOn) {
            $expiryDateText = " Expires on $(([System.DateTimeOffset]::FromUnixTimeSeconds($expiryTimestamp)).LocalDateTime)."
        }

        Write-Host "Updated temporary token$tokenText for user $Username. Valid for $MaximumUses more uses.$expiryDateText"
        return $true
    } else {
        if ($apiResult.records_skipped.Count -gt 0) {
            Write-Error $apiResult.records_skipped.records.output.description
        } elseif ($apiResult.records_invalid.Count -gt 0) {
            Write-Error $apiResult.records_invalid.records.output.description
        }
        return $false
    }
}