Private/Database.ps1


function Open-Database {
    # Generate a credential by decrypting the Phrase.pwd file with its matching AES.key file.
    # The decrypted phrase is then marshalled into text for use in the connection string.
    Try {
        $phrase = Get-Content "$PSScriptRoot\Phrase.pwd" | ConvertTo-SecureString -Key (Get-Content $Global:configuration.AESKey) -ErrorAction SilentlyContinue
        $bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($phrase)
        $phrase = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)
    }
    Catch {
        Write-Console -Message 'The key pair could not be properly validated.' -Color 'Red'
        Return $NULL
    }
    $database = New-Object System.Data.SqlClient.SqlConnection
    $database.ConnectionString = "Server=tcp:nanite.database.windows.net,1433;Initial Catalog=nanite;Persist Security Info=False;User ID=nanite_service;Password=$phrase;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
    Try {
        $database.Open()
        Return $database
    }
    Catch {
        Return $NULL
    }
}

function Invoke-Database {
    param (
        [Parameter(
            Mandatory = $FALSE
        )][string]$query
    )
    $command = $Global:database.CreateCommand()
    $command.CommandText = $query
    $adapter = New-Object System.Data.SqlClient.SqlDataAdapter $command
    $data = New-Object System.Data.DataSet
    $adapter.Fill($data)
    Return $data
}

function Add-Log {
    param (
        [Parameter(
            Mandatory = $FALSE
        )][int]$operation
    )
    $currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
    $tokens = $currentUser.Split('\')
    $query = "
        INSERT INTO [dbo].[logs]
            (
                [domain],
                [username],
                [operation]
            )
        VALUES
            (
                @domain,
                @username,
                @operation
            )
    "

    $command = $database.CreateCommand()
    $command.CommandText = $query
    $null = $command.Parameters.Add('@domain', $tokens[0])
    $null = $command.Parameters.Add('@username', $tokens[1])
    $null = $command.Parameters.Add('@operation', $operation)
    $null = $command.ExecuteNonQuery()
}