Assign-GreenRadiusTemporaryToken.ps1

function Assign-GreenRadiusTemporaryToken {
    <#
        .SYNOPSIS
            Creates a temp token to for a user.
 
        .DESCRIPTION
            Utilizes the GreenRADIUS API to associate a temp token to a user. Relies on the user not
            already having such a token assigned.
 
        .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 to which we are assigning the token. 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. This must adhere to the length standard configured
            within GreenRADIUS, and the last 6 characters cannot be numeric, for some reason.
 
            If left blank, a 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.
 
        .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 will be set to the very next midnight in UTC time.
 
        .PARAMETER MaximumUses
            The number of times that the user is allowed to use the token. 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.
 
        .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.
 
        .NOTES
            Version 2026.02.09.1446
    #>


    <# 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;
    }

    if ($Token) {
        $newToken = $Token
    } else {
        $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)] })
        $newToken = $tokenPart1 + $tokenPart2
    }

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


    $Body = @{
        temporary_tokens = @(
            @{
                username = $Username
                temporary_token = $newToken
                count_of_max_auth = $MaximumUses
                expiry_date = $expiryTimestamp
            }
        )
    }

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

    if ($RawRequest) {
        Set-Variable -Name $RawRequest -Value $apiResult -Scope 1
    }

    $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 1
    }

    if ($apiResult.records_created.Count -gt 0) {
        $expiryDate = ([System.DateTimeOffset]::FromUnixTimeSeconds($expiryTimestamp)).LocalDateTime
        Write-Host "Assigned temporary token $newToken to user $Username. Valid for $MaximumUses uses, expires on $expiryDate."
        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
    }
}